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(reminders): write a secret update and its reminder in one transaction
Calvin71b5c9b25bb0
diff --git a/backend/e2e-test/routes/v1/secret-reminder.spec.ts b/backend/e2e-test/routes/v1/secret-reminder.spec.tsindex 3357aff2c0..ae94f744a2 100644--- a/backend/e2e-test/routes/v1/secret-reminder.spec.ts+++ b/backend/e2e-test/routes/v1/secret-reminder.spec.ts@@ -1,4 +1,4 @@-import { OrgMembershipRole, ProjectMembershipRole } from "@app/db/schemas";+import { OrgMembershipRole, ProjectMembershipRole, SecretType } from "@app/db/schemas";import { up as migrateRemindersToAlerts } from "../../../src/db/migrations/20260929130000_migrate-secret-reminders-to-alerts";import { updateAlert } from "../../testUtils/alerts";@@ -346,6 +346,44 @@ describe("Secret reminders delivered through alerts", () => {expect(await getSecretReminder({ secretId, authToken })).toBeNull();});+ // The reminder provider only accepts reminders on shared secrets. That check belongs to the alert+ // module, so this shows a refusal from it now fails the whole update before the secret is written.+ test("a secret update whose reminder the alert module refuses leaves the secret unchanged", async () => {+ await createSecret("PERSONAL_REMINDER");+ await createSecretV2({+ workspaceId: projectId,+ environmentSlug: ENVIRONMENT,+ secretPath: "/",+ key: "PERSONAL_REMINDER",+ value: "personal",+ type: SecretType.Personal,+ authToken+ });++ await updateSecretV2({+ workspaceId: projectId,+ environmentSlug: ENVIRONMENT,+ secretPath: "/",+ key: "PERSONAL_REMINDER",+ value: "changed",+ type: SecretType.Personal,+ reminder: { repeatDays: 14 },+ authToken+ }).expect((res) => {+ expect(res.statusCode).toBe(400);+ expect(res.json<{ message: string }>().message).toMatch(/Reminders can only be set on shared secrets/);+ });++ const res = await testServer.inject({+ method: "GET",+ url: "/api/v3/secrets/raw/PERSONAL_REMINDER",+ headers: { authorization: `Bearer ${authToken}` },+ query: { workspaceId: projectId, environment: ENVIRONMENT, secretPath: "/", type: SecretType.Personal }+ });+ expect(res.statusCode).toBe(200);+ expect(res.json<{ secret: { secretValue: string } }>().secret.secretValue).toBe("personal");+ });+test("deleting a reminder removes its alert, channels and recipients", async () => {const secretId = await createSecret("DELETE_ME");await setSecretReminder({ secretId, authToken, repeatDays: 30, recipients: [member.userId] });diff --git a/backend/src/services/alert/alert-channel-service-types.ts b/backend/src/services/alert/alert-channel-service-types.tsindex ef7b072317..3c411fa482 100644--- a/backend/src/services/alert/alert-channel-service-types.ts+++ b/backend/src/services/alert/alert-channel-service-types.ts@@ -25,3 +25,25 @@ export type TAlertChannelInput = {enabled?: boolean;recipients?: TChannelRecipientInput[];};++// A channel write that has passed every check and had its config encrypted. Applying it is plain inserts+// and updates, so it can join a caller's transaction without a KMS call or a validation read inside it.+export type TPreparedChannelCreate = {+ row: {+ name: string;+ channelType: string;+ encryptedConfig: Buffer;+ enabled: boolean;+ orgId: string;+ projectId: string | null;+ createdByActorId: string | null;+ createdByActorType: string;+ };+ recipients: TChannelRecipientInput[];+};++export type TPreparedChannelUpdate = {+ channelId: string;+ patch: { name?: string; enabled?: boolean; encryptedConfig?: Buffer };+ recipients?: TChannelRecipientInput[];+};diff --git a/backend/src/services/alert/alert-channel-service.ts b/backend/src/services/alert/alert-channel-service.tsindex 94e31795d9..cfb5d6734c 100644--- a/backend/src/services/alert/alert-channel-service.ts+++ b/backend/src/services/alert/alert-channel-service.ts@@ -21,7 +21,12 @@ import {} from "./alert-channel-crypto-fns";import { TAlertChannelDALFactory } from "./alert-channel-dal";import { TAlertChannelRecipientDALFactory } from "./alert-channel-recipient-dal";-import { TAlertChannelEmbedded, TChannelRecipientInput } from "./alert-channel-service-types";+import {+ TAlertChannelEmbedded,+ TChannelRecipientInput,+ TPreparedChannelCreate,+ TPreparedChannelUpdate+} from "./alert-channel-service-types";import { AlertChannelType } from "./alert-channel-types";import { findVerifiedEmailDomains, isOnVerifiedDomain, resolvePrincipalsInScope } from "./alert-principal-scope-fns";import { AlertPrincipalType, TAlertRecipientScope } from "./alert-types";@@ -206,19 +211,19 @@ export const alertChannelServiceFactory = ({return redacted;};- const createChannelInTx = async (+ const prepareChannelCreate = async (input: TCreateChannelInTxInput,encryptor: TAlertEncryptor,- tx: Knex- ): Promise<TAlertChannels> => {+ tx?: Knex+ ): Promise<TPreparedChannelCreate> => {const definition = getChannelDefinition(input.channelType);const recipients = input.recipients ?? [];$assertRecipientRules(definition, input.channelType, recipients);assertChannelConfigValid(definition, input.channelType, input.config);await validateRecipients(input.orgId, input.recipientScope, recipients, tx);- const created = await alertChannelDAL.create(- {+ return {+ row: {name: input.name,channelType: input.channelType,encryptedConfig: encryptChannelConfig(input.config, encryptor),@@ -228,24 +233,37 @@ export const alertChannelServiceFactory = ({createdByActorId: input.createdByActorId,createdByActorType: input.createdByActorType},- tx- );+ recipients+ };+ };- if (recipients.length) {+ const applyChannelCreate = async (prepared: TPreparedChannelCreate, tx: Knex): Promise<TAlertChannels> => {+ const created = await alertChannelDAL.create(prepared.row, tx);+ if (prepared.recipients.length) {await alertChannelRecipientDAL.insertMany(- recipients.map((r) => ({ channelId: created.id, principalType: r.principalType, principalId: r.principalId })),+ prepared.recipients.map((r) => ({+ channelId: created.id,+ principalType: r.principalType,+ principalId: r.principalId+ })),tx);}return created;};- const updateChannelInTx = async (+ const createChannelInTx = async (+ input: TCreateChannelInTxInput,+ encryptor: TAlertEncryptor,+ tx: Knex+ ): Promise<TAlertChannels> => applyChannelCreate(await prepareChannelCreate(input, encryptor, tx), tx);++ const prepareChannelUpdate = async (input: TUpdateChannelInTxInput,channel: TAlertChannels,cipher: { encryptor: TAlertEncryptor; decryptor: TAlertDecryptor },- tx: Knex- ): Promise<void> => {+ tx?: Knex+ ): Promise<TPreparedChannelUpdate> => {if (input.channelType !== undefined && input.channelType !== channel.channelType) {throw new BadRequestError({message: `Channel '${channel.id}' is a ${channel.channelType} channel and its type cannot be changed to ${input.channelType}`@@ -268,22 +286,26 @@ export const alertChannelServiceFactory = ({await validateRecipients(channel.orgId, input.recipientScope, recipients, tx);}- await alertChannelDAL.updateById(- channel.id,- {+ return {+ channelId: channel.id,+ patch: {...(input.name !== undefined ? { name: input.name } : {}),...(input.enabled !== undefined ? { enabled: input.enabled } : {}),...(input.config !== undefined ? { encryptedConfig: encryptChannelConfig(finalConfig, cipher.encryptor) } : {})},- tx- );+ recipients+ };+ };- if (recipients !== undefined) {- await alertChannelRecipientDAL.deleteByChannelId(channel.id, tx);- if (recipients.length) {+ const applyChannelUpdate = async (prepared: TPreparedChannelUpdate, tx: Knex): Promise<void> => {+ await alertChannelDAL.updateById(prepared.channelId, prepared.patch, tx);++ if (prepared.recipients !== undefined) {+ await alertChannelRecipientDAL.deleteByChannelId(prepared.channelId, tx);+ if (prepared.recipients.length) {await alertChannelRecipientDAL.insertMany(- recipients.map((r) => ({- channelId: channel.id,+ prepared.recipients.map((r) => ({+ channelId: prepared.channelId,principalType: r.principalType,principalId: r.principalId})),@@ -293,6 +315,13 @@ export const alertChannelServiceFactory = ({}};+ const updateChannelInTx = async (+ input: TUpdateChannelInTxInput,+ channel: TAlertChannels,+ cipher: { encryptor: TAlertEncryptor; decryptor: TAlertDecryptor },+ tx: Knex+ ): Promise<void> => applyChannelUpdate(await prepareChannelUpdate(input, channel, cipher, tx), tx);+// For callers that carry recipient lists from outside the alert module (eg reminder recipients that// were never pruned when someone left the project), where an out-of-scope id should be dropped// rather than fail the whole write.@@ -361,6 +390,10 @@ export const alertChannelServiceFactory = ({return {createChannelInTx,updateChannelInTx,+ prepareChannelCreate,+ applyChannelCreate,+ prepareChannelUpdate,+ applyChannelUpdate,deleteChannelInTx,getDetailsForChannels,validateRecipients,diff --git a/backend/src/services/alert/alert-service-types.ts b/backend/src/services/alert/alert-service-types.tsindex ece666da33..86501b130e 100644--- a/backend/src/services/alert/alert-service-types.ts+++ b/backend/src/services/alert/alert-service-types.ts@@ -1,6 +1,13 @@+import { TAlerts, TAlertsInsert } from "@app/db/schemas";import { TGenericPermission } from "@app/lib/types";-import { TAlertChannelEmbedded, TAlertChannelInput, TChannelRecipientInput } from "./alert-channel-service-types";+import {+ TAlertChannelEmbedded,+ TAlertChannelInput,+ TChannelRecipientInput,+ TPreparedChannelCreate,+ TPreparedChannelUpdate+} from "./alert-channel-service-types";import { AlertChannelType } from "./alert-channel-types";import { AlertRunStatus } from "./alert-types";@@ -85,3 +92,21 @@ export type TAlertLastRun = {timestamp: Date;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[];+ };diff --git a/backend/src/services/alert/alert-service.test.ts b/backend/src/services/alert/alert-service.test.tsindex 18d32b8e93..7998358498 100644--- a/backend/src/services/alert/alert-service.test.ts+++ b/backend/src/services/alert/alert-service.test.ts@@ -159,17 +159,21 @@ const buildService = (opts?: {return data;}},+ // Prepared writes are the inputs passed straight through, so applying one is where a row appears.alertChannelService: {- createChannelInTx: async (input: {+ prepareChannelCreate: async (input: { recipientScope: { projectId: string | null } }) => {+ recipientProjectIds.push(input.recipientScope.projectId);+ return input;+ },+ prepareChannelUpdate: async (input: unknown) => input,+ applyChannelCreate: async (input: {name: string;channelType: AlertChannelType | string;enabled?: boolean;recipients?: { principalType: string; principalId: string }[];orgId: string;projectId?: string | null;- recipientScope: { projectId: string | null };}) => {- recipientProjectIds.push(input.recipientScope.projectId);channelSeq += 1;const row: TChannelRow = {id: `ch-${channelSeq}`,@@ -185,7 +189,7 @@ const buildService = (opts?: {channels.set(row.id, row);return row;},- updateChannelInTx: async (input: {+ applyChannelUpdate: async (input: {channelId: string;name?: string;enabled?: boolean;@@ -484,6 +488,34 @@ describe("alert service", () => {expect(gatedChannelTypeCalls.at(-1)).toEqual([]);});+ test("refuses more channels than an alert can hold", async () => {+ const { service } = buildService();+ 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"+ );++ await service.createAlert(validCreate);+ 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("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);++ await service.applyAlertWrite(plan, {} as never);+ expect(alerts.size).toBe(1);+ expect(channels.size).toBe(2);+ });+test("update rejects an empty channel list", async () => {const { service } = buildService();await service.createAlert(validCreate);diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.tsindex 0aacc24746..c9d07a4f57 100644--- a/backend/src/services/alert/alert-service.ts+++ b/backend/src/services/alert/alert-service.ts@@ -13,7 +13,12 @@ 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, TChannelRecipientInput } from "./alert-channel-service-types";+import {+ TAlertChannelEmbedded,+ TChannelRecipientInput,+ TPreparedChannelCreate,+ TPreparedChannelUpdate+} from "./alert-channel-service-types";import { TAlertDALFactory } from "./alert-dal";import { TAlertHistoryDALFactory } from "./alert-history-dal";import { getRecipientScope } from "./alert-principal-scope-fns";@@ -21,6 +26,7 @@ import { getAlertResourceName, resolveAlertProjectId, TAlertProviderRegistry } fimport {TAlertLastRun,TAlertResponse,+ TAlertWritePlan,TCreateAlertDTO,TDeleteAlertDTO,TGetAlertDTO,@@ -33,9 +39,9 @@ import {AlertRunStatus,AlertTelemetryAction,IResourceAlertProvider,+ MAX_CHANNELS_PER_ALERT,TAlertAuditInput,TAlertEventDefinition,- TAlertRecipientScope,toAlertActor} from "./alert-types";@@ -46,8 +52,10 @@ export type TAlertServiceFactoryDep = {alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "findByChannelIds" | "insertMany">;alertChannelService: Pick<TAlertChannelServiceFactory,- | "createChannelInTx"- | "updateChannelInTx"+ | "prepareChannelCreate"+ | "applyChannelCreate"+ | "prepareChannelUpdate"+ | "applyChannelUpdate"| "deleteChannelInTx"| "getDetailsForChannels"| "filterRecipientsInScope"@@ -140,6 +148,14 @@ export const alertServiceFactory = ({}};+ const $assertChannelCount = (count: number) => {+ if (count > MAX_CHANNELS_PER_ALERT) {+ throw new BadRequestError({+ message: `An alert can have at most ${MAX_CHANNELS_PER_ALERT} channels, and this would leave it with ${count}`+ });+ }+ };+const $getResourceNames = async (provider: IResourceAlertProvider,orgId: string,@@ -190,7 +206,7 @@ export const alertServiceFactory = ({updatedAt: alert.updatedAt});- const createAlert = async (dto: TCreateAlertDTO): Promise<TAlertResponse> => {+ const $prepareCreate = async (dto: TCreateAlertDTO) => {if (!dto.resourceId) {throw new BadRequestError({message:@@ -239,6 +255,7 @@ export const alertServiceFactory = ({if (!dto.channels || dto.channels.length === 0) {throw new BadRequestError({ message: "At least one channel is required" });}+ $assertChannelCount(dto.channels.length);await provider.assertChannelTypesAllowed?.({orgId: dto.actorOrgId,@@ -247,27 +264,165 @@ export const alertServiceFactory = ({const scope = { orgId: dto.actorOrgId, projectId: projectId ?? null };const cipher = await getAlertChannelCipher(kmsService, scope);+ const recipientScope = getRecipientScope(provider, projectId);- const { created, channels } = await alertDAL.transaction(async (tx) => {+ const channels: TPreparedChannelCreate[] = [];+ for (const channelInput of dto.channels) {+ // 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: dto.actorOrgId,+ projectId: projectId ?? null,+ recipientScope,+ createdByActorId: dto.actorId,+ createdByActorType: dto.actor+ },+ 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,+ 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);+ 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)+ .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.enabled !== undefined ? { enabled: dto.enabled } : {})+ },+ deleteChannelIds,+ channelUpdates,+ channelCreates+ };+ 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> => {+ if (plan.kind === "create") {let createdAlert: TAlerts;try {- createdAlert = await alertDAL.create(- {- 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,- enabled: dto.enabled ?? true,- orgId: dto.actorOrgId,- projectId,- createdByActorId: dto.actorId,- createdByActorType: dto.actor- },- tx- );+ createdAlert = await alertDAL.create(plan.alert, tx);} catch (err) {// findScopedDuplicate reads the replica, so two concurrent creates can both pass it.if (@@ -278,29 +433,43 @@ export const alertServiceFactory = ({}throw err;}-- for (const channelInput of dto.channels) {+ 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);}+ return createdAlert;+ }++ const updatedAlert =+ Object.keys(plan.patch).length > 0 ? await alertDAL.updateById(plan.alert.id, plan.patch, tx) : plan.alert;+ for (const channelId of plan.deleteChannelIds) {+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial+ await alertChannelService.deleteChannelInTx(channelId, tx);+ }+ for (const prepared of plan.channelUpdates) {+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial+ await alertChannelService.applyChannelUpdate(prepared, tx);+ }+ for (const prepared of plan.channelCreates) {+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial+ const channel = await alertChannelService.applyChannelCreate(prepared, tx);+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial+ await alertChannelMembershipDAL.insertMany([{ alertId: plan.alert.id, channelId: channel.id }], tx);+ }+ return updatedAlert;+ };++ const prepareCreateAlert = async (dto: TCreateAlertDTO): Promise<TAlertWritePlan> => (await $prepareCreate(dto)).plan;++ const prepareUpdateAlert = async (dto: TUpdateAlertDTO): Promise<TAlertWritePlan> => (await $prepareUpdate(dto)).plan;++ 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 attachedChannels = await alertChannelDAL.findByAlertId(createdAlert.id, {}, tx);const details = await alertChannelService.getDetailsForChannels(attachedChannels, cipher, tx);return { created: createdAlert, channels: details };@@ -393,128 +562,20 @@ export const alertServiceFactory = ({);};- const $reconcileChannels = async (- recipientScope: TAlertRecipientScope,- alert: TAlerts,- incoming: TAlertChannelInput[],- cipher: Awaited<ReturnType<typeof getAlertChannelCipher>>,- tx: Knex- ) => {- const existing = await alertChannelDAL.findByAlertId(alert.id, {}, tx);- const existingById = new Map<string, TAlertChannels>(existing.map((channel) => [channel.id, channel]));-- const incomingIds = new Set(incoming.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` });- }- }-- const toDelete = existing.filter((channel) => !incomingIds.has(channel.id));- for (const channel of toDelete) {- // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial- await alertChannelService.deleteChannelInTx(channel.id, tx);- }-- for (const channelInput of incoming) {- if (channelInput.id) {- const existingChannel = existingById.get(channelInput.id) as TAlertChannels;- // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial- await alertChannelService.updateChannelInTx(- {- channelId: channelInput.id,- channelType: channelInput.channelType,- name: channelInput.name,- config: channelInput.config,- enabled: channelInput.enabled,- recipients: channelInput.recipients,- recipientScope- },- existingChannel,- cipher,- tx- );- } else {- // 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: alert.orgId,- projectId: alert.projectId,- recipientScope,- createdByActorId: alert.createdByActorId ?? null,- createdByActorType: alert.createdByActorType- },- cipher.encryptor,- tx- );- // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial- await alertChannelMembershipDAL.insertMany([{ alertId: alert.id, channelId: channel.id }], tx);- }- }- };-const updateAlert = async (dto: TUpdateAlertDTO): Promise<TAlertResponse> => {- 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);- if (dto.channels !== undefined && dto.channels.length === 0) {- throw new BadRequestError({ message: "At least one channel is required" });- }-- if (dto.channels && provider.assertChannelTypesAllowed) {- const existingTypeById = new Map(- (await alertChannelDAL.findByAlertId(alert.id)).map((channel) => [channel.id, channel.channelType])- );- await provider.assertChannelTypesAllowed({- orgId: alert.orgId,- channelTypes: dto.channels- .filter((channel) => !channel.id || existingTypeById.get(channel.id) !== channel.channelType)- .map((channel) => channel.channelType)- });- }-- const scope = { orgId: alert.orgId, projectId: alert.projectId };- const cipher = await getAlertChannelCipher(kmsService, scope);+ const { plan, provider, cipher } = await $prepareUpdate(dto);const { updated, channels } = await alertDAL.transaction(async (tx) => {- const 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.enabled !== undefined ? { enabled: dto.enabled } : {})- };-- const updatedAlert = Object.keys(patch).length > 0 ? await alertDAL.updateById(alert.id, patch, tx) : alert;-- if (dto.channels !== undefined) {- await $reconcileChannels(getRecipientScope(provider, alert.projectId), alert, dto.channels, cipher, tx);- }-- const attachedChannels = await alertChannelDAL.findByAlertId(alert.id, {}, tx);+ const updatedAlert = await applyAlertWrite(plan, tx);+ const attachedChannels = await alertChannelDAL.findByAlertId(updatedAlert.id, {}, tx);const details = await alertChannelService.getDetailsForChannels(attachedChannels, cipher, tx);return { updated: updatedAlert, channels: details };});- const lastRuns = await $getLastRuns(provider, [alert.id]);+ const lastRuns = await $getLastRuns(provider, [updated.id]);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)});};@@ -726,6 +787,9 @@ export const alertServiceFactory = ({getTelemetryEvent,getAuditEvent,createAlert,+ prepareCreateAlert,+ prepareUpdateAlert,+ applyAlertWrite,getAlertById,listAlerts,updateAlert,diff --git a/backend/src/services/reminder/reminder-service.test.ts b/backend/src/services/reminder/reminder-service.test.tsindex daee9f7e2d..7deed62867 100644--- a/backend/src/services/reminder/reminder-service.test.ts+++ b/backend/src/services/reminder/reminder-service.test.ts@@ -207,7 +207,9 @@ type TStoredAlert = {}>;};-const buildWriteService = (opts: { existingAlert?: TStoredAlert; projectUserIds?: string[] } = {}) => {+const buildWriteService = (+ opts: { existingAlert?: TStoredAlert; projectUserIds?: string[]; alertRefusal?: Error } = {}+) => {const calls: string[] = [];const created: unknown[] = [];const updated: Array<{ alertId: string; name?: string; channels?: unknown[] }> = [];@@ -215,11 +217,16 @@ const buildWriteService = (opts: { existingAlert?: TStoredAlert; projectUserIds?const deletedAlerts: Array<{ resourceIds: string[]; tx: unknown }> = [];const repointed: Array<{ fromResourceId: string; toResourceId: string; tx: unknown }> = [];+ const reminderTx = { tx: "reminder" };+ const writeTxs: unknown[] = [];+const service = reminderServiceFactory({reminderDAL: {+ transaction: async (cb: (trx: unknown) => unknown) => cb(reminderTx),findOne: async () => undefined,- create: async (data: Record<string, unknown>) => {+ create: async (data: Record<string, unknown>, trx?: unknown) => {calls.push("reminder:create");+ writeTxs.push(trx);return { id: "rem-1", ...data };},updateById: async () => ({}),@@ -248,15 +255,27 @@ const buildWriteService = (opts: { existingAlert?: TStoredAlert; projectUserIds?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] : []),- createAlert: async (input: unknown) => {- calls.push("alert:create");+ prepareCreateAlert: async (input: unknown) => {+ if (opts.alertRefusal) throw opts.alertRefusal;created.push(input);- return input;+ return { kind: "create" };},- updateAlert: async ({ alertId, name, channels }: { alertId: string; name?: string; channels?: unknown[] }) => {- calls.push("alert:update");+ prepareUpdateAlert: async ({+ alertId,+ name,+ channels+ }: {+ alertId: string;+ name?: string;+ channels?: unknown[];+ }) => {+ if (opts.alertRefusal) throw opts.alertRefusal;updated.push({ alertId, name, channels });- return { alertId, name, channels };+ return { kind: "update" };+ },+ applyAlertWrite: async (_plan: unknown, trx: unknown) => {+ calls.push("alert:apply");+ writeTxs.push(trx);},findRecipientsForResources: async ({ resourceIds }: { resourceIds: string[] }) =>resourceIds.map((resourceId) => ({ resourceId, principalId: "user-1" })),@@ -276,14 +295,14 @@ const buildWriteService = (opts: { existingAlert?: TStoredAlert; projectUserIds?}} as never);- return { service, calls, created, updated, deletedAlerts, repointed, copied };+ return { service, calls, created, updated, deletedAlerts, repointed, copied, reminderTx, writeTxs };};const caller = { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null };const saveReminder = (service: ReturnType<typeof buildWriteService>["service"],- fields: { recipients?: string[] | null; resolvedRecipients?: unknown[]; channels?: unknown[] }+ fields: { recipients?: string[] | null; channels?: unknown[] }) =>service.createReminder({...caller,@@ -317,10 +336,44 @@ describe("reminder alert sync", () => {]);});- test("syncs the alert before writing the reminder, so a reminder never exists without one", async () => {- const { service, calls } = buildWriteService();+ test("writes the alert and the reminder in one transaction, so neither exists without the other", async () => {+ const { service, calls, reminderTx, writeTxs } = buildWriteService();await saveReminder(service, { recipients: ["user-1"] });- expect(calls).toEqual(["alert:create", "reminder:create"]);+ expect(calls).toEqual(["alert:apply", "reminder:create"]);+ expect(writeTxs).toEqual([reminderTx, reminderTx]);+ });++ test("a refusal from the alert module stops the reminder before anything is written", async () => {+ const { service, calls } = buildWriteService({+ alertRefusal: new Error("An alert can have at most 10 channels, and this would leave it with 11")+ });+ await expect(saveReminder(service, { recipients: ["user-1"] })).rejects.toThrow(/at most 10 channels/);+ expect(calls).toEqual([]);+ });++ test("preparing a reminder writes nothing until it is applied in the caller's transaction", async () => {+ const { service, calls, writeTxs } = buildWriteService();+ const callerTx = { tx: "secret-update" } as never;+ const prepared = await service.prepareReminder({+ ...caller,+ secretKey: "RENAMED",+ reminder: { secretId: "secret-1", repeatDays: 30, recipients: ["user-1"] }+ } as never);+ expect(calls).toEqual([]);++ await service.applyReminder(prepared, callerTx);+ expect(calls).toEqual(["alert:apply", "reminder:create"]);+ expect(writeTxs).toEqual([callerTx, callerTx]);+ });++ test("a rename in the same request names the alert after the new key", async () => {+ const { service, created } = 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" })]);});test("no recipients means everyone in the project", async () => {@@ -347,56 +400,6 @@ describe("reminder alert sync", () => {expect(calls).toEqual([]);});- test("recipients a caller already resolved are used as given, without a second membership check", async () => {- const { service, created } = buildWriteService({ projectUserIds: [] });- await saveReminder(service, { resolvedRecipients: [{ principalType: "user", principalId: "user-1" }] });- expect((created[0] as { channels: { recipients: unknown }[] }).channels[0].recipients).toEqual([- { principalType: "user", principalId: "user-1" }- ]);- });-- test("resolving recipients refuses a list with nobody left in the project", async () => {- const { service } = buildWriteService({ projectUserIds: [] });- await expect(- service.resolveReminderRecipients({- actorOrgId: "org-1",- projectId: "proj-1",- secretId: "secret-1",- recipients: ["user-gone"]- })- ).rejects.toThrow(/None of the selected reminder recipients/);- });-- test("refuses more email recipients than fit beside the alert's other channels", async () => {- const webhookOnly = {- id: "alert-1",- name: "Reminder for DB_PASSWORD",- resourceId: "secret-1",- channels: [{ id: "ch-hook", name: "Webhook", channelType: "webhook", enabled: true }]- };- const { service, calls } = buildWriteService({ existingAlert: webhookOnly });- const recipients = Array.from({ length: 200 }, (_, i) => `user-${i}`);-- await expect(saveReminder(service, { recipients })).rejects.toThrow(- "This reminder already sends to 1 other channels, so it can email at most 180 recipients."- );- expect(calls).toEqual([]);- });-- test("accepts as many email recipients as fit beside the alert's other channels", async () => {- const webhookOnly = {- id: "alert-1",- name: "Reminder for DB_PASSWORD",- resourceId: "secret-1",- channels: [{ id: "ch-hook", name: "Webhook", channelType: "webhook", enabled: true }]- };- const { service, updated } = buildWriteService({ existingAlert: webhookOnly });- const recipients = Array.from({ length: 180 }, (_, i) => `user-${i}`);-- await saveReminder(service, { recipients });- expect(updated[0].channels).toHaveLength(10);- });-test("given channels, saves them as the alert's complete channel list", async () => {const channels = [{diff --git a/backend/src/services/reminder/reminder-service.ts b/backend/src/services/reminder/reminder-service.tsindex a49bb0dec3..0a730c7e1a 100644--- a/backend/src/services/reminder/reminder-service.ts+++ b/backend/src/services/reminder/reminder-service.ts@@ -13,7 +13,8 @@ import { TGenericPermission } from "@app/lib/types";import { TAlertChannelInput, TChannelRecipientInput } from "../alert/alert-channel-service-types";import { AlertChannelType } from "../alert/alert-channel-types";import { TAlertServiceFactory } from "../alert/alert-service";-import { AlertPrincipalType, MAX_CHANNELS_PER_ALERT, MAX_RECIPIENTS_PER_CHANNEL } from "../alert/alert-types";+import { TAlertWritePlan } from "../alert/alert-service-types";+import { AlertPrincipalType, MAX_RECIPIENTS_PER_CHANNEL } 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";@@ -34,8 +35,9 @@ type TReminderServiceFactoryDep = {eventEmitter: TEventEmitter;alertService: Pick<TAlertServiceFactory,- | "createAlert"- | "updateAlert"+ | "prepareCreateAlert"+ | "prepareUpdateAlert"+ | "applyAlertWrite"| "findAlertChannelSummariesForResources"| "findRecipientsForResources"| "deleteAlertsForDeletedResources"@@ -80,18 +82,20 @@ export const reminderServiceFactory = ({};// Who a reminder's email goes to. An empty list keeps the reminder's original meaning: everyone in the- // project. Exposed so a caller that writes something else first (a secret update) can refuse the- // request before that write instead of after it has committed.- const resolveReminderRecipients: TReminderServiceFactory["resolveReminderRecipients"] = async ({- actorOrgId,+ // project.+ const $resolveEmailRecipients = async ({+ orgId,projectId,- secretId,recipients- }) => {+ }: {+ orgId: string;+ projectId: string;+ recipients?: string[] | null;+ }): Promise<TChannelRecipientInput[]> => {// Reminder recipients were never pruned when someone left the project, so drop them rather than fail.const requested = [...new Set(recipients ?? [])];const inScope = await alertService.filterRecipientsInScope(- { orgId: actorOrgId, projectId },+ { orgId, projectId },requested.map((principalId) => ({ principalType: AlertPrincipalType.USER, principalId })));// Falling back to the whole project here would send the secret's key, path and note to people nobody@@ -101,81 +105,56 @@ export const reminderServiceFactory = ({message: "None of the selected reminder recipients are members of this project. Choose recipients again."});}- const emailRecipients: TChannelRecipientInput[] = inScope.length- ? inScope- : [{ principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: projectId }];-- // The email channels sit beside the alert's other channels (Slack, webhook, PagerDuty), and the alert- // API refuses to save more than MAX_CHANNELS_PER_ALERT in total. Writing past it here would leave an- // alert nobody can edit until a channel is removed.- const [existing] = await alertService.findAlertChannelSummariesForResources({- resourceType: SECRET_REMINDER_RESOURCE_TYPE,- resourceIds: [secretId]- });- const otherChannelCount =- existing?.channels.filter((channel) => channel.channelType !== AlertChannelType.EMAIL).length ?? 0;- const emailChannelCount = Math.ceil(emailRecipients.length / MAX_RECIPIENTS_PER_CHANNEL);- if (otherChannelCount + emailChannelCount > MAX_CHANNELS_PER_ALERT) {- const maxRecipients = Math.max(MAX_CHANNELS_PER_ALERT - otherChannelCount, 0) * MAX_RECIPIENTS_PER_CHANNEL;- throw new BadRequestError({- message: `This reminder already sends to ${otherChannelCount} other channels, so it can email at most ${maxRecipients} recipients. Remove recipients or channels and try again.`- });- }-- return emailRecipients;+ 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 written as the caller, so the reminder provider- // checks they can edit the secret.- const $syncReminderAlert = async ({+ // 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,- emailRecipients,+ recipients,channels,actor}: {secretId: string;secretKey: string;projectId: string;- emailRecipients: TChannelRecipientInput[];+ recipients?: string[] | null;channels?: TAlertChannelInput[];actor: TGenericPermission;- }) => {+ }): Promise<TAlertWritePlan> => {const [existing] = await alertService.findAlertChannelSummariesForResources({resourceType: SECRET_REMINDER_RESOURCE_TYPE,resourceIds: [secretId]});- const $writeAlert = async (alertChannels: TAlertChannelInput[]) => {- if (existing) {- await alertService.updateAlert({- alertId: existing.id,- name: reminderAlertName(secretKey),- channels: alertChannels,- ...actor- });- return;- }- await alertService.createAlert({- name: reminderAlertName(secretKey),- resourceType: SECRET_REMINDER_RESOURCE_TYPE,- resourceId: secretId,- eventType: SECRET_REMINDER_DUE_EVENT,- condition: null,- projectId,- channels: alertChannels,- ...actor- });- };+ 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) {- await $writeAlert(channels);- return;- }+ if (channels) return $plan(channels);+ const emailRecipients = await $resolveEmailRecipients({ orgId: actor.actorOrgId, projectId, recipients });const existingEmailChannels =existing?.channels.filter((channel) => channel.channelType === AlertChannelType.EMAIL) ?? [];@@ -199,7 +178,7 @@ export const reminderServiceFactory = ({enabled: channel.enabled}));- await $writeAlert([...emailChannels, ...otherChannels]);+ return $plan([...emailChannels, ...otherChannels]);};const $getSecretForPermissionCheck = async (secretId: string) => {@@ -226,30 +205,14 @@ export const reminderServiceFactory = ({};};- const $saveReminder = async ({- secretId,- secretKey,- message,+ const $schedule = ({repeatDays,nextReminderDate: nextReminderDateInput,- recipients,- resolvedRecipients,- channels,- projectId,- fromDate: fromDateInput,- actor+ fromDate: fromDateInput}: {- secretId: string;- secretKey: string;- message?: string | null;repeatDays?: number | null;nextReminderDate?: string | null;- recipients?: string[] | null;- resolvedRecipients?: TChannelRecipientInput[];- channels?: TAlertChannelInput[];fromDate?: string | null;- projectId: string;- actor: TGenericPermission;}) => {let nextReminderDate;let fromDate;@@ -269,48 +232,21 @@ export const reminderServiceFactory = ({if (!nextReminderDate) {throw new BadRequestError({ message: "repeatDays must be a positive number" });}-- const emailRecipients =- resolvedRecipients ??- (await resolveReminderRecipients({ actorOrgId: actor.actorOrgId, projectId, secretId, recipients }));-- // The alert goes first, outside any transaction because encrypting channel config can call out to- // KMS. If the reminder write then fails, an alert with no reminder never fires and is reused next time.- await $syncReminderAlert({ secretId, secretKey, projectId, emailRecipients, channels, actor });-- const existingReminder = await reminderDAL.findOne({ secretId });- let reminderId: string;-- if (existingReminder) {- await reminderDAL.updateById(existingReminder.id, {- message,- repeatDays,- nextReminderDate,- fromDate- });- reminderId = existingReminder.id;- } else {- const newReminder = await reminderDAL.create({- secretId,- message,- repeatDays,- nextReminderDate,- fromDate- });- reminderId = newReminder.id;- }-- await secretV2BridgeDAL.invalidateSecretCacheByProjectId(projectId);- return { id: reminderId, created: !existingReminder };+ return { nextReminderDate, fromDate };};- const createReminder: TReminderServiceFactory["createReminder"] = async ({+ // Everything that can refuse a reminder runs here, before anything is written: the caller's permission on+ // the secret, the schedule, the recipients, and the alert module's own checks on the reminder's alert. A+ // caller that writes something else in the same request (a secret update) prepares first, so a refused+ // reminder fails the request before that write.+ const prepareReminder: TReminderServiceFactory["prepareReminder"] = async ({actor,actorId,actorOrgId,actorAuthMethod,- reminder- }: TCreateReminderDTO) => {+ reminder,+ secretKey+ }) => {const { secret, subjectFields } = await $getSecretForPermissionCheck(reminder.secretId!);const { permission } = await permissionService.getProjectPermission({actor,@@ -325,13 +261,42 @@ export const reminderServiceFactory = ({subject(ProjectPermissionSub.Secrets, subjectFields));- return $saveReminder({- ...reminder,+ const { nextReminderDate, fromDate } = $schedule(reminder);+ const alertPlan = await $prepareReminderAlert({secretId: secret.id,- secretKey: secret.key,+ secretKey: secretKey ?? secret.key,projectId: secret.projectId,+ recipients: reminder.recipients,+ channels: reminder.channels,actor: { actor, actorId, actorOrgId, actorAuthMethod }});++ return {+ secretId: secret.id,+ projectId: secret.projectId,+ row: { message: reminder.message, repeatDays: reminder.repeatDays, nextReminderDate, fromDate },+ alertPlan+ };+ };++ // 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);++ const existingReminder = await reminderDAL.findOne({ secretId: prepared.secretId }, tx);+ if (existingReminder) {+ await reminderDAL.updateById(existingReminder.id, prepared.row, tx);+ return { id: existingReminder.id, created: false };+ }+ const newReminder = await reminderDAL.create({ secretId: prepared.secretId, ...prepared.row }, tx);+ return { id: newReminder.id, created: true };+ };++ const createReminder: TReminderServiceFactory["createReminder"] = async (dto: TCreateReminderDTO) => {+ const prepared = await prepareReminder(dto);+ const result = await reminderDAL.transaction((tx) => applyReminder(prepared, tx));+ await secretV2BridgeDAL.invalidateSecretCacheByProjectId(prepared.projectId);+ return result;};const getReminder: TReminderServiceFactory["getReminder"] = async ({@@ -607,7 +572,8 @@ export const reminderServiceFactory = ({};return {- resolveReminderRecipients,+ prepareReminder,+ applyReminder,createReminder,getReminder,dispatchDueReminders,diff --git a/backend/src/services/reminder/reminder-types.ts b/backend/src/services/reminder/reminder-types.tsindex 97bc7b4a55..32367ec332 100644--- a/backend/src/services/reminder/reminder-types.ts+++ b/backend/src/services/reminder/reminder-types.ts@@ -1,6 +1,7 @@import { Knex } from "knex";-import { TAlertChannelInput, TChannelRecipientInput } from "../alert/alert-channel-service-types";+import { TAlertChannelInput } from "../alert/alert-channel-service-types";+import { TAlertWritePlan } from "../alert/alert-service-types";import { ActorAuthMethod, ActorType } from "../auth/auth-type";export type TReminder = {@@ -26,12 +27,30 @@ export type TCreateReminderDTO = {fromDate?: string | null;nextReminderDate?: string | null;recipients?: string[] | null;- // From resolveReminderRecipients, for a caller that checked them before its own write.- resolvedRecipients?: TChannelRecipientInput[];channels?: TAlertChannelInput[];};};+export type TPrepareReminderDTO = TCreateReminderDTO & {+ // The key the secret will have once the caller's own write lands (eg a rename in the same update), so+ // the alert is named after it rather than the key being replaced.+ secretKey?: string;+};++// A reminder that has passed every check, ready to be written with applyReminder in the caller's+// transaction.+export type TPreparedReminder = {+ secretId: string;+ projectId: string;+ row: {+ message?: string | null;+ repeatDays?: number | null;+ nextReminderDate: Date;+ fromDate?: Date;+ };+ alertPlan: TAlertWritePlan;+};+export type TBatchCreateReminderDTO = {secretId: string;message?: string | null;@@ -42,12 +61,9 @@ export type TBatchCreateReminderDTO = {}[];export interface TReminderServiceFactory {- resolveReminderRecipients: (input: {- actorOrgId: string;- projectId: string;- secretId: string;- recipients?: string[] | null;- }) => Promise<TChannelRecipientInput[]>;+ prepareReminder: (dto: TPrepareReminderDTO) => Promise<TPreparedReminder>;++ applyReminder: (prepared: TPreparedReminder, tx: Knex) => Promise<{ id: string; created: boolean }>;createReminder: ({ actor, actorId, actorOrgId, actorAuthMethod, reminder }: TCreateReminderDTO) => Promise<{id: string;diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.tsindex bafdd53497..ea442c22dd 100644--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts@@ -189,7 +189,8 @@ type TSecretV2BridgeServiceFactoryDep = {>;reminderService: Pick<TReminderServiceFactory,- | "resolveReminderRecipients"+ | "prepareReminder"+ | "applyReminder"| "createReminder"| "getReminder"| "batchCreateReminders"@@ -798,13 +799,21 @@ export const secretV2BridgeServiceFactory = ({await $validateSecretReferences(projectId, permission, allSecretReferences);}- // A recipient nobody can notify has to fail here, before the secret changes, not after it has committed.- const reminderRecipients = inputSecret.secretReminderRepeatDays- ? await reminderService.resolveReminderRecipients({+ // The secret and its reminder are one change: the reminder is checked before anything is written, then+ // written in the secret's transaction, so either both land or neither does.+ const preparedReminder = inputSecret.secretReminderRepeatDays+ ? await reminderService.prepareReminder({+ actor,+ actorId,actorOrgId,- projectId,- secretId,- recipients: inputSecret.secretReminderRecipients+ actorAuthMethod,+ secretKey: inputSecret.newSecretName || inputSecret.secretName,+ reminder: {+ secretId,+ message: inputSecret.secretReminderNote,+ repeatDays: inputSecret.secretReminderRepeatDays,+ recipients: inputSecret.secretReminderRecipients+ }}): undefined;@@ -869,23 +878,11 @@ export const secretV2BridgeServiceFactory = ({});}+ if (preparedReminder) await reminderService.applyReminder(preparedReminder, tx);+await secretDAL.invalidateSecretCacheByProjectId(projectId, tx);return modifiedSecretsInDB;});- if (inputSecret.secretReminderRepeatDays) {- await reminderService.createReminder({- actor,- actorId,- actorOrgId,- actorAuthMethod,- reminder: {- secretId: secret.id,- message: inputSecret.secretReminderNote,- repeatDays: inputSecret.secretReminderRepeatDays,- resolvedRecipients: reminderRecipients- }- });- }if (inputSecret.type === SecretType.Shared) {await secretQueueService.syncSecrets({