Skip to content

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

fix(reminders): copy the reminder alert when a move leaves the source secret behind

Calvin68ab38bdffed
diff --git a/backend/e2e-test/routes/v1/secret-reminder.spec.ts b/backend/e2e-test/routes/v1/secret-reminder.spec.ts
index f48a13d184..3357aff2c0 100644
--- a/backend/e2e-test/routes/v1/secret-reminder.spec.ts
+++ b/backend/e2e-test/routes/v1/secret-reminder.spec.ts
@@ -14,6 +14,7 @@ import {
setSecretReminder,
waitForReminderEmails
} from "../../testUtils/reminders";
+import { createSecretApprovalPolicy } from "../../testUtils/secret-approval-policies";
import { createSecretV2, getSecretByNameV2, updateSecretV2 } from "../../testUtils/secrets";
import { addUserMembership, createUser, deleteUsers } from "../../testUtils/users";
@@ -182,6 +183,67 @@ describe("Secret reminders delivered through alerts", () => {
expect((await reminderAlerts(moved.id)).map((alert) => alert.id)).toEqual([before.id]);
});
+ // An approval policy on the source folder holds its secrets until the request merges, so for a
+ // while the same reminder lives on two secrets. Both must keep someone to notify.
+ test("moving a secret out of a folder with an approval policy leaves the source its alert and copies it", async () => {
+ await createFolder({
+ workspaceId: projectId,
+ environmentSlug: ENVIRONMENT,
+ secretPath: "/",
+ name: "held",
+ authToken
+ });
+ const sourceId = await createSecret("HELD", { secretPath: "/held" });
+ await setSecretReminder({ secretId: sourceId, authToken, repeatDays: 30, recipients: [member.userId] });
+ const [sourceAlert] = await reminderAlerts(sourceId);
+ await createSecretApprovalPolicy({
+ projectId,
+ environmentSlug: ENVIRONMENT,
+ secretPath: "/held",
+ approverUserIds: [member.userId],
+ authToken
+ });
+
+ const move = await testServer.inject({
+ method: "POST",
+ url: "/api/v4/secrets/move",
+ headers: { authorization: `Bearer ${authToken}` },
+ body: {
+ projectId,
+ sourceEnvironment: ENVIRONMENT,
+ sourceSecretPath: "/held",
+ destinationEnvironment: ENVIRONMENT,
+ destinationSecretPath: "/",
+ secretIds: [sourceId]
+ }
+ });
+ expect(move.statusCode).toBe(200);
+
+ const stillAtSource = await getSecretByNameV2({
+ workspaceId: projectId,
+ environmentSlug: ENVIRONMENT,
+ secretPath: "/held",
+ key: "HELD",
+ authToken
+ });
+ expect(stillAtSource.id).toBe(sourceId);
+ expect((await reminderAlerts(sourceId)).map((alert) => alert.id)).toEqual([sourceAlert.id]);
+
+ const copy = await getSecretByNameV2({
+ workspaceId: projectId,
+ environmentSlug: ENVIRONMENT,
+ secretPath: "/",
+ key: "HELD",
+ authToken
+ });
+ const [copiedAlert] = await reminderAlerts(copy.id);
+ expect(copiedAlert.id).not.toBe(sourceAlert.id);
+ expect(copiedAlert.channels.map((channel) => channel.recipients)).toEqual(
+ sourceAlert.channels.map((channel) => channel.recipients)
+ );
+ expect((await getSecretReminder({ secretId: copy.id, authToken }))?.recipients).toEqual([member.userId]);
+ });
+
test(
"the daily job emails a due reminder and moves its schedule forward",
async () => {
diff --git a/backend/e2e-test/testUtils/secret-approval-policies.ts b/backend/e2e-test/testUtils/secret-approval-policies.ts
new file mode 100644
index 0000000000..cb9216b5f3
--- /dev/null
+++ b/backend/e2e-test/testUtils/secret-approval-policies.ts
@@ -0,0 +1,32 @@
+import { ApproverType } from "@app/ee/services/access-approval-policy/access-approval-policy-types";
+
+import { request } from "./request";
+
+// Reviewers that must sign off before a secret change in a path takes effect. One user approver and
+// one required approval is enough to make a write wait on a request.
+export const createSecretApprovalPolicy = (dto: {
+ projectId: string;
+ environmentSlug: string;
+ secretPath: string;
+ approverUserIds: string[];
+ authToken: string;
+}) =>
+ request(
+ {
+ method: "POST",
+ url: "/api/v1/secret-approvals",
+ headers: { authorization: `Bearer ${dto.authToken}` },
+ body: {
+ workspaceId: dto.projectId,
+ environment: dto.environmentSlug,
+ name: `policy${dto.secretPath.replaceAll("/", "-")}`,
+ secretPath: dto.secretPath,
+ approvers: dto.approverUserIds.map((id) => ({ type: ApproverType.User, id })),
+ approvals: 1
+ }
+ },
+ (res) => {
+ expect(res.statusCode).toBe(200);
+ return res.json<{ approval: { id: string } }>().approval;
+ }
+ );
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 9e8730c610..fa8adc44f5 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1148,6 +1148,7 @@ export const registerRoutes = async (
alertDAL,
alertChannelDAL,
alertChannelMembershipDAL,
+ alertChannelRecipientDAL,
alertChannelService,
kmsService,
alertProviderRegistry
diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.ts
index 93638f43e7..ff8355ce69 100644
--- a/backend/src/services/alert/alert-service.ts
+++ b/backend/src/services/alert/alert-service.ts
@@ -10,6 +10,7 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { 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, TChannelRecipientInput } from "./alert-channel-service-types";
import { TAlertDALFactory } from "./alert-dal";
@@ -27,8 +28,9 @@ import { AlertPermissionAction, IResourceAlertProvider, TAlertEventDefinition, t
export type TAlertServiceFactoryDep = {
alertDAL: TAlertDALFactory;
- alertChannelDAL: Pick<TAlertChannelDALFactory, "findByAlertId" | "findByAlertIds" | "delete">;
+ alertChannelDAL: Pick<TAlertChannelDALFactory, "findByAlertId" | "findByAlertIds" | "delete" | "create">;
alertChannelMembershipDAL: Pick<TAlertChannelMembershipDALFactory, "insertMany">;
+ alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "findByChannelIds" | "insertMany">;
alertChannelService: Pick<
TAlertChannelServiceFactory,
| "createChannelInTx"
@@ -47,6 +49,7 @@ export const alertServiceFactory = ({
alertDAL,
alertChannelDAL,
alertChannelMembershipDAL,
+ alertChannelRecipientDAL,
alertChannelService,
kmsService,
alertProviderRegistry
@@ -495,6 +498,74 @@ export const alertServiceFactory = ({
await alertDAL.update({ resourceType, resourceId: fromResourceId }, { resourceId: toResourceId }, tx);
};
+ // For a resource recreated under a new id while the original stays (eg a secret moved out of a folder
+ // whose approval policy holds the source until the request merges), so both keep working alerts.
+ // Channel configs are copied still encrypted: both ids belong to the same project and share its cipher,
+ // so no KMS call is needed and this is safe inside the caller's transaction.
+ const copyAlertsForResource = async (
+ {
+ resourceType,
+ fromResourceId,
+ toResourceId
+ }: { resourceType: string; fromResourceId: string; toResourceId: string },
+ tx: Knex
+ ): Promise<void> => {
+ const alerts = await alertDAL.find({ resourceType, resourceId: fromResourceId }, { tx });
+ if (alerts.length === 0) return;
+
+ const channels = await alertChannelDAL.findByAlertIds(
+ alerts.map((alert) => alert.id),
+ tx
+ );
+ const recipients = await alertChannelRecipientDAL.findByChannelIds(
+ channels.map((channel) => channel.id),
+ tx
+ );
+
+ for (const alert of alerts) {
+ const { id: alertId, createdAt, updatedAt, condition, ...alertFields } = alert;
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ const copiedAlert = await alertDAL.create(
+ {
+ ...alertFields,
+ resourceId: toResourceId,
+ condition: condition != null ? JSON.stringify(condition) : null
+ },
+ tx
+ );
+ for (const channel of channels.filter((row) => row.alertId === alertId)) {
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ const copiedChannel = await alertChannelDAL.create(
+ {
+ name: channel.name,
+ channelType: channel.channelType,
+ encryptedConfig: channel.encryptedConfig,
+ enabled: channel.enabled,
+ orgId: channel.orgId,
+ projectId: channel.projectId,
+ createdByActorId: channel.createdByActorId,
+ createdByActorType: channel.createdByActorType
+ },
+ tx
+ );
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ await alertChannelMembershipDAL.insertMany([{ alertId: copiedAlert.id, channelId: copiedChannel.id }], tx);
+ const channelRecipients = recipients.filter((recipient) => recipient.channelId === channel.id);
+ if (channelRecipients.length > 0) {
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ await alertChannelRecipientDAL.insertMany(
+ channelRecipients.map(({ principalType, principalId }) => ({
+ channelId: copiedChannel.id,
+ principalType,
+ principalId
+ })),
+ tx
+ );
+ }
+ }
+ }
+ };
+
const findRecipientsForResources = (
input: { resourceType: string; resourceIds: string[]; channelType: string; principalType: string },
tx?: Knex
@@ -517,6 +588,7 @@ export const alertServiceFactory = ({
findAlertChannelSummariesForResources,
deleteAlertsForDeletedResources,
repointAlertsForResource,
+ copyAlertsForResource,
findRecipientsForResources,
filterRecipientsInScope
};
diff --git a/backend/src/services/reminder/reminder-service.test.ts b/backend/src/services/reminder/reminder-service.test.ts
index 9a46dab38e..9c53576957 100644
--- a/backend/src/services/reminder/reminder-service.test.ts
+++ b/backend/src/services/reminder/reminder-service.test.ts
@@ -211,6 +211,7 @@ const buildWriteService = (opts: { existingAlert?: TStoredAlert; projectUserIds?
const calls: string[] = [];
const created: unknown[] = [];
const updated: Array<{ alertId: string; name?: string; channels?: unknown[] }> = [];
+ const copied: unknown[] = [];
const deletedAlerts: Array<{ resourceIds: string[]; tx: unknown }> = [];
const repointed: Array<{ fromResourceId: string; toResourceId: string; tx: unknown }> = [];
@@ -267,11 +268,15 @@ const buildWriteService = (opts: { existingAlert?: TStoredAlert; projectUserIds?
repointAlertsForResource: async (input: { fromResourceId: string; toResourceId: string }, tx: unknown) => {
calls.push("alert:repoint");
repointed.push({ ...input, tx });
+ },
+ copyAlertsForResource: async (input: { fromResourceId: string; toResourceId: string }, tx: unknown) => {
+ calls.push("alert:copy");
+ copied.push({ ...input, tx });
}
}
} as never);
- return { service, calls, created, updated, deletedAlerts, repointed };
+ return { service, calls, created, updated, deletedAlerts, repointed, copied };
};
const caller = { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null };
@@ -439,6 +444,18 @@ describe("reminder alert sync", () => {
]);
});
+ test("copying reminder alerts clears the destination's alert, then copies the source alert onto it", async () => {
+ const { service, calls, repointed, copied } = buildWriteService();
+ const tx = { tx: true } as never;
+ await service.copyReminderAlerts([{ fromSecretId: "secret-src", toSecretId: "secret-dst" }], tx);
+
+ expect(calls).toEqual(["alert:delete", "alert:copy"]);
+ expect(repointed).toEqual([]);
+ expect(copied).toEqual([
+ { resourceType: SECRET_REMINDER_RESOURCE_TYPE, fromResourceId: "secret-src", toResourceId: "secret-dst", tx }
+ ]);
+ });
+
test("dashboard recipients come from the alert, not the old recipients table", async () => {
const { service } = buildWriteService();
const reminders = await service.getRemindersForDashboard(["secret-1"]);
diff --git a/backend/src/services/reminder/reminder-service.ts b/backend/src/services/reminder/reminder-service.ts
index ea49099439..a7a4149a85 100644
--- a/backend/src/services/reminder/reminder-service.ts
+++ b/backend/src/services/reminder/reminder-service.ts
@@ -40,6 +40,7 @@ type TReminderServiceFactoryDep = {
| "findRecipientsForResources"
| "deleteAlertsForDeletedResources"
| "repointAlertsForResource"
+ | "copyAlertsForResource"
| "filterRecipientsInScope"
>;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
@@ -527,23 +528,38 @@ export const reminderServiceFactory = ({
};
};
- // Alerts are copied by moving them rather than rebuilding them, so channel secrets (webhook signing
- // keys, PagerDuty integration keys) and send history follow the secret to its new id.
- const moveReminderAlerts: TReminderServiceFactory["moveReminderAlerts"] = async (moves, tx) => {
- if (moves.length === 0) return;
- await alertService.deleteAlertsForDeletedResources(
+ type TReminderAlertMove = { fromSecretId: string; toSecretId: string };
+
+ // A destination secret that already had a reminder loses that reminder in the move, so its alert goes too.
+ const $clearDestinationReminderAlerts = (moves: TReminderAlertMove[], tx: Knex) =>
+ alertService.deleteAlertsForDeletedResources(
{ resourceType: SECRET_REMINDER_RESOURCE_TYPE, resourceIds: moves.map((move) => move.toSecretId) },
tx
);
+
+ const $alertResource = (move: TReminderAlertMove) => ({
+ resourceType: SECRET_REMINDER_RESOURCE_TYPE,
+ fromResourceId: move.fromSecretId,
+ toResourceId: move.toSecretId
+ });
+
+ // For a secret that is deleted at its source. Alerts follow it to its new id rather than being rebuilt,
+ // so channel secrets (webhook signing keys, PagerDuty integration keys) and send history go with it.
+ const moveReminderAlerts: TReminderServiceFactory["moveReminderAlerts"] = async (moves, tx) => {
+ if (moves.length === 0) return;
+ await $clearDestinationReminderAlerts(moves, tx);
+ for (const move of moves) {
+ await alertService.repointAlertsForResource($alertResource(move), tx);
+ }
+ };
+
+ // For a secret that stays at its source as well. Its reminder keeps firing there, so it keeps its alert
+ // and the destination gets its own.
+ const copyReminderAlerts: TReminderServiceFactory["copyReminderAlerts"] = async (moves, tx) => {
+ if (moves.length === 0) return;
+ await $clearDestinationReminderAlerts(moves, tx);
for (const move of moves) {
- await alertService.repointAlertsForResource(
- {
- resourceType: SECRET_REMINDER_RESOURCE_TYPE,
- fromResourceId: move.fromSecretId,
- toResourceId: move.toSecretId
- },
- tx
- );
+ await alertService.copyAlertsForResource($alertResource(move), tx);
}
};
@@ -577,6 +593,7 @@ export const reminderServiceFactory = ({
deleteReminderBySecretId,
batchCreateReminders,
moveReminderAlerts,
+ copyReminderAlerts,
getRemindersForDashboard
};
};
diff --git a/backend/src/services/reminder/reminder-types.ts b/backend/src/services/reminder/reminder-types.ts
index 1cbb3a2588..9126407aec 100644
--- a/backend/src/services/reminder/reminder-types.ts
+++ b/backend/src/services/reminder/reminder-types.ts
@@ -97,5 +97,7 @@ export interface TReminderServiceFactory {
moveReminderAlerts: (moves: { fromSecretId: string; toSecretId: string }[], tx: Knex) => Promise<void>;
+ copyReminderAlerts: (moves: { fromSecretId: string; toSecretId: string }[], tx: Knex) => Promise<void>;
+
getRemindersForDashboard: (secretIds: string[]) => Promise<Record<string, TReminder & { recipients: string[] }>>;
}
diff --git a/backend/src/services/secret-folder/secret-folder-service.ts b/backend/src/services/secret-folder/secret-folder-service.ts
index 17196af669..27c5e4552f 100644
--- a/backend/src/services/secret-folder/secret-folder-service.ts
+++ b/backend/src/services/secret-folder/secret-folder-service.ts
@@ -117,7 +117,7 @@ type TSecretFolderServiceFactoryDep = {
secretImportDAL: Pick<TSecretImportDALFactory, "findImportByFolderIds">;
secretV2BridgeService: Pick<TSecretV2BridgeServiceFactory, "dispatchSecretMoveSideEffects">;
reminderDAL: Pick<TReminderDALFactory, "findSecretReminders" | "delete">;
- reminderService: Pick<TReminderServiceFactory, "batchCreateReminders" | "moveReminderAlerts">;
+ reminderService: Pick<TReminderServiceFactory, "batchCreateReminders" | "moveReminderAlerts" | "copyReminderAlerts">;
keyStore: Pick<TKeyStoreFactory, "acquireLock">;
};
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts
index 78c70ec647..d8d6fb0e66 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts
@@ -1702,6 +1702,14 @@ export const fnSecretMove = async (dto: TFnSecretMove): Promise<TFnSecretMoveRes
const sourceReminders = await reminderDAL.findSecretReminders(secretIds, tx);
const sourceSecretIdToKey = Object.fromEntries(decryptedSourceSecrets.map((s) => [s.id, s.key]));
+ // Looked up before the destination is written, because how the reminders' alerts are carried over
+ // depends on whether the source keeps its secrets.
+ const sourceFolderPolicy = await secretApprovalPolicyService.getSecretApprovalPolicy(
+ projectId,
+ sourceFolder.environment.slug,
+ sourceFolder.path
+ );
+
let isSourceUpdated = false;
let isDestinationUpdated = false;
@@ -1994,10 +2002,14 @@ export const fnSecretMove = async (dto: TFnSecretMove): Promise<TFnSecretMoveRes
remindersToCreate.map(({ sourceSecretId, ...reminder }) => reminder),
tx
);
- await reminderService.moveReminderAlerts(
- remindersToCreate.map((r) => ({ fromSecretId: r.sourceSecretId, toSecretId: r.secretId })),
- tx
- );
+ const alertMoves = remindersToCreate.map((r) => ({ fromSecretId: r.sourceSecretId, toSecretId: r.secretId }));
+ // A source held by an approval policy keeps its secrets, and their reminders, until the request merges,
+ // so those reminders keep their alerts and the destination gets copies.
+ if (shouldApplyPolicy(sourceFolderPolicy, actor)) {
+ await reminderService.copyReminderAlerts(alertMoves, tx);
+ } else {
+ await reminderService.moveReminderAlerts(alertMoves, tx);
+ }
}
isDestinationUpdated = true;
@@ -2007,12 +2019,6 @@ export const fnSecretMove = async (dto: TFnSecretMove): Promise<TFnSecretMoveRes
const sourceSecretsGroupByKey = groupBy(sourceSecrets, (i) => i.key);
const locallyDeletedSecrets = decryptedSourceSecrets.map((el) => ({ ...el, operation: SecretOperations.Delete }));
- const sourceFolderPolicy = await secretApprovalPolicyService.getSecretApprovalPolicy(
- projectId,
- sourceFolder.environment.slug,
- sourceFolder.path
- );
-
if (shouldApplyPolicy(sourceFolderPolicy, actor)) {
// if secret approval policy exists for source, we create the secret approval request
const localSecretsIds = decryptedSourceSecrets.map(({ id }) => id);
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.ts
index 3537c39f4f..fc8617450c 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
@@ -186,7 +186,12 @@ type TSecretV2BridgeServiceFactoryDep = {
>;
reminderService: Pick<
TReminderServiceFactory,
- "resolveReminderRecipients" | "createReminder" | "getReminder" | "batchCreateReminders" | "moveReminderAlerts"
+ | "resolveReminderRecipients"
+ | "createReminder"
+ | "getReminder"
+ | "batchCreateReminders"
+ | "moveReminderAlerts"
+ | "copyReminderAlerts"
>;
reminderDAL: Pick<TReminderDALFactory, "findSecretReminders" | "delete">;
secretValidationRuleService: Pick<TSecretValidationRuleServiceFactory, "validateSecrets">;
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
index c37d725677..d441e393ba 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
@@ -312,7 +312,7 @@ export type TFnSecretMove = {
>;
secretQueueService: Pick<TSecretQueueFactory, "syncSecrets">;
reminderDAL: Pick<TReminderDALFactory, "findSecretReminders" | "delete">;
- reminderService: Pick<TReminderServiceFactory, "batchCreateReminders" | "moveReminderAlerts">;
+ reminderService: Pick<TReminderServiceFactory, "batchCreateReminders" | "moveReminderAlerts" | "copyReminderAlerts">;
};
export type TFnSecretMoveResult = {