Skip to content

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

refactor(reminders): address review on the reminder alert sync

Calvin79156762e7e0
diff --git a/backend/e2e-test/routes/v1/secret-reminder.spec.ts b/backend/e2e-test/routes/v1/secret-reminder.spec.ts
index 860a828e2d..6afbefcdc9 100644
--- a/backend/e2e-test/routes/v1/secret-reminder.spec.ts
+++ b/backend/e2e-test/routes/v1/secret-reminder.spec.ts
@@ -5,6 +5,7 @@ import { updateAlert } from "../../testUtils/alerts";
import { createIsolatedOrgAndProject } from "../../testUtils/fixtures";
import { createFolder, deleteFolder } from "../../testUtils/folders";
import {
+ deleteSecretReminder,
getSecretReminder,
listSecretReminderAlerts,
reapOrphanedReminderAlerts,
@@ -69,6 +70,17 @@ describe("Secret reminders delivered through alerts", () => {
const reminderAlerts = (secretId: string) => listSecretReminderAlerts({ projectId, secretId, authToken });
+ // The alert API cannot show a reaped alert's channels (every read goes through the alert), so the
+ // rows that must go with it are checked directly.
+ const expectAlertFullyRemoved = async (alert: { id: string; channels: { id: string }[] }) => {
+ const channelIds = alert.channels.map((channel) => channel.id);
+ expect(channelIds.length).toBeGreaterThan(0);
+ expect(await testDb("alerts").where({ id: alert.id })).toHaveLength(0);
+ expect(await testDb("alert_channel_memberships").where({ alertId: alert.id })).toHaveLength(0);
+ expect(await testDb("alert_channels").whereIn("id", channelIds)).toHaveLength(0);
+ expect(await testDb("alert_channel_recipients").whereIn("channelId", channelIds)).toHaveLength(0);
+ };
+
const nextReminderDate = async (secretId: string) => {
const reminder = await getSecretReminder({ secretId, authToken });
expect(reminder).not.toBeNull();
@@ -223,7 +235,19 @@ describe("Secret reminders delivered through alerts", () => {
await reapOrphanedReminderAlerts();
- expect(await testDb("alerts").where({ id: alert.id })).toHaveLength(0);
+ await expectAlertFullyRemoved(alert);
+ });
+
+ 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] });
+ const [alert] = await reminderAlerts(secretId);
+
+ await deleteSecretReminder({ secretId, authToken });
+
+ expect(await getSecretReminder({ secretId, authToken })).toBeNull();
+ expect(await reminderAlerts(secretId)).toEqual([]);
+ await expectAlertFullyRemoved(alert);
});
// Rows from before the migration have no API that creates them, so these tests seed the reminder
diff --git a/backend/e2e-test/testUtils/reminders.ts b/backend/e2e-test/testUtils/reminders.ts
index eb2aa7972f..e3a1a3dabe 100644
--- a/backend/e2e-test/testUtils/reminders.ts
+++ b/backend/e2e-test/testUtils/reminders.ts
@@ -54,6 +54,18 @@ export const getSecretReminder = (dto: { secretId: string; authToken: string })
}
);
+export const deleteSecretReminder = (dto: { secretId: string; authToken: string }) =>
+ request(
+ {
+ method: "DELETE",
+ url: `/api/v1/reminders/secrets/${dto.secretId}`,
+ headers: { authorization: `Bearer ${dto.authToken}` }
+ },
+ (res) => {
+ expect(res.statusCode).toBe(200);
+ }
+ );
+
export const listSecretReminderAlerts = (dto: { projectId: string; secretId: string; authToken: string }) =>
listAlerts({
resourceType: SECRET_REMINDER_RESOURCE_TYPE,
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index fc644ab9bb..9e8730c610 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1543,7 +1543,6 @@ export const registerRoutes = async (
reminderDAL,
eventEmitter: eventOutboxService,
alertService,
- projectDAL,
permissionService,
secretV2BridgeDAL,
folderDAL
diff --git a/backend/src/server/routes/v3/deprecated-secret-router.ts b/backend/src/server/routes/v3/deprecated-secret-router.ts
index 88951720db..b63f5b84b2 100644
--- a/backend/src/server/routes/v3/deprecated-secret-router.ts
+++ b/backend/src/server/routes/v3/deprecated-secret-router.ts
@@ -768,7 +768,12 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
.optional()
.nullable()
.describe(RAW_SECRETS.UPDATE.secretReminderRepeatDays),
- secretReminderRecipients: z.string().array().optional().describe(RAW_SECRETS.UPDATE.secretReminderRecipients),
+ secretReminderRecipients: z
+ .string()
+ .uuid()
+ .array()
+ .optional()
+ .describe(RAW_SECRETS.UPDATE.secretReminderRecipients),
newSecretName: SecretNameSchema.optional().describe(RAW_SECRETS.UPDATE.newSecretName),
secretComment: z.string().optional().describe(RAW_SECRETS.UPDATE.secretComment)
}),
diff --git a/backend/src/server/routes/v4/secret-router.ts b/backend/src/server/routes/v4/secret-router.ts
index 1008481523..7236943768 100644
--- a/backend/src/server/routes/v4/secret-router.ts
+++ b/backend/src/server/routes/v4/secret-router.ts
@@ -629,7 +629,12 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
.optional()
.nullable()
.describe(RAW_SECRETS.UPDATE.secretReminderRepeatDays),
- secretReminderRecipients: z.string().array().optional().describe(RAW_SECRETS.UPDATE.secretReminderRecipients),
+ secretReminderRecipients: z
+ .string()
+ .uuid()
+ .array()
+ .optional()
+ .describe(RAW_SECRETS.UPDATE.secretReminderRecipients),
newSecretName: SecretNameSchema.optional().describe(RAW_SECRETS.UPDATE.newSecretName),
secretComment: z.string().optional().describe(RAW_SECRETS.UPDATE.secretComment)
}),
diff --git a/backend/src/services/alert/alert-dal.ts b/backend/src/services/alert/alert-dal.ts
index deb9a8a6b0..dfe04248e9 100644
--- a/backend/src/services/alert/alert-dal.ts
+++ b/backend/src/services/alert/alert-dal.ts
@@ -3,12 +3,19 @@ import { Knex } from "knex";
import { TDbClient } from "@app/db";
import { TableName, TAlerts } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
-import { ormify, selectAllTableCols } from "@app/lib/knex";
+import { ormify, selectAllTableCols, sqlNestRelationships } from "@app/lib/knex";
import { AlertTriggerType } from "./alert-types";
export type TAlertDALFactory = ReturnType<typeof alertDALFactory>;
+export type TAlertChannelSummary = {
+ id: string;
+ name: string;
+ resourceId: string | null;
+ channels: { id: string; name: string; channelType: string; enabled: boolean }[];
+};
+
export const alertDALFactory = (db: TDbClient) => {
const alertOrm = ormify(db, TableName.Alert);
@@ -221,8 +228,65 @@ 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 (
+ { resourceType, resourceIds }: { resourceType: string; resourceIds: string[] },
+ tx?: Knex
+ ): Promise<TAlertChannelSummary[]> => {
+ if (resourceIds.length === 0) return [];
+ try {
+ const rows = await (tx || db)(TableName.Alert)
+ .where(`${TableName.Alert}.resourceType`, resourceType)
+ .whereIn(`${TableName.Alert}.resourceId`, resourceIds)
+ .leftJoin(
+ TableName.AlertChannelMembership,
+ `${TableName.Alert}.id`,
+ `${TableName.AlertChannelMembership}.alertId`
+ )
+ .leftJoin(
+ TableName.AlertChannel,
+ `${TableName.AlertChannelMembership}.channelId`,
+ `${TableName.AlertChannel}.id`
+ )
+ .select(
+ db.ref("id").withSchema(TableName.Alert),
+ db.ref("name").withSchema(TableName.Alert),
+ db.ref("resourceId").withSchema(TableName.Alert),
+ db.ref("id").withSchema(TableName.AlertChannel).as("channelId"),
+ db.ref("name").withSchema(TableName.AlertChannel).as("channelName"),
+ db.ref("channelType").withSchema(TableName.AlertChannel),
+ db.ref("enabled").withSchema(TableName.AlertChannel).as("channelEnabled")
+ )
+ .orderBy(`${TableName.AlertChannel}.createdAt`, "asc");
+
+ return sqlNestRelationships({
+ data: rows,
+ key: "id",
+ parentMapper: ({ id, name, resourceId }) => ({ id, name, resourceId: resourceId ?? null }),
+ childrenMapper: [
+ {
+ key: "channelId",
+ label: "channels" as const,
+ mapper: ({ channelId, channelName, channelType, channelEnabled }) => ({
+ id: channelId,
+ name: channelName,
+ channelType,
+ enabled: channelEnabled
+ })
+ }
+ ]
+ });
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindChannelSummariesForResources" });
+ }
+ };
+
return {
...alertOrm,
+ findChannelSummariesForResources,
findRecipientsForResources,
findEnabledByResourceType,
findEnabledForEvent,
diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.ts
index d754be93d3..93638f43e7 100644
--- a/backend/src/services/alert/alert-service.ts
+++ b/backend/src/services/alert/alert-service.ts
@@ -470,40 +470,8 @@ export const alertServiceFactory = ({
tx?: Knex
): Promise<number> => $reapAlerts({ resourceType, resourceId }, tx);
- const findAlertsForResources = async (
- { resourceType, resourceIds }: { resourceType: string; resourceIds: string[] },
- tx?: Knex
- ): Promise<TAlertResponse[]> => {
- if (resourceIds.length === 0) return [];
-
- const alerts = await alertDAL.find({ resourceType, $in: { resourceId: resourceIds } }, { tx });
- if (alerts.length === 0) return [];
-
- const channels = await alertChannelDAL.findByAlertIds(
- alerts.map((alert) => alert.id),
- tx
- );
- const channelsByAlert = new Map<string, TAlertChannels[]>();
- channels.forEach((channel) => {
- channelsByAlert.set(channel.alertId, [...(channelsByAlert.get(channel.alertId) ?? []), channel]);
- });
-
- const cipherByScope = new Map<string, Awaited<ReturnType<typeof getAlertChannelCipher>>>();
- const responses: TAlertResponse[] = [];
- for (const alert of alerts) {
- const scopeKey = `${alert.orgId}:${alert.projectId ?? ""}`;
- let cipher = cipherByScope.get(scopeKey);
- if (!cipher) {
- // eslint-disable-next-line no-await-in-loop -- one cipher per scope, and resource ids usually share one
- cipher = await getAlertChannelCipher(kmsService, { orgId: alert.orgId, projectId: alert.projectId }, tx);
- cipherByScope.set(scopeKey, cipher);
- }
- // eslint-disable-next-line no-await-in-loop -- reuses tx when given, so reads must be serial
- const details = await alertChannelService.getDetailsForChannels(channelsByAlert.get(alert.id) ?? [], cipher, tx);
- responses.push($assembleResponse(alert, details));
- }
- return responses;
- };
+ const findAlertChannelSummariesForResources = (input: { resourceType: string; resourceIds: string[] }, tx?: Knex) =>
+ alertDAL.findChannelSummariesForResources(input, tx);
const deleteAlertsForDeletedResources = async (
{ resourceType, resourceIds }: { resourceType: string; resourceIds: string[] },
@@ -546,7 +514,7 @@ export const alertServiceFactory = ({
deleteAlert,
deleteAlertsForResource,
deleteAlertsForDeletedResource,
- findAlertsForResources,
+ findAlertChannelSummariesForResources,
deleteAlertsForDeletedResources,
repointAlertsForResource,
findRecipientsForResources,
diff --git a/backend/src/services/alert/providers/secret-reminder-alert-provider.test.ts b/backend/src/services/alert/providers/secret-reminder-alert-provider.test.ts
index b33ea89dc3..a5fb091059 100644
--- a/backend/src/services/alert/providers/secret-reminder-alert-provider.test.ts
+++ b/backend/src/services/alert/providers/secret-reminder-alert-provider.test.ts
@@ -1,15 +1,15 @@
import { createMongoAbility } from "@casl/ability";
import { vi } from "vitest";
-import { emitSecretReminderDue } from "@app/services/reminder/reminder-events";
+import {
+ emitSecretReminderDue,
+ SECRET_REMINDER_DUE_EVENT,
+ SECRET_REMINDER_RESOURCE_TYPE
+} from "@app/services/reminder/reminder-events";
import { AlertPermissionAction, TAlertContext } from "../alert-types";
import { TReminderSecret } from "./secret-reminder-alert-dal";
-import {
- SECRET_REMINDER_DUE_EVENT,
- SECRET_REMINDER_RESOURCE_TYPE,
- secretReminderAlertProviderFactory
-} from "./secret-reminder-alert-provider";
+import { secretReminderAlertProviderFactory } from "./secret-reminder-alert-provider";
vi.mock("@app/lib/config/env", () => ({
getConfig: () => ({ SITE_URL: "https://app.infisical.com" })
diff --git a/backend/src/services/alert/providers/secret-reminder-alert-provider.ts b/backend/src/services/alert/providers/secret-reminder-alert-provider.ts
index e423a8cf62..1317bdc3f9 100644
--- a/backend/src/services/alert/providers/secret-reminder-alert-provider.ts
+++ b/backend/src/services/alert/providers/secret-reminder-alert-provider.ts
@@ -25,8 +25,6 @@ import {
} from "../alert-types";
import { TReminderSecret, TSecretReminderAlertDALFactory } from "./secret-reminder-alert-dal";
-export { SECRET_REMINDER_DUE_EVENT, SECRET_REMINDER_RESOURCE_TYPE };
-
const SecretReminderConditionSchema = z.object({}).nullish();
export type TSecretReminderTarget = TReminderSecret & {
diff --git a/backend/src/services/reminder/reminder-service.test.ts b/backend/src/services/reminder/reminder-service.test.ts
index 12a6feb703..f8d54a3d86 100644
--- a/backend/src/services/reminder/reminder-service.test.ts
+++ b/backend/src/services/reminder/reminder-service.test.ts
@@ -204,7 +204,6 @@ type TStoredAlert = {
name: string;
channelType: string;
enabled: boolean;
- recipients: { principalType: string; principalId: string }[];
}>;
};
@@ -228,7 +227,6 @@ const buildWriteService = (opts: { existingAlert?: TStoredAlert; projectUserIds?
secretIds.map((secretId) => ({ id: `rem-${secretId}`, secretId, recipients: ["stale-user"] }))
},
eventEmitter: { emit: async () => {} },
- projectDAL: { findById: async () => ({ id: "proj-1", orgId: "org-1" }) },
secretV2BridgeDAL: {
findOneWithTags: async () => ({
id: "secret-1",
@@ -248,7 +246,7 @@ const buildWriteService = (opts: { existingAlert?: TStoredAlert; projectUserIds?
alertService: {
filterRecipientsInScope: async (_scope: unknown, recipients: { principalType: string; principalId: string }[]) =>
opts.projectUserIds ? recipients.filter((r) => opts.projectUserIds!.includes(r.principalId)) : recipients,
- findAlertsForResources: async () => (opts.existingAlert ? [opts.existingAlert] : []),
+ findAlertChannelSummariesForResources: async () => (opts.existingAlert ? [opts.existingAlert] : []),
createAlert: async (input: unknown) => {
calls.push("alert:create");
created.push(input);
@@ -382,8 +380,8 @@ describe("reminder alert sync", () => {
name: "Reminder for OLD_NAME",
resourceId: "secret-1",
channels: [
- { id: "ch-email", name: "Team email", channelType: "email", enabled: true, recipients: [] },
- { id: "ch-hook", name: "Webhook", channelType: "webhook", enabled: false, recipients: [] }
+ { id: "ch-email", name: "Team email", channelType: "email", enabled: true },
+ { id: "ch-hook", name: "Webhook", channelType: "webhook", enabled: false }
]
}
});
diff --git a/backend/src/services/reminder/reminder-service.ts b/backend/src/services/reminder/reminder-service.ts
index 63a09afd3d..2f6eb26c20 100644
--- a/backend/src/services/reminder/reminder-service.ts
+++ b/backend/src/services/reminder/reminder-service.ts
@@ -16,7 +16,6 @@ import { TAlertServiceFactory } from "../alert/alert-service";
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 { TProjectDALFactory } from "../project/project-dal";
import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
import { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-dal";
import { TReminderDALFactory } from "./reminder-dal";
@@ -37,13 +36,12 @@ type TReminderServiceFactoryDep = {
TAlertServiceFactory,
| "createAlert"
| "updateAlert"
- | "findAlertsForResources"
+ | "findAlertChannelSummariesForResources"
| "findRecipientsForResources"
| "deleteAlertsForDeletedResources"
| "repointAlertsForResource"
| "filterRecipientsInScope"
>;
- projectDAL: Pick<TProjectDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
secretV2BridgeDAL: Pick<TSecretV2BridgeDALFactory, "invalidateSecretCacheByProjectId" | "findOneWithTags">;
folderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds">;
@@ -53,7 +51,6 @@ export const reminderServiceFactory = ({
reminderDAL,
eventEmitter,
alertService,
- projectDAL,
permissionService,
secretV2BridgeDAL,
folderDAL
@@ -101,10 +98,7 @@ export const reminderServiceFactory = ({
channels?: TAlertChannelInput[];
actor: TGenericPermission;
}) => {
- const project = await projectDAL.findById(projectId);
- if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
-
- const [existing] = await alertService.findAlertsForResources({
+ const [existing] = await alertService.findAlertChannelSummariesForResources({
resourceType: SECRET_REMINDER_RESOURCE_TYPE,
resourceIds: [secretId]
});
@@ -139,7 +133,7 @@ export const reminderServiceFactory = ({
// 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: project.orgId, projectId },
+ { orgId: actor.actorOrgId, 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
@@ -381,6 +375,9 @@ export const reminderServiceFactory = ({
}
};
+ // Deleting a reminder or its secret reaps the alert inline. This covers secrets removed by cascade
+ // (folder, environment or project deletion), which no reminder code sees and which nothing cascades
+ // to because alerts.resourceId has no foreign key.
const reapOrphanedReminderAlerts: TReminderServiceFactory["reapOrphanedReminderAlerts"] = async () => {
for (let batch = 0; batch < MAX_ORPHAN_REAP_BATCHES; batch += 1) {
// eslint-disable-next-line no-await-in-loop -- each batch is its own short transaction