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
feat(reminders): backfill alerts for existing reminders
Calvine974158fef6b
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 2ea5fe7129..c0f8375525 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -712,6 +712,12 @@ Invariants worth knowing before extending it:Wire it into **every** path that deletes or detaches the resource, not just the obvious one. A resource usually has several (a hard delete, an org-membership removal, a project-membership removal), and each needs its own reap. Call it **inside the delete transaction** and pass `tx`; the reap is pure DB (no KMS or network), so it is safe there. The `(resourceType, resourceId)` index on `alerts` is what keeps the unscoped reap off a seq scan, so a provider whose resource is deleted in bulk depends on it.+**Secret reminders are the exception to reaping on every delete path.** `reminders` stays the source of truth for the schedule (it backs the `secretReminder*` fields on secret responses, Insights and audit reports), the reminder cron emits `secret.reminder.due` into the outbox in the same short transaction that advances the reminder (`reminder-events.ts`), and each reminder's `secret.reminder` alert only holds its channels. An event can only come from a reminder row, and reminder rows cascade with their secret, so an alert left behind by a deleted secret can never fire. The reminder cron therefore reaps orphaned reminder alerts once a day (`reapOrphanedReminderAlerts`) instead of every secret delete path doing it. Do not copy this shortcut to a provider whose alerts can fire without such a row.++**Domain services that own their resource's authorization use the internal entry points** on `alertService` (`createAlertInternal`, `updateAlertInternal`, `findAlertsForResources`, `findRecipientsForResources`, `deleteAlertsForDeletedResources`, `repointAlertsForResource`, `filterRecipientsInScope`). They skip the provider's `assertPermission`, take an explicit creator (`ActorType.PLATFORM` with a null `createdByActorId` for background work) and accept `tx`. The reminder layer (`reminder-service.ts`) is the worked example: it keeps its own interface and callers never import the alert module. Encrypting a channel config can call out to KMS, so it writes the alert before opening its own transaction rather than inside it.++**`project-members` is an email recipient principal for everyone in the channel's project**, expanded at send time by the recipient resolver and still re-checked against org and project scope. It is only valid on a project-scoped channel for that channel's own project.+### Event Outbox (transactional and generic; alerting is its first consumer)`src/services/event-outbox/` writes "this happened" as a row inside the caller's own transaction, sodiff --git a/backend/e2e-test/routes/v1/secret-reminder.spec.ts b/backend/e2e-test/routes/v1/secret-reminder.spec.tsindex 89adfb767e..e66896be46 100644--- a/backend/e2e-test/routes/v1/secret-reminder.spec.ts+++ b/backend/e2e-test/routes/v1/secret-reminder.spec.ts@@ -13,6 +13,7 @@ import { eventOutboxServiceFactory } from "@app/services/event-outbox/event-outbimport { reminderDALFactory } from "@app/services/reminder/reminder-dal";import { reminderServiceFactory } from "@app/services/reminder/reminder-service";+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";@@ -81,7 +82,19 @@ const setReminder = async (secretId: string, body: Record<string, unknown>) => {expect(res.statusCode).toBe(200);};-const reminderAlert = async (secretId: string) => {+type TReminderAlert = {+ id: string;+ name: string;+ channels: {+ id: string;+ name: string;+ channelType: string;+ enabled: boolean;+ recipients: { principalType: string; principalId: string }[];+ }[];+};++const reminderAlert = async (secretId: string): Promise<TReminderAlert[]> => {const res = await testServer.inject({method: "GET",url: "/api/v1/alerts",@@ -89,8 +102,7 @@ const reminderAlert = async (secretId: string) => {query: { resourceType: RESOURCE_TYPE, projectId, resourceId: secretId }});expect(res.statusCode).toBe(200);- const { alerts } = res.json();- return alerts;+ return res.json<{ alerts: TReminderAlert[] }>().alerts;};const reminderAlertRows = (secretId: string) =>@@ -303,4 +315,75 @@ describe("Secret reminders delivered through alerts", async () => {expect(await reminderAlertRows(secretId)).toHaveLength(0);expect(await reminderAlertRows("11111111-1111-4111-8111-111111111111")).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 }+ ]);++ await migrateRemindersToAlerts(testDb);++ 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" })+ ]);+ });++ 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)+ });++ await migrateRemindersToAlerts(testDb);++ const [alert] = await reminderAlert(secretId);+ expect(alert.channels[0].recipients).toEqual([{ principalType: "project-members", principalId: projectId }]);+ });++ 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)+ });++ await migrateRemindersToAlerts(testDb);+ await migrateRemindersToAlerts(testDb);++ expect(await reminderAlertRows(secretId)).toHaveLength(1);+ });++ 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)+ });++ 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/src/db/migrations/20260929130000_migrate-secret-reminders-to-alerts.ts b/backend/src/db/migrations/20260929130000_migrate-secret-reminders-to-alerts.tsnew file mode 100644index 0000000000..0a3399390e--- /dev/null+++ b/backend/src/db/migrations/20260929130000_migrate-secret-reminders-to-alerts.ts@@ -0,0 +1,244 @@+/* eslint-disable no-await-in-loop -- batches run one after another on purpose */+import { Knex } from "knex";++import { inMemoryKeyStore } from "@app/keystore/memory";+import { initLogger, logger } from "@app/lib/logger";+import { resolvePrincipalsInScope } from "@app/services/alert/alert-principal-scope-fns";+import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";+import { KmsDataKey } from "@app/services/kms/kms-types";+import { orgDALFactory } from "@app/services/org/org-dal";+import { projectDALFactory } from "@app/services/project/project-dal";+import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";++import { TableName } from "../schemas";+import { getMigrationEnvConfig, getMigrationHsmConfig } from "./utils/env-config";+import { createCircularCache } from "./utils/ring-buffer";+import { getMigrationEncryptionServices, getMigrationHsmService } from "./utils/services";++// Copied rather than imported so later changes to the reminder or alert code can't change what this+// migration did.+const RESOURCE_TYPE = "secret.reminder";+const EVENT_TYPE = "secret.reminder.due";+const MAX_ALERT_NAME_LENGTH = 255;+const MAX_RECIPIENTS_PER_CHANNEL = 20;+const CATCH_UP_DAYS = 7;+const DAY_MS = 24 * 60 * 60 * 1000;+const BATCH_SIZE = 100;+const BATCH_STATEMENT_TIMEOUT_MS = 60_000;++type TReminderRow = {+ id: string;+ secretId: string;+ secretKey: string;+ projectId: string;+ orgId: string;+};++type TRecipient = { principalType: string; principalId: string };++const startOfUtcDay = (date: Date) => Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());++// Recurring reminders that silently died (a failed send left their date in the past) resume on their+// original schedule from the next future date. Nothing is sent for the dates they missed.+const rollForwardStaleReminders = async (knex: Knex) => {+ const now = new Date();+ const cutoff = new Date(startOfUtcDay(now) - CATCH_UP_DAYS * DAY_MS);+ const endOfToday = startOfUtcDay(now) + DAY_MS - 1;++ const stale = (await knex(TableName.Reminder)+ .whereNotNull("repeatDays")+ .where("repeatDays", ">", 0)+ .where("nextReminderDate", "<", cutoff)+ .select("id", "nextReminderDate", "repeatDays")) as { id: string; nextReminderDate: Date; repeatDays: number }[];++ for (let i = 0; i < stale.length; i += BATCH_SIZE) {+ const batch = stale.slice(i, i + BATCH_SIZE);+ await knex.transaction(async (tx) => {+ await tx.raw(`SET LOCAL statement_timeout = ${BATCH_STATEMENT_TIMEOUT_MS}`);+ for (const reminder of batch) {+ const due = new Date(reminder.nextReminderDate).getTime();+ const periodMs = reminder.repeatDays * DAY_MS;+ const periods = Math.floor((endOfToday - due) / periodMs) + 1;+ await tx(TableName.Reminder)+ .where({ id: reminder.id })+ .update({ nextReminderDate: new Date(due + periods * periodMs) });+ }+ });+ }+ logger.info(`migrate-secret-reminders-to-alerts: rolled forward ${stale.length} stale recurring reminders`);+};++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.Reminder)) || !(await knex.schema.hasTable(TableName.Alert))) return;++ initLogger();++ await rollForwardStaleReminders(knex);++ const hasReminders = await knex(TableName.Reminder).whereNotNull("secretId").first("id");+ if (!hasReminders) return;++ const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });+ const envConfig = await getMigrationEnvConfig(superAdminDALFactory(knex), hsmService, kmsRootConfigDALFactory(knex));+ const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore: inMemoryKeyStore(), db: knex });+ const cipherCache = createCircularCache<Awaited<ReturnType<(typeof kmsService)["createCipherPairWithDataKey"]>>>(25);+ const orgDAL = orgDALFactory(knex as never);+ const projectDAL = projectDALFactory(knex as never);++ let lastId: string | undefined;+ let migrated = 0;++ for (;;) {+ const cursor = lastId;+ const reminders = (await knex(TableName.Reminder)+ .join(TableName.SecretV2, `${TableName.Reminder}.secretId`, `${TableName.SecretV2}.id`)+ .join(TableName.SecretFolder, `${TableName.SecretV2}.folderId`, `${TableName.SecretFolder}.id`)+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)+ .join(TableName.Project, `${TableName.Environment}.projectId`, `${TableName.Project}.id`)+ .modify((qb) => {+ if (cursor) void qb.where(`${TableName.Reminder}.id`, ">", cursor);+ })+ .orderBy(`${TableName.Reminder}.id`, "asc")+ .limit(BATCH_SIZE)+ .select(+ knex.ref("id").withSchema(TableName.Reminder),+ knex.ref("secretId").withSchema(TableName.Reminder),+ knex.ref("key").withSchema(TableName.SecretV2).as("secretKey"),+ knex.ref("id").withSchema(TableName.Project).as("projectId"),+ knex.ref("orgId").withSchema(TableName.Project).as("orgId")+ )) as TReminderRow[];+ if (reminders.length === 0) break;+ lastId = reminders[reminders.length - 1].id;++ // A rerun after a partial failure skips reminders that already have their alert.+ const alreadyMigrated = new Set(+ (+ await knex(TableName.Alert)+ .where({ resourceType: RESOURCE_TYPE })+ .whereIn(+ "resourceId",+ reminders.map((reminder) => reminder.secretId)+ )+ .select("resourceId")+ ).map((row) => row.resourceId as string)+ );+ const pending = reminders.filter((reminder) => !alreadyMigrated.has(reminder.secretId));++ const recipientRows = (await knex(TableName.ReminderRecipient)+ .whereIn(+ "reminderId",+ pending.map((reminder) => reminder.id)+ )+ .select("reminderId", "userId")) as { reminderId: string; userId: string }[];++ const encryptedEmptyConfigByProject = new Map<string, Buffer>();+ for (const projectId of new Set(pending.map((reminder) => reminder.projectId))) {+ let cipher = cipherCache.getItem(projectId);+ if (!cipher) {+ cipher = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId }, knex);+ cipherCache.push(projectId, cipher);+ }+ encryptedEmptyConfigByProject.set(+ projectId,+ cipher.encryptor({ plainText: Buffer.from(JSON.stringify({})) }).cipherTextBlob+ );+ }++ // Reminder recipients were never pruned when someone left a project. Keep only principals the alert+ // module would accept, so the migrated channel can be saved again from the UI.+ const recipientsByReminder = new Map<string, TRecipient[]>();+ for (const reminder of pending) {+ const userIds = [+ ...new Set(recipientRows.filter((row) => row.reminderId === reminder.id).map((row) => row.userId))+ ];+ const inScope = userIds.length+ ? await resolvePrincipalsInScope(+ { orgDAL, projectDAL },+ { orgId: reminder.orgId, projectId: reminder.projectId, userIds, groupIds: [], tx: knex }+ )+ : { userIds: new Set<string>() };+ const kept = userIds.filter((userId) => inScope.userIds.has(userId));+ recipientsByReminder.set(+ reminder.id,+ kept.length+ ? kept.map((principalId) => ({ principalType: "user", principalId }))+ : [{ principalType: "project-members", principalId: reminder.projectId }]+ );+ }++ await knex.transaction(async (tx) => {+ await tx.raw(`SET LOCAL statement_timeout = ${BATCH_STATEMENT_TIMEOUT_MS}`);+ for (const reminder of pending) {+ const [alert] = (await tx(TableName.Alert)+ .insert({+ name: `Reminder for ${reminder.secretKey}`.slice(0, MAX_ALERT_NAME_LENGTH),+ resourceType: RESOURCE_TYPE,+ resourceId: reminder.secretId,+ eventType: EVENT_TYPE,+ triggerType: "event",+ condition: null,+ enabled: true,+ orgId: reminder.orgId,+ projectId: reminder.projectId,+ createdByActorId: null,+ createdByActorType: "platform"+ })+ .returning("id")) as { id: string }[];++ const recipients = recipientsByReminder.get(reminder.id) ?? [];+ for (let i = 0; i < recipients.length; i += MAX_RECIPIENTS_PER_CHANNEL) {+ const channelNumber = i / MAX_RECIPIENTS_PER_CHANNEL + 1;+ const [channel] = (await tx(TableName.AlertChannel)+ .insert({+ name: channelNumber === 1 ? "Email" : `Email ${channelNumber}`,+ channelType: "email",+ encryptedConfig: encryptedEmptyConfigByProject.get(reminder.projectId) as Buffer,+ enabled: true,+ orgId: reminder.orgId,+ projectId: reminder.projectId,+ createdByActorId: null,+ createdByActorType: "platform"+ })+ .returning("id")) as { id: string }[];+ await tx(TableName.AlertChannelMembership).insert({ alertId: alert.id, channelId: channel.id });+ await tx(TableName.AlertChannelRecipient).insert(+ recipients.slice(i, i + MAX_RECIPIENTS_PER_CHANNEL).map((recipient) => ({+ channelId: channel.id,+ principalType: recipient.principalType,+ principalId: recipient.principalId+ }))+ );+ }+ }+ });++ migrated += pending.length;+ }++ logger.info(`migrate-secret-reminders-to-alerts: created alerts for ${migrated} reminders`);+}++export async function down(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.Alert))) return;++ const alertIds = knex(TableName.Alert)+ .where({ resourceType: RESOURCE_TYPE, createdByActorType: "platform" })+ .whereNull("createdByActorId")+ .select("id");+ const channelIds = (await knex(TableName.AlertChannelMembership)+ .whereIn("alertId", alertIds)+ .pluck("channelId")) as string[];++ await knex(TableName.Alert)+ .where({ resourceType: RESOURCE_TYPE, createdByActorType: "platform" })+ .whereNull("createdByActorId")+ .delete();+ for (let i = 0; i < channelIds.length; i += BATCH_SIZE) {+ await knex(TableName.AlertChannel)+ .whereIn("id", channelIds.slice(i, i + BATCH_SIZE))+ .delete();+ }+}++const config = { transaction: false };+export { config };diff --git a/backend/src/services/reminder/reminder-dal.ts b/backend/src/services/reminder/reminder-dal.tsindex f7a7a9cb6c..86c0c5e85b 100644--- a/backend/src/services/reminder/reminder-dal.ts+++ b/backend/src/services/reminder/reminder-dal.ts@@ -3,31 +3,13 @@ import { Knex } from "knex";import { TDbClient } from "@app/db";import { TableName, TProjectEnvironments, TProjects, TSecretFolders, TSecretsV2 } from "@app/db/schemas";import { RemindersSchema } from "@app/db/schemas/reminders";-import { ormify, selectAllTableCols, sqlNestRelationships } from "@app/lib/knex";+import { ormify, selectAllTableCols } from "@app/lib/knex";export type TReminderDALFactory = ReturnType<typeof reminderDALFactory>;export const reminderDALFactory = (db: TDbClient) => {const reminderOrm = ormify(db, TableName.Reminder);- const getTodayDateRange = () => {- const today = new Date();- const year = today.getUTCFullYear();- const month = today.getUTCMonth();- const date = today.getUTCDate();-- // Start of day: 00:00:00.000 UTC- const startOfDay = new Date(Date.UTC(year, month, date, 0, 0, 0, 0));-- // End of day: 23:59:59.999 UTC- const endOfDay = new Date(Date.UTC(year, month, date, 23, 59, 59, 999));-- return {- startOfDay,- endOfDay- };- };-// Due reminders whose secret is still live. Soft-deleted environments and projects keep their// reminders so a restore brings them back, but they do not fire in the meantime.const findDueReminders = async ({ from, to }: { from: Date; to: Date }, tx?: Knex) => {@@ -79,67 +61,20 @@ export const reminderDALFactory = (db: TDbClient) => {return rows.map((row) => row.resourceId);};- const findUpcomingReminders = async (daysAhead: number = 7, tx?: Knex) => {- const { startOfDay } = getTodayDateRange();- const futureDate = new Date(startOfDay);- futureDate.setDate(futureDate.getDate() + daysAhead);-- const reminders = await (tx || db.replicaNode())(TableName.Reminder)- .where("nextReminderDate", ">=", startOfDay)- .where("nextReminderDate", "<=", futureDate)- .orderBy("nextReminderDate", "asc")- .leftJoin(TableName.ReminderRecipient, `${TableName.Reminder}.id`, `${TableName.ReminderRecipient}.reminderId`)- .select(selectAllTableCols(TableName.Reminder))- .select(db.ref("userId").withSchema(TableName.ReminderRecipient));- return reminders;- };-+ // Recipients are not stored here: they live on the reminder's alert email channel.const findSecretReminder = async (secretId: string, tx?: Knex) => {- const rawReminders = await (tx || db.replicaNode())(TableName.Reminder)+ const reminder = await (tx || db.replicaNode())(TableName.Reminder).where(`${TableName.Reminder}.secretId`, secretId)- .leftJoin(TableName.ReminderRecipient, `${TableName.Reminder}.id`, `${TableName.ReminderRecipient}.reminderId`).select(selectAllTableCols(TableName.Reminder))- .select(db.ref("userId").withSchema(TableName.ReminderRecipient));- const reminders = sqlNestRelationships({- data: rawReminders,- key: "id",- parentMapper: (el) => ({- _id: el.id,- ...RemindersSchema.parse(el)- }),- childrenMapper: [- {- key: "userId",- label: "recipients" as const,- mapper: ({ userId }) => userId- }- ]- });- return reminders[0] || null;+ .first();+ return reminder ? RemindersSchema.parse(reminder) : null;};const findSecretReminders = async (secretIds: string[], tx?: Knex) => {- const rawReminders = await (tx || db.replicaNode())(TableName.Reminder)+ const reminders = await (tx || db.replicaNode())(TableName.Reminder).whereIn(`${TableName.Reminder}.secretId`, secretIds)- .leftJoin(TableName.ReminderRecipient, `${TableName.Reminder}.id`, `${TableName.ReminderRecipient}.reminderId`)- .select(selectAllTableCols(TableName.Reminder))- .select(db.ref("userId").withSchema(TableName.ReminderRecipient));- const reminders = sqlNestRelationships({- data: rawReminders,- key: "id",- parentMapper: (el) => ({- _id: el.id,- ...RemindersSchema.parse(el)- }),- childrenMapper: [- {- key: "userId",- label: "recipients" as const,- mapper: ({ userId }) => userId- }- ]- });- return reminders;+ .select(selectAllTableCols(TableName.Reminder));+ return reminders.map((reminder) => RemindersSchema.parse(reminder));};const findByProjectAndDateRange = async (@@ -193,7 +128,6 @@ export const reminderDALFactory = (db: TDbClient) => {...reminderOrm,findDueReminders,findOrphanedReminderAlertResourceIds,- findUpcomingReminders,findSecretReminder,findSecretReminders,findByProjectAndDateRangediff --git a/backend/src/services/reminder/reminder-service.ts b/backend/src/services/reminder/reminder-service.tsindex d5cf2b9c13..db9af8d492 100644--- a/backend/src/services/reminder/reminder-service.ts+++ b/backend/src/services/reminder/reminder-service.ts@@ -541,7 +541,7 @@ export const reminderServiceFactory = ({reminders.map((reminder) => reminder.secretId).filter((id): id is string => Boolean(id)));- const reminderMap: Record<string, (typeof reminders)[number]> = {};+ const reminderMap: Record<string, (typeof reminders)[number] & { recipients: string[] }> = {};reminders.forEach((reminder) => {if (reminder.secretId) {