Skip to content

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

test(reminders): run the daily reminder job on demand in e2e

Calvinfa84246fec3e
diff --git a/backend/e2e-test/fakes/event-outbox-queue.ts b/backend/e2e-test/fakes/event-outbox-queue.ts
new file mode 100644
index 0000000000..b5506e8649
--- /dev/null
+++ b/backend/e2e-test/fakes/event-outbox-queue.ts
@@ -0,0 +1,29 @@
+import type { TEventOutboxServiceFactory } from "@app/services/event-outbox/event-outbox-service";
+
+// Reached through a path the alias does not match, so this resolves to the real module.
+import * as RealEventOutboxQueue from "../../src/services/event-outbox/event-outbox-queue";
+
+// Wraps the real outbox queue so a spec can deliver pending events now rather than waiting up to
+// OUTBOX_RELAY_INTERVAL_MS (plus start jitter) for the relay. Wired up by test.alias in
+// vitest.e2e.config.mts; nothing under src/ references this file.
+//
+// The relay keeps running alongside. Claims are exclusive, so an event is delivered once whichever
+// side gets to it first, and a spec should still wait on the outcome rather than on the drain.
+//
+// The handle hangs off globalThis for the reason given in aws-parameter-store-sync-fns.ts.
+const globalScope = globalThis as typeof globalThis & {
+ infisicalEventOutboxService?: Pick<TEventOutboxServiceFactory, "drain">;
+};
+
+export const eventOutboxQueueFactory: typeof RealEventOutboxQueue.eventOutboxQueueFactory = (deps) => {
+ globalScope.infisicalEventOutboxService = deps.eventOutboxService;
+ return RealEventOutboxQueue.eventOutboxQueueFactory(deps);
+};
+
+export const eventOutbox = {
+ drain: async (consumer: string) => {
+ const service = globalScope.infisicalEventOutboxService;
+ if (!service) throw new Error("The test server has not wired the event outbox yet");
+ await service.drain({ consumer });
+ }
+};
diff --git a/backend/e2e-test/fakes/reminder-queue.ts b/backend/e2e-test/fakes/reminder-queue.ts
new file mode 100644
index 0000000000..dc1b830798
--- /dev/null
+++ b/backend/e2e-test/fakes/reminder-queue.ts
@@ -0,0 +1,33 @@
+import type { TReminderServiceFactory } from "@app/services/reminder/reminder-types";
+
+// Reached through a path the alias does not match, so this resolves to the real module.
+import * as RealReminderQueue from "../../src/services/reminder/reminder-queue";
+
+// Wraps the real daily reminder job so a spec can run it on demand instead of waiting for the cron.
+// Wired up by test.alias in vitest.e2e.config.mts; nothing under src/ references this file.
+//
+// The job is real: it registers with the server's cron as usual, and the handle below calls the same
+// reminder service the handler does, wired with the server's own dependencies. Only the trigger
+// changes, and the spec can pass the day to run for instead of waiting for it.
+//
+// The handle hangs off globalThis for the reason given in aws-parameter-store-sync-fns.ts: the
+// server and a spec reach this module by different specifiers and get separate copies of it.
+const globalScope = globalThis as typeof globalThis & {
+ infisicalReminderService?: TReminderServiceFactory;
+};
+
+export const dailyReminderQueueServiceFactory: typeof RealReminderQueue.dailyReminderQueueServiceFactory = (deps) => {
+ globalScope.infisicalReminderService = deps.reminderService;
+ return RealReminderQueue.dailyReminderQueueServiceFactory(deps);
+};
+
+const reminderService = () => {
+ const service = globalScope.infisicalReminderService;
+ if (!service) throw new Error("The test server has not wired the daily reminder job yet");
+ return service;
+};
+
+export const dailyReminderJob = {
+ dispatchDueReminders: (opts: { now: Date }) => reminderService().dispatchDueReminders(opts),
+ reapOrphanedReminderAlerts: () => reminderService().reapOrphanedReminderAlerts()
+};
diff --git a/backend/e2e-test/routes/v1/secret-reminder.spec.ts b/backend/e2e-test/routes/v1/secret-reminder.spec.ts
index e66896be46..f9d0b9d023 100644
--- a/backend/e2e-test/routes/v1/secret-reminder.spec.ts
+++ b/backend/e2e-test/routes/v1/secret-reminder.spec.ts
@@ -1,152 +1,99 @@
import { seedData1 } from "@app/db/seed-data";
-import { alertChannelDALFactory } from "@app/services/alert/alert-channel-dal";
-import { alertChannelMembershipDALFactory } from "@app/services/alert/alert-channel-membership-dal";
-import { alertDALFactory } from "@app/services/alert/alert-dal";
-import { alertEventConsumerFactory } from "@app/services/alert/alert-event-consumer";
-import { alertProviderRegistryFactory } from "@app/services/alert/alert-provider-registry";
-import { alertServiceFactory } from "@app/services/alert/alert-service";
-import { secretReminderAlertDALFactory } from "@app/services/alert/providers/secret-reminder-alert-dal";
-import { secretReminderAlertProviderFactory } from "@app/services/alert/providers/secret-reminder-alert-provider";
-import { eventOutboxDALFactory } from "@app/services/event-outbox/event-outbox-dal";
-import { eventOutboxRegistryFactory } from "@app/services/event-outbox/event-outbox-registry";
-import { eventOutboxServiceFactory } from "@app/services/event-outbox/event-outbox-service";
-import { reminderDALFactory } from "@app/services/reminder/reminder-dal";
-import { reminderServiceFactory } from "@app/services/reminder/reminder-service";
+import { SECRET_REMINDER_RESOURCE_TYPE } from "@app/services/reminder/reminder-events";
import { up as migrateRemindersToAlerts } from "../../../src/db/migrations/20260929130000_migrate-secret-reminders-to-alerts";
-import { createFolder } from "../../testUtils/folders";
-import { createSecretV2, deleteSecretV2 } from "../../testUtils/secrets";
-
-const RESOURCE_TYPE = "secret.reminder";
-const EVENT_TYPE = "secret.reminder.due";
-const projectId = seedData1.projectV3.id;
-const environment = seedData1.environment.slug;
-const auth = () => ({ authorization: `Bearer ${jwtAuthToken}` });
-
-// Services are decorated inside the routes plugin, out of a spec's reach, so the cron's two entry
-// points are built here from the real DALs and the real event outbox registration. The stubbed
-// dependencies are ones dispatch and reaping never call.
-const buildReminderCron = () => {
- const db = testDb as never;
- const alertDAL = alertDALFactory(db);
- const alertProviderRegistry = alertProviderRegistryFactory();
- alertProviderRegistry.register(
- secretReminderAlertProviderFactory({
- secretReminderAlertDAL: secretReminderAlertDALFactory(db),
- folderDAL: {} as never,
- permissionService: {} as never
- })
- );
- const eventOutboxRegistry = eventOutboxRegistryFactory();
- eventOutboxRegistry.register(
- alertEventConsumerFactory({ alertDAL, alertEngine: {} as never, alertProviderRegistry })
- );
- return reminderServiceFactory({
- reminderDAL: reminderDALFactory(db),
- eventEmitter: eventOutboxServiceFactory({ eventOutboxDAL: eventOutboxDALFactory(db), eventOutboxRegistry }),
- alertService: alertServiceFactory({
- alertDAL,
- alertChannelDAL: alertChannelDALFactory(db),
- alertChannelMembershipDAL: alertChannelMembershipDALFactory(db),
- alertChannelService: {} as never,
- kmsService: {} as never,
- alertProviderRegistry
- }),
- projectDAL: {} as never,
- permissionService: {} as never,
- secretV2BridgeDAL: {} as never,
- folderDAL: {} as never
- });
+import { listAlerts, updateAlert } from "../../testUtils/alerts";
+import { createIsolatedOrgAndProject } from "../../testUtils/fixtures";
+import { createFolder, deleteFolder } from "../../testUtils/folders";
+import {
+ deleteSecretReminder,
+ getSecretReminder,
+ listSecretReminderAlerts,
+ reapOrphanedReminderAlerts,
+ reminderEmailsFor,
+ runDailyReminders,
+ setSecretReminder,
+ waitForReminderEmails
+} from "../../testUtils/reminders";
+import { createSecretV2, getSecretByNameV2 } from "../../testUtils/secrets";
+
+const ENVIRONMENT = "dev";
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+const startOfUtcDay = (date: Date) => {
+ const day = new Date(date);
+ day.setUTCHours(0, 0, 0, 0);
+ return day;
};
-const createSecret = async (key: string, secretPath = "/") => {
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: environment,
- secretPath,
- key,
- value: "value",
- authToken: jwtAuthToken
+describe("Secret reminders delivered through alerts", () => {
+ let projectId: string;
+ let authToken: string;
+ let cleanup: () => Promise<void>;
+
+ beforeEach(async () => {
+ ({ projectId, authToken, cleanup } = await createIsolatedOrgAndProject("reminders"));
});
- const row = await testDb("secrets_v2").where({ key, type: "shared" }).first();
- return row.id as string;
-};
-const setReminder = async (secretId: string, body: Record<string, unknown>) => {
- const res = await testServer.inject({
- method: "POST",
- url: `/api/v1/reminders/secrets/${secretId}`,
- headers: auth(),
- body
+ afterEach(async () => {
+ await cleanup();
});
- expect(res.statusCode).toBe(200);
-};
-type TReminderAlert = {
- id: string;
- name: string;
- channels: {
- id: string;
- name: string;
- channelType: string;
- enabled: boolean;
- recipients: { principalType: string; principalId: string }[];
- }[];
-};
+ const createSecret = async (key: string, opts: { secretPath?: string } = {}) => {
+ const secret = await createSecretV2({
+ workspaceId: projectId,
+ environmentSlug: ENVIRONMENT,
+ secretPath: opts.secretPath ?? "/",
+ key,
+ value: "value",
+ authToken
+ });
+ return secret.id;
+ };
-const reminderAlert = async (secretId: string): Promise<TReminderAlert[]> => {
- const res = await testServer.inject({
- method: "GET",
- url: "/api/v1/alerts",
- headers: auth(),
- query: { resourceType: RESOURCE_TYPE, projectId, resourceId: secretId }
- });
- expect(res.statusCode).toBe(200);
- return res.json<{ alerts: TReminderAlert[] }>().alerts;
-};
+ const reminderAlerts = (secretId: string) => listSecretReminderAlerts({ projectId, secretId, authToken });
-const reminderAlertRows = (secretId: string) =>
- testDb("alerts").where({ resourceType: RESOURCE_TYPE, resourceId: secretId });
+ const nextReminderDate = async (secretId: string) => {
+ const reminder = await getSecretReminder({ secretId, authToken });
+ expect(reminder).not.toBeNull();
+ return new Date(reminder?.nextReminderDate as string);
+ };
-describe("Secret reminders delivered through alerts", async () => {
test("setting a reminder creates its alert with an email channel to the recipients", async () => {
- const secretId = await createSecret("REMINDER_E2E_CREATE");
- await setReminder(secretId, { repeatDays: 30, message: "rotate it", recipients: [seedData1.id] });
+ const secretId = await createSecret("CREATE");
+ await setSecretReminder({ secretId, authToken, repeatDays: 30, message: "rotate it", recipients: [seedData1.id] });
- const [alert] = await reminderAlert(secretId);
- expect(alert.name).toBe("Reminder for REMINDER_E2E_CREATE");
+ const [alert] = await reminderAlerts(secretId);
+ expect(alert.name).toBe("Reminder for CREATE");
expect(alert.channels).toHaveLength(1);
expect(alert.channels[0]).toMatchObject({
channelType: "email",
recipients: [{ principalType: "user", principalId: seedData1.id }]
});
- const res = await testServer.inject({
- method: "GET",
- url: `/api/v1/reminders/secrets/${secretId}`,
- headers: auth()
+ expect(await getSecretReminder({ secretId, authToken })).toMatchObject({
+ repeatDays: 30,
+ message: "rotate it",
+ recipients: [seedData1.id]
});
- expect(res.statusCode).toBe(200);
- expect(res.json().reminder).toMatchObject({ repeatDays: 30, message: "rotate it", recipients: [seedData1.id] });
});
test("a reminder with no recipients notifies all project members", async () => {
- const secretId = await createSecret("REMINDER_E2E_EVERYONE");
- await setReminder(secretId, { repeatDays: 7 });
+ const secretId = await createSecret("EVERYONE");
+ await setSecretReminder({ secretId, authToken, repeatDays: 7 });
- const [alert] = await reminderAlert(secretId);
+ const [alert] = await reminderAlerts(secretId);
expect(alert.channels[0].recipients).toEqual([{ principalType: "project-members", principalId: projectId }]);
});
test("updating the reminder keeps channels added through the alert API", async () => {
- const secretId = await createSecret("REMINDER_E2E_KEEP_WEBHOOK");
- await setReminder(secretId, { repeatDays: 30, recipients: [seedData1.id] });
- const [alert] = await reminderAlert(secretId);
-
- const patch = await testServer.inject({
- method: "PATCH",
- url: `/api/v1/alerts/${alert.id}`,
- headers: auth(),
+ const secretId = await createSecret("KEEP_WEBHOOK");
+ await setSecretReminder({ secretId, authToken, repeatDays: 30, recipients: [seedData1.id] });
+ const [alert] = await reminderAlerts(secretId);
+
+ await updateAlert({
+ alertId: alert.id,
+ authToken,
body: {
channels: [
{ id: alert.channels[0].id, name: alert.channels[0].name, channelType: "email" },
@@ -154,11 +101,10 @@ describe("Secret reminders delivered through alerts", async () => {
]
}
});
- expect(patch.statusCode).toBe(200);
- await setReminder(secretId, { repeatDays: 14 });
+ await setSecretReminder({ secretId, authToken, repeatDays: 14 });
- const [updated] = await reminderAlert(secretId);
+ const [updated] = await reminderAlerts(secretId);
expect(updated.channels.map((channel) => channel.channelType).sort()).toEqual(["email", "webhook"]);
expect(updated.channels.find((channel) => channel.channelType === "email")?.recipients).toEqual([
{ principalType: "project-members", principalId: projectId }
@@ -166,20 +112,14 @@ describe("Secret reminders delivered through alerts", async () => {
});
test("the secret listing reports recipients from the reminder's alert", async () => {
- const secretId = await createSecret("REMINDER_E2E_LISTING");
- await setReminder(secretId, { repeatDays: 30, recipients: [seedData1.id] });
+ const secretId = await createSecret("LISTING");
+ await setSecretReminder({ secretId, authToken, repeatDays: 30, recipients: [seedData1.id] });
const res = await testServer.inject({
method: "GET",
url: "/api/v1/dashboard/secrets-details",
- headers: auth(),
- query: {
- projectId,
- environment,
- secretPath: "/",
- search: "REMINDER_E2E_LISTING",
- includeSecrets: "true"
- }
+ headers: { authorization: `Bearer ${authToken}` },
+ query: { projectId, environment: ENVIRONMENT, secretPath: "/", search: "LISTING", includeSecrets: "true" }
});
expect(res.statusCode).toBe(200);
const [secret] = res.json().secrets as {
@@ -191,199 +131,186 @@ describe("Secret reminders delivered through alerts", async () => {
});
test("listing reminder alerts across a project is refused", async () => {
- const res = await testServer.inject({
- method: "GET",
- url: "/api/v1/alerts",
- headers: auth(),
- query: { resourceType: RESOURCE_TYPE, projectId }
- });
+ const res = await listAlerts({ resourceType: SECRET_REMINDER_RESOURCE_TYPE, projectId, authToken }).raw();
expect(res.statusCode).toBe(400);
});
test("moving a secret carries its reminder alert to the new secret", async () => {
await createFolder({
workspaceId: projectId,
- environmentSlug: environment,
+ environmentSlug: ENVIRONMENT,
secretPath: "/",
- name: "reminder-move-dest",
- authToken: jwtAuthToken
+ name: "dest",
+ authToken
});
- const secretId = await createSecret("REMINDER_E2E_MOVE");
- await setReminder(secretId, { repeatDays: 30, recipients: [seedData1.id] });
- const [before] = await reminderAlert(secretId);
+ const secretId = await createSecret("MOVE");
+ await setSecretReminder({ secretId, authToken, repeatDays: 30, recipients: [seedData1.id] });
+ const [before] = await reminderAlerts(secretId);
const move = await testServer.inject({
method: "POST",
url: "/api/v4/secrets/move",
- headers: auth(),
+ headers: { authorization: `Bearer ${authToken}` },
body: {
projectId,
- sourceEnvironment: environment,
+ sourceEnvironment: ENVIRONMENT,
sourceSecretPath: "/",
- destinationEnvironment: environment,
- destinationSecretPath: "/reminder-move-dest",
+ destinationEnvironment: ENVIRONMENT,
+ destinationSecretPath: "/dest",
secretIds: [secretId]
}
});
expect(move.statusCode).toBe(200);
- const moved = await testDb("secrets_v2").where({ key: "REMINDER_E2E_MOVE", type: "shared" }).first();
+ const moved = await getSecretByNameV2({
+ workspaceId: projectId,
+ environmentSlug: ENVIRONMENT,
+ secretPath: "/dest",
+ key: "MOVE",
+ authToken
+ });
expect(moved.id).not.toBe(secretId);
- expect(await reminderAlertRows(secretId)).toHaveLength(0);
- const movedAlerts = await reminderAlertRows(moved.id as string);
- expect(movedAlerts.map((alert) => alert.id)).toEqual([before.id]);
+ expect((await reminderAlerts(moved.id)).map((alert) => alert.id)).toEqual([before.id]);
});
- test("the cron emits one event per due reminder and moves the schedule forward", async () => {
- const secretId = await createSecret("REMINDER_E2E_DISPATCH");
- await setReminder(secretId, { repeatDays: 30, message: "rotate it" });
+ test("the daily job emails a due reminder and moves its schedule forward", async () => {
+ const secretId = await createSecret("DISPATCH");
+ await setSecretReminder({ secretId, authToken, repeatDays: 30, message: "rotate it", recipients: [seedData1.id] });
+ const dueDate = await nextReminderDate(secretId);
- const today = new Date();
- today.setUTCHours(0, 0, 0, 0);
- await testDb("reminders").where({ secretId }).update({ nextReminderDate: today });
+ await runDailyReminders({ now: new Date() });
+ expect(reminderEmailsFor("DISPATCH")).toHaveLength(0);
- await buildReminderCron().dispatchDueReminders();
+ await runDailyReminders({ now: dueDate });
- const occurrenceDate = today.toISOString().slice(0, 10);
- const events = await testDb("event_outbox").where({
- eventType: EVENT_TYPE,
- idempotencyKey: `${EVENT_TYPE}:${secretId}:${occurrenceDate}`
- });
- expect(events).toHaveLength(1);
- expect(events[0].payload).toMatchObject({
- resourceType: RESOURCE_TYPE,
- resourceId: secretId,
- targetIds: [secretId],
- note: "rotate it",
- repeatDays: 30,
- occurrenceDate
- });
+ const [email] = await waitForReminderEmails("DISPATCH");
+ expect(email.recipients).toEqual([seedData1.email]);
+ expect(JSON.stringify(email.substitutions)).toContain("rotate it");
- const reminder = await testDb("reminders").where({ secretId }).first();
- expect(new Date(reminder.nextReminderDate).getTime()).toBe(today.getTime() + 30 * 24 * 60 * 60 * 1000);
+ expect((await nextReminderDate(secretId)).getTime()).toBe(dueDate.getTime() + 30 * DAY_MS);
});
test("a one-time reminder is removed once it fires, but its alert stays as the record", async () => {
- const secretId = await createSecret("REMINDER_E2E_ONE_OFF");
- const tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString();
- await setReminder(secretId, { nextReminderDate: tomorrow });
+ const secretId = await createSecret("ONE_OFF");
+ const dueDate = new Date(Date.now() + DAY_MS);
+ await setSecretReminder({ secretId, authToken, nextReminderDate: dueDate.toISOString() });
- const today = new Date();
- today.setUTCHours(0, 0, 0, 0);
- await testDb("reminders").where({ secretId }).update({ nextReminderDate: today });
- await buildReminderCron().dispatchDueReminders();
+ await runDailyReminders({ now: dueDate });
- expect(await testDb("reminders").where({ secretId })).toHaveLength(0);
- expect(await reminderAlertRows(secretId)).toHaveLength(1);
+ await waitForReminderEmails("ONE_OFF");
+ expect(await getSecretReminder({ secretId, authToken })).toBeNull();
+ expect(await reminderAlerts(secretId)).toHaveLength(1);
});
test("deleting the reminder deletes its alert", async () => {
- const secretId = await createSecret("REMINDER_E2E_DELETE_REMINDER");
- await setReminder(secretId, { repeatDays: 30 });
+ const secretId = await createSecret("DELETE_REMINDER");
+ await setSecretReminder({ secretId, authToken, repeatDays: 30 });
- const res = await testServer.inject({
- method: "DELETE",
- url: `/api/v1/reminders/secrets/${secretId}`,
- headers: auth()
- });
- expect(res.statusCode).toBe(200);
- expect(await reminderAlertRows(secretId)).toHaveLength(0);
+ await deleteSecretReminder({ secretId, authToken });
+ expect(await reminderAlerts(secretId)).toHaveLength(0);
});
- test("the cron reaps alerts whose secret was deleted", async () => {
- const secretId = await createSecret("REMINDER_E2E_REAP");
- await setReminder(secretId, { repeatDays: 30 });
- const [alert] = await reminderAlert(secretId);
-
- await deleteSecretV2({
+ // Force-deleting a folder removes its secrets by cascade, which no reminder code sees. The API
+ // cannot show the orphaned alert either (every read goes through its secret), so this reads the
+ // alert row directly.
+ test("the daily job reaps alerts whose secret was removed without the reminder code seeing it", async () => {
+ const folder = await createFolder({
workspaceId: projectId,
- environmentSlug: environment,
+ environmentSlug: ENVIRONMENT,
secretPath: "/",
- key: "REMINDER_E2E_REAP",
- authToken: jwtAuthToken
+ name: "reap",
+ authToken
});
- // A second orphan whose secret never existed shows the sweep does not rely on any delete path.
- await testDb("alerts").insert({
- ...(await testDb("alerts").where({ id: alert.id }).first()),
- id: undefined,
- resourceId: "11111111-1111-4111-8111-111111111111",
- name: "orphan"
+ const secretId = await createSecret("REAP", { secretPath: "/reap" });
+ await setSecretReminder({ secretId, authToken, repeatDays: 30 });
+ const [alert] = await reminderAlerts(secretId);
+
+ await deleteFolder({
+ workspaceId: projectId,
+ environmentSlug: ENVIRONMENT,
+ secretPath: "/",
+ id: folder.id,
+ forceDelete: true,
+ authToken
});
+ expect(await testDb("alerts").where({ id: alert.id })).toHaveLength(1);
- await buildReminderCron().reapOrphanedReminderAlerts();
+ await reapOrphanedReminderAlerts();
- expect(await reminderAlertRows(secretId)).toHaveLength(0);
- expect(await reminderAlertRows("11111111-1111-4111-8111-111111111111")).toHaveLength(0);
+ expect(await testDb("alerts").where({ id: alert.id })).toHaveLength(0);
});
- test("the migration gives existing reminders an alert, keeping only recipients still in the project", async () => {
- const secretId = await createSecret("REMINDER_E2E_MIGRATE");
- const [outsider] = await testDb("users")
- .insert({ username: "[email protected]", email: "[email protected]" })
- .returning("id");
- const [reminder] = await testDb("reminders")
- .insert({ secretId, repeatDays: 30, nextReminderDate: new Date(Date.now() + 24 * 60 * 60 * 1000) })
- .returning("id");
- await testDb("reminders_recipients").insert([
- { reminderId: reminder.id, userId: seedData1.id },
- { reminderId: reminder.id, userId: outsider.id }
- ]);
+ // Rows from before the migration have no API that creates them, so these tests seed the reminder
+ // tables directly and check the result through the API.
+ describe("migrating existing reminders", () => {
+ const seedReminder = async (secretId: string, fields: { repeatDays: number; nextReminderDate: Date }) => {
+ const [reminder] = await testDb("reminders")
+ .insert({ secretId, ...fields })
+ .returning("id");
+ return reminder.id as string;
+ };
+
+ test("gives existing reminders an alert, keeping only recipients still in the project", async () => {
+ const secretId = await createSecret("MIGRATE");
+ const [outsider] = await testDb("users")
+ .insert({ username: "[email protected]", email: "[email protected]" })
+ .returning("id");
+ const reminderId = await seedReminder(secretId, {
+ repeatDays: 30,
+ nextReminderDate: new Date(Date.now() + DAY_MS)
+ });
+ await testDb("reminders_recipients").insert([
+ { reminderId, userId: seedData1.id },
+ { reminderId, userId: outsider.id }
+ ]);
+
+ await migrateRemindersToAlerts(testDb);
+
+ const [alert] = await reminderAlerts(secretId);
+ expect(alert).toMatchObject({ name: "Reminder for MIGRATE", triggerType: "event" });
+ expect(alert.channels).toHaveLength(1);
+ expect(alert.channels[0].recipients).toEqual([{ principalType: "user", principalId: seedData1.id }]);
+ // The API does not report who created an alert.
+ expect(await testDb("alerts").where({ id: alert.id }).first()).toMatchObject({
+ createdByActorType: "platform",
+ createdByActorId: null
+ });
+ });
- await migrateRemindersToAlerts(testDb);
+ test("falls back to all project members when no listed recipient is left", async () => {
+ const secretId = await createSecret("MIGRATE_EVERYONE");
+ await seedReminder(secretId, { repeatDays: 7, nextReminderDate: new Date(Date.now() + DAY_MS) });
- const [alert] = await reminderAlert(secretId);
- expect(alert.name).toBe("Reminder for REMINDER_E2E_MIGRATE");
- expect(alert.channels).toHaveLength(1);
- expect(alert.channels[0].recipients).toEqual([{ principalType: "user", principalId: seedData1.id }]);
- expect(await reminderAlertRows(secretId)).toEqual([
- expect.objectContaining({ createdByActorType: "platform", createdByActorId: null, triggerType: "event" })
- ]);
- });
+ await migrateRemindersToAlerts(testDb);
- test("the migration falls back to all project members when no listed recipient is left", async () => {
- const secretId = await createSecret("REMINDER_E2E_MIGRATE_EVERYONE");
- await testDb("reminders").insert({
- secretId,
- repeatDays: 7,
- nextReminderDate: new Date(Date.now() + 24 * 60 * 60 * 1000)
+ const [alert] = await reminderAlerts(secretId);
+ expect(alert.channels[0].recipients).toEqual([{ principalType: "project-members", principalId: projectId }]);
});
- await migrateRemindersToAlerts(testDb);
+ test("rerunning does not duplicate alerts", async () => {
+ const secretId = await createSecret("MIGRATE_TWICE");
+ await seedReminder(secretId, { repeatDays: 7, nextReminderDate: new Date(Date.now() + DAY_MS) });
- const [alert] = await reminderAlert(secretId);
- expect(alert.channels[0].recipients).toEqual([{ principalType: "project-members", principalId: projectId }]);
- });
+ await migrateRemindersToAlerts(testDb);
+ await migrateRemindersToAlerts(testDb);
- test("rerunning the migration does not duplicate alerts", async () => {
- const secretId = await createSecret("REMINDER_E2E_MIGRATE_TWICE");
- await testDb("reminders").insert({
- secretId,
- repeatDays: 7,
- nextReminderDate: new Date(Date.now() + 24 * 60 * 60 * 1000)
+ expect(await reminderAlerts(secretId)).toHaveLength(1);
});
- await migrateRemindersToAlerts(testDb);
- await migrateRemindersToAlerts(testDb);
+ test("resumes long-dead recurring reminders on their schedule without sending", async () => {
+ const secretId = await createSecret("MIGRATE_STALE");
+ const startOfToday = startOfUtcDay(new Date());
+ // Died 100 days ago on a 30 day schedule: the next date on that schedule is 20 days from today.
+ await seedReminder(secretId, {
+ repeatDays: 30,
+ nextReminderDate: new Date(startOfToday.getTime() - 100 * DAY_MS)
+ });
- expect(await reminderAlertRows(secretId)).toHaveLength(1);
- });
+ await migrateRemindersToAlerts(testDb);
+ await runDailyReminders({ now: new Date() });
- test("the migration resumes long-dead recurring reminders on their schedule without sending", async () => {
- const secretId = await createSecret("REMINDER_E2E_MIGRATE_STALE");
- const dayMs = 24 * 60 * 60 * 1000;
- const startOfToday = new Date();
- startOfToday.setUTCHours(0, 0, 0, 0);
- // Died 100 days ago on a 30 day schedule: the next date on that schedule is 20 days from today.
- await testDb("reminders").insert({
- secretId,
- repeatDays: 30,
- nextReminderDate: new Date(startOfToday.getTime() - 100 * dayMs)
+ expect((await nextReminderDate(secretId)).getTime()).toBe(startOfToday.getTime() + 20 * DAY_MS);
+ expect(reminderEmailsFor("MIGRATE_STALE")).toHaveLength(0);
});
-
- await migrateRemindersToAlerts(testDb);
-
- const migrated = await testDb("reminders").where({ secretId }).first();
- expect(new Date(migrated.nextReminderDate).getTime()).toBe(startOfToday.getTime() + 20 * dayMs);
- expect(await testDb("event_outbox").whereRaw(`payload->>'resourceId' = ?`, [secretId])).toHaveLength(0);
});
});
diff --git a/backend/e2e-test/testUtils/alerts.ts b/backend/e2e-test/testUtils/alerts.ts
new file mode 100644
index 0000000000..679091f5c5
--- /dev/null
+++ b/backend/e2e-test/testUtils/alerts.ts
@@ -0,0 +1,45 @@
+import { request } from "./request";
+
+export type TAlertRecord = {
+ id: string;
+ name: string;
+ channels: {
+ id: string;
+ name: string;
+ channelType: string;
+ enabled: boolean;
+ recipients: { principalType: string; principalId: string }[];
+ }[];
+};
+
+export const listAlerts = (dto: { resourceType: string; projectId: string; resourceId?: string; authToken: string }) =>
+ request(
+ {
+ method: "GET",
+ url: "/api/v1/alerts",
+ headers: { authorization: `Bearer ${dto.authToken}` },
+ query: {
+ resourceType: dto.resourceType,
+ projectId: dto.projectId,
+ ...(dto.resourceId ? { resourceId: dto.resourceId } : {})
+ }
+ },
+ (res) => {
+ expect(res.statusCode).toBe(200);
+ return res.json<{ alerts: TAlertRecord[] }>().alerts;
+ }
+ );
+
+export const updateAlert = (dto: { alertId: string; body: Record<string, unknown>; authToken: string }) =>
+ request(
+ {
+ method: "PATCH",
+ url: `/api/v1/alerts/${dto.alertId}`,
+ headers: { authorization: `Bearer ${dto.authToken}` },
+ body: dto.body
+ },
+ (res) => {
+ expect(res.statusCode).toBe(200);
+ return res.json<{ alert: TAlertRecord }>().alert;
+ }
+ );
diff --git a/backend/e2e-test/testUtils/poll.ts b/backend/e2e-test/testUtils/poll.ts
new file mode 100644
index 0000000000..5b0f334b49
--- /dev/null
+++ b/backend/e2e-test/testUtils/poll.ts
@@ -0,0 +1,27 @@
+const DEFAULT_TIMEOUT_MS = 20_000;
+const POLL_MS = 100;
+
+export const pollUntil = async <T>(dto: {
+ describe: string;
+ read: () => Promise<T> | T;
+ done: (value: T) => boolean;
+ timeoutMs?: number;
+}) => {
+ const timeoutMs = dto.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const deadline = Date.now() + timeoutMs;
+
+ for (;;) {
+ // eslint-disable-next-line no-await-in-loop
+ const value = await dto.read();
+ if (dto.done(value)) return value;
+
+ if (Date.now() >= deadline) {
+ throw new Error(`Timed out after ${timeoutMs}ms waiting for ${dto.describe}`);
+ }
+
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((resolve) => {
+ setTimeout(resolve, POLL_MS);
+ });
+ }
+};
diff --git a/backend/e2e-test/testUtils/reminders.ts b/backend/e2e-test/testUtils/reminders.ts
new file mode 100644
index 0000000000..24ad5dd27d
--- /dev/null
+++ b/backend/e2e-test/testUtils/reminders.ts
@@ -0,0 +1,96 @@
+import { eventOutbox } from "e2e-test/fakes/event-outbox-queue";
+import { dailyReminderJob } from "e2e-test/fakes/reminder-queue";
+import { TTestSmtpService } from "e2e-test/mocks/smtp";
+
+import { ALERT_EVENT_CONSUMER } from "@app/services/alert/alert-event-consumer";
+import { SECRET_REMINDER_RESOURCE_TYPE } from "@app/services/reminder/reminder-events";
+
+import { listAlerts } from "./alerts";
+import { pollUntil } from "./poll";
+import { request } from "./request";
+
+type TReminderRecord = {
+ id: string;
+ secretId: string;
+ message?: string | null;
+ repeatDays?: number | null;
+ nextReminderDate: string;
+ recipients?: string[];
+};
+
+export type TSetSecretReminderBody = {
+ message?: string;
+ repeatDays?: number | null;
+ nextReminderDate?: string | null;
+ fromDate?: string | null;
+ recipients?: string[];
+};
+
+export const setSecretReminder = (dto: { secretId: string; authToken: string } & TSetSecretReminderBody) => {
+ const { secretId, authToken, ...body } = dto;
+ return request(
+ {
+ method: "POST",
+ url: `/api/v1/reminders/secrets/${secretId}`,
+ headers: { authorization: `Bearer ${authToken}` },
+ body
+ },
+ (res) => {
+ expect(res.statusCode).toBe(200);
+ }
+ );
+};
+
+export const getSecretReminder = (dto: { secretId: string; authToken: string }) =>
+ request(
+ {
+ method: "GET",
+ url: `/api/v1/reminders/secrets/${dto.secretId}`,
+ headers: { authorization: `Bearer ${dto.authToken}` }
+ },
+ (res) => {
+ expect(res.statusCode).toBe(200);
+ return res.json<{ reminder?: TReminderRecord | null }>().reminder ?? null;
+ }
+ );
+
+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, resourceId: dto.secretId, ...dto });
+
+// Runs the daily reminder job as if it fired on `now`, then delivers what it emitted rather than
+// leaving that to the outbox relay's next tick.
+export const runDailyReminders = async (dto: { now: Date }) => {
+ await dailyReminderJob.dispatchDueReminders({ now: dto.now });
+ await eventOutbox.drain(ALERT_EVENT_CONSUMER);
+};
+
+export const reapOrphanedReminderAlerts = () => dailyReminderJob.reapOrphanedReminderAlerts();
+
+const smtp = () => (globalThis as unknown as { testSmtp: TTestSmtpService }).testSmtp;
+
+export const reminderEmailsFor = (secretKey: string) =>
+ smtp()
+ .getEmails()
+ .filter((email) => {
+ const items = (email.substitutions as { items?: { title: string }[] } | undefined)?.items ?? [];
+ return email.subjectLine === "Infisical Secret Reminder Alert" && items.some((item) => item.title === secretKey);
+ });
+
+export const waitForReminderEmails = (secretKey: string) =>
+ pollUntil({
+ describe: `a reminder email for secret '${secretKey}'`,
+ read: () => reminderEmailsFor(secretKey),
+ done: (emails) => emails.length > 0
+ });
diff --git a/backend/e2e-test/testUtils/secret-syncs.ts b/backend/e2e-test/testUtils/secret-syncs.ts
index 41efed11a6..a034312ff1 100644
--- a/backend/e2e-test/testUtils/secret-syncs.ts
+++ b/backend/e2e-test/testUtils/secret-syncs.ts
@@ -3,13 +3,12 @@ import { fakeParameterStore } from "e2e-test/fakes/aws-parameter-store-sync-fns"
import { SecretSyncInitialSyncBehavior } from "@app/services/secret-sync/secret-sync-enums";
import { SecretSyncStatus } from "@app/services/secret-sync/secret-sync-types";
+import { pollUntil } from "./poll";
+
// Every spec drives AWS Parameter Store, which is faked for the whole e2e run. See
// e2e-test/fakes/ and the alias block in vitest.e2e.config.mts.
const DESTINATION = "aws-parameter-store";
-const SYNC_TIMEOUT_MS = 20_000;
-const SYNC_POLL_MS = 100;
-
type TSecretSyncRecord = {
id: string;
name: string;
@@ -176,25 +175,6 @@ export const deleteSecretSync = async (dto: { syncId: string; authToken: string
expect(res.statusCode).toBe(200);
};
-const pollUntil = async <T>(dto: { describe: string; read: () => Promise<T> | T; done: (value: T) => boolean }) => {
- const deadline = Date.now() + SYNC_TIMEOUT_MS;
-
- for (;;) {
- // eslint-disable-next-line no-await-in-loop
- const value = await dto.read();
- if (dto.done(value)) return value;
-
- if (Date.now() >= deadline) {
- throw new Error(`Timed out after ${SYNC_TIMEOUT_MS}ms waiting for ${dto.describe}`);
- }
-
- // eslint-disable-next-line no-await-in-loop
- await new Promise((resolve) => {
- setTimeout(resolve, SYNC_POLL_MS);
- });
- }
-};
-
// Waits on the fake's own run counter before reading the record, rather than on the record
// alone. triggerSecretSyncSyncSecretsById writes syncStatus "pending" *after* enqueuing the job
// (secret-sync-service.ts:800), so a status-only wait races that write and can sit on a stale
diff --git a/backend/e2e-test/testUtils/secrets.ts b/backend/e2e-test/testUtils/secrets.ts
index 766a060625..0b19edae12 100644
--- a/backend/e2e-test/testUtils/secrets.ts
+++ b/backend/e2e-test/testUtils/secrets.ts
@@ -5,6 +5,7 @@ import { SecretType } from "@app/db/schemas";
import { request } from "./request";
type TRawSecret = {
+ id: string;
secretKey: string;
secretValue: string;
secretComment?: string;
diff --git a/backend/src/services/reminder/reminder-service.test.ts b/backend/src/services/reminder/reminder-service.test.ts
index 07f0355dfa..80f49cc0d3 100644
--- a/backend/src/services/reminder/reminder-service.test.ts
+++ b/backend/src/services/reminder/reminder-service.test.ts
@@ -82,24 +82,18 @@ const buildService = (opts: {
};
describe("reminder dispatch", () => {
- beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2026-10-10T00:00:05.000Z"));
- });
- afterEach(() => {
- vi.useRealTimers();
- });
+ const now = new Date("2026-10-10T00:00:05.000Z");
test("looks back over the catch-up window", async () => {
const { service, window } = buildService({});
- await service.dispatchDueReminders();
+ await service.dispatchDueReminders({ now });
expect(window()?.from.toISOString()).toBe("2026-10-03T00:00:00.000Z");
expect(window()?.to.toISOString()).toBe("2026-10-10T23:59:59.999Z");
});
test("emits the due event and advances a recurring reminder in the same transaction", async () => {
const { service, emitted, updates } = buildService({ due: [reminder()] });
- await service.dispatchDueReminders();
+ await service.dispatchDueReminders({ now });
expect(emitted).toHaveLength(1);
expect(emitted[0]).toMatchObject({
@@ -123,7 +117,7 @@ describe("reminder dispatch", () => {
test("deletes a one-time reminder once its event is emitted", async () => {
const { service, emitted, deletes, updates } = buildService({ due: [reminder({ repeatDays: null })] });
- await service.dispatchDueReminders();
+ await service.dispatchDueReminders({ now });
expect(emitted).toHaveLength(1);
expect(deletes).toEqual([{ id: "rem-1", tx: emitted[0].tx }]);
@@ -134,7 +128,7 @@ describe("reminder dispatch", () => {
const { service, emitted, updates } = buildService({
due: [reminder({ repeatDays: 2, nextReminderDate: new Date("2026-10-05T00:00:00.000Z") })]
});
- await service.dispatchDueReminders();
+ await service.dispatchDueReminders({ now });
expect(emitted).toHaveLength(1);
expect(emitted[0].payload.occurrenceDate).toBe("2026-10-05");
@@ -146,7 +140,7 @@ describe("reminder dispatch", () => {
due: [reminder({ id: "rem-1", secretId: "secret-1" }), reminder({ id: "rem-2", secretId: "secret-2" })],
emitFails: (secretId) => secretId === "secret-1"
});
- await service.dispatchDueReminders();
+ await service.dispatchDueReminders({ now });
expect(emitted.map((event) => event.payload.resourceId)).toEqual(["secret-2"]);
expect(updates.map((update) => update.id)).toEqual(["rem-2"]);
@@ -154,7 +148,7 @@ describe("reminder dispatch", () => {
test("skips a reminder with no secret", async () => {
const { service, emitted } = buildService({ due: [reminder({ secretId: null })] });
- await service.dispatchDueReminders();
+ await service.dispatchDueReminders({ now });
expect(emitted).toHaveLength(0);
});
});
diff --git a/backend/src/services/reminder/reminder-service.ts b/backend/src/services/reminder/reminder-service.ts
index db9af8d492..7ea024d2f5 100644
--- a/backend/src/services/reminder/reminder-service.ts
+++ b/backend/src/services/reminder/reminder-service.ts
@@ -336,8 +336,7 @@ export const reminderServiceFactory = ({
return { ...reminder, recipients: recipientIds.get(secretId) ?? [] };
};
- const dispatchDueReminders: TReminderServiceFactory["dispatchDueReminders"] = async () => {
- const now = new Date();
+ const dispatchDueReminders: TReminderServiceFactory["dispatchDueReminders"] = async ({ now = new Date() } = {}) => {
const dueReminders = await reminderDAL.findDueReminders(getReminderDueWindow(now));
for (const reminder of dueReminders) {
diff --git a/backend/src/services/reminder/reminder-types.ts b/backend/src/services/reminder/reminder-types.ts
index 121a2958d0..defc8ad19a 100644
--- a/backend/src/services/reminder/reminder-types.ts
+++ b/backend/src/services/reminder/reminder-types.ts
@@ -57,7 +57,7 @@ export interface TReminderServiceFactory {
actorAuthMethod: ActorAuthMethod;
}) => Promise<(TReminder & { recipients: string[] }) | null>;
- dispatchDueReminders: () => Promise<void>;
+ dispatchDueReminders: (opts?: { now?: Date }) => Promise<void>;
reapOrphanedReminderAlerts: () => Promise<void>;
diff --git a/backend/vitest.e2e.config.mts b/backend/vitest.e2e.config.mts
index 02d3c0fedf..1fe8471c3e 100644
--- a/backend/vitest.e2e.config.mts
+++ b/backend/vitest.e2e.config.mts
@@ -78,6 +78,16 @@ export default defineConfig({
{
find: "./aws-connection-fns",
replacement: path.resolve(__dirname, "./e2e-test/fakes/aws-connection-fns")
+ },
+ // Pass-through wrappers that hand a spec the real job, to run on demand. Only
+ // server/routes/index.ts imports either specifier.
+ {
+ find: /^@app\/services\/reminder\/reminder-queue$/,
+ replacement: path.resolve(__dirname, "./e2e-test/fakes/reminder-queue")
+ },
+ {
+ find: /^@app\/services\/event-outbox\/event-outbox-queue$/,
+ replacement: path.resolve(__dirname, "./e2e-test/fakes/event-outbox-queue")
}
]
},