Skip to content

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

fix(reminders): address review feedback on reminder delivery

Calvineb10e2da2551
diff --git a/backend/e2e-test/routes/v1/secret-reminder.spec.ts b/backend/e2e-test/routes/v1/secret-reminder.spec.ts
index d5c6355e57..fcf01254a7 100644
--- a/backend/e2e-test/routes/v1/secret-reminder.spec.ts
+++ b/backend/e2e-test/routes/v1/secret-reminder.spec.ts
@@ -1,12 +1,10 @@
import { OrgMembershipRole, ProjectMembershipRole } from "@app/db/schemas";
-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 { listAlerts, updateAlert } from "../../testUtils/alerts";
+import { updateAlert } from "../../testUtils/alerts";
import { createIsolatedOrgAndProject } from "../../testUtils/fixtures";
import { createFolder, deleteFolder } from "../../testUtils/folders";
import {
- deleteSecretReminder,
getSecretReminder,
listSecretReminderAlerts,
reapOrphanedReminderAlerts,
@@ -66,37 +64,17 @@ describe("Secret reminders delivered through alerts", () => {
return new Date(reminder?.nextReminderDate as string);
};
- test("setting a reminder creates its alert with an email channel to the recipients", async () => {
- const secretId = await createSecret("CREATE");
- await setSecretReminder({ secretId, authToken, repeatDays: 30, message: "rotate it", recipients: [member.userId] });
-
- 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: member.userId }]
- });
-
- expect(await getSecretReminder({ secretId, authToken })).toMatchObject({
- repeatDays: 30,
- message: "rotate it",
- recipients: [member.userId]
- });
- });
-
- test("a reminder with no recipients notifies all project members", async () => {
- const secretId = await createSecret("EVERYONE");
- await setSecretReminder({ secretId, authToken, repeatDays: 7 });
-
- 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("KEEP_WEBHOOK");
- await setSecretReminder({ secretId, authToken, repeatDays: 30, recipients: [member.userId] });
+ await setSecretReminder({ secretId, authToken, repeatDays: 30, message: "rotate it", recipients: [member.userId] });
const [alert] = await reminderAlerts(secretId);
+ expect(alert.name).toBe("Reminder for KEEP_WEBHOOK");
+ expect(alert.channels).toEqual([
+ expect.objectContaining({
+ channelType: "email",
+ recipients: [{ principalType: "user", principalId: member.userId }]
+ })
+ ]);
await updateAlert({
alertId: alert.id,
@@ -116,6 +94,11 @@ describe("Secret reminders delivered through alerts", () => {
expect(updated.channels.find((channel) => channel.channelType === "email")?.recipients).toEqual([
{ principalType: "project-members", principalId: projectId }
]);
+ expect(await getSecretReminder({ secretId, authToken })).toMatchObject({
+ repeatDays: 14,
+ message: "rotate it",
+ recipients: []
+ });
});
test("the secret listing reports recipients from the reminder's alert", async () => {
@@ -137,11 +120,6 @@ describe("Secret reminders delivered through alerts", () => {
expect(secret.secretReminderRecipients.map((recipient) => recipient.user.id)).toEqual([member.userId]);
});
- test("listing reminder alerts across a project is refused", async () => {
- 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,
@@ -197,26 +175,6 @@ describe("Secret reminders delivered through alerts", () => {
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("ONE_OFF");
- const dueDate = new Date(Date.now() + DAY_MS);
- await setSecretReminder({ secretId, authToken, nextReminderDate: dueDate.toISOString() });
-
- await runDailyReminders({ now: dueDate });
-
- 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("DELETE_REMINDER");
- await setSecretReminder({ secretId, authToken, repeatDays: 30 });
-
- await deleteSecretReminder({ secretId, authToken });
- expect(await reminderAlerts(secretId)).toHaveLength(0);
- });
-
// 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.
@@ -259,14 +217,17 @@ describe("Secret reminders delivered through alerts", () => {
test("gives existing reminders an alert, keeping only recipients still in the project", async () => {
const secretId = await createSecret("MIGRATE");
+ const everyoneSecretId = await createSecret("MIGRATE_EVERYONE");
+ const nobodyLeftSecretId = await createSecret("MIGRATE_NOBODY_LEFT");
const outsider = await createUser("reminder-outsider");
- const reminderId = await seedReminder(secretId, {
- repeatDays: 30,
- nextReminderDate: new Date(Date.now() + DAY_MS)
- });
+ const dueDate = new Date(Date.now() + DAY_MS);
+ const reminderId = await seedReminder(secretId, { repeatDays: 30, nextReminderDate: dueDate });
+ await seedReminder(everyoneSecretId, { repeatDays: 7, nextReminderDate: dueDate });
+ const nobodyLeftReminderId = await seedReminder(nobodyLeftSecretId, { repeatDays: 7, nextReminderDate: dueDate });
await testDb("reminders_recipients").insert([
{ reminderId, userId: member.userId },
- { reminderId, userId: outsider.userId }
+ { reminderId, userId: outsider.userId },
+ { reminderId: nobodyLeftReminderId, userId: outsider.userId }
]);
await migrateRemindersToAlerts(testDb);
@@ -280,16 +241,15 @@ describe("Secret reminders delivered through alerts", () => {
createdByActorType: "platform",
createdByActorId: null
});
- });
- 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) });
-
- await migrateRemindersToAlerts(testDb);
+ // A reminder that never listed anyone keeps its meaning: everyone in the project.
+ const [everyoneAlert] = await reminderAlerts(everyoneSecretId);
+ expect(everyoneAlert.channels[0].recipients).toEqual([
+ { principalType: "project-members", principalId: projectId }
+ ]);
- const [alert] = await reminderAlerts(secretId);
- expect(alert.channels[0].recipients).toEqual([{ principalType: "project-members", principalId: projectId }]);
+ // One whose listed recipients have all left gets no alert, rather than one to people nobody chose.
+ expect(await reminderAlerts(nobodyLeftSecretId)).toHaveLength(0);
});
test("rerunning does not duplicate alerts", async () => {
diff --git a/backend/e2e-test/testUtils/alerts.ts b/backend/e2e-test/testUtils/alerts.ts
index 679091f5c5..53369f3e85 100644
--- a/backend/e2e-test/testUtils/alerts.ts
+++ b/backend/e2e-test/testUtils/alerts.ts
@@ -1,6 +1,6 @@
import { request } from "./request";
-export type TAlertRecord = {
+type TAlertRecord = {
id: string;
name: string;
channels: {
@@ -12,17 +12,13 @@ export type TAlertRecord = {
}[];
};
-export const listAlerts = (dto: { resourceType: string; projectId: string; resourceId?: string; authToken: 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 } : {})
- }
+ query: { resourceType: dto.resourceType, projectId: dto.projectId, resourceId: dto.resourceId }
},
(res) => {
expect(res.statusCode).toBe(200);
diff --git a/backend/e2e-test/testUtils/reminders.ts b/backend/e2e-test/testUtils/reminders.ts
index 24ad5dd27d..eb2aa7972f 100644
--- a/backend/e2e-test/testUtils/reminders.ts
+++ b/backend/e2e-test/testUtils/reminders.ts
@@ -18,7 +18,7 @@ type TReminderRecord = {
recipients?: string[];
};
-export type TSetSecretReminderBody = {
+type TSetSecretReminderBody = {
message?: string;
repeatDays?: number | null;
nextReminderDate?: string | null;
@@ -54,20 +54,13 @@ 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, resourceId: dto.secretId, ...dto });
+ listAlerts({
+ resourceType: SECRET_REMINDER_RESOURCE_TYPE,
+ projectId: dto.projectId,
+ resourceId: dto.secretId,
+ authToken: dto.authToken
+ });
// 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.
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.ts
index 0a3399390e..820033362c 100644
--- a/backend/src/db/migrations/20260929130000_migrate-secret-reminders-to-alerts.ts
+++ b/backend/src/db/migrations/20260929130000_migrate-secret-reminders-to-alerts.ts
@@ -80,13 +80,19 @@ export async function up(knex: Knex): Promise<void> {
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 { kmsService } = await getMigrationEncryptionServices({
+ envConfig,
+ keyStore: inMemoryKeyStore(),
+ db: knex,
+ skipHsmLicenseCheck: true
+ });
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;
+ let skipped = 0;
for (;;) {
const cursor = lastId;
@@ -145,7 +151,9 @@ export async function up(knex: Knex): Promise<void> {
}
// 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.
+ // module would accept, so the migrated channel can be saved again from the UI. A reminder whose
+ // listed recipients have all left gets no alert rather than one to the whole project: nobody chose
+ // that audience, and it would see the secret's key, path and note.
const recipientsByReminder = new Map<string, TRecipient[]>();
for (const reminder of pending) {
const userIds = [
@@ -158,17 +166,21 @@ export async function up(knex: Knex): Promise<void> {
)
: { 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 }]
- );
+ if (userIds.length && !kept.length) {
+ skipped += 1;
+ } else {
+ 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) {
+ for (const reminder of pending.filter(({ id }) => recipientsByReminder.has(id))) {
const [alert] = (await tx(TableName.Alert)
.insert({
name: `Reminder for ${reminder.secretKey}`.slice(0, MAX_ALERT_NAME_LENGTH),
@@ -185,7 +197,7 @@ export async function up(knex: Knex): Promise<void> {
})
.returning("id")) as { id: string }[];
- const recipients = recipientsByReminder.get(reminder.id) ?? [];
+ const recipients = recipientsByReminder.get(reminder.id) as TRecipient[];
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)
@@ -212,27 +224,35 @@ export async function up(knex: Knex): Promise<void> {
}
});
- migrated += pending.length;
+ migrated += recipientsByReminder.size;
}
- logger.info(`migrate-secret-reminders-to-alerts: created alerts for ${migrated} reminders`);
+ logger.info(
+ `migrate-secret-reminders-to-alerts: created alerts for ${migrated} reminders, skipped ${skipped} whose recipients have all left their project`
+ );
}
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");
+ // Background work also creates platform reminder alerts after the backfill (eg a reminder set through a
+ // secret update), so only the alerts that existed when this migration finished are its own. The record
+ // is named .ts or .mjs depending on how the migrations were run.
+ const record = await knex("infisical_migrations")
+ .where("name", "like", "20260929130000_migrate-secret-reminders-to-alerts.%")
+ .first("migration_time");
+ if (!record) return;
+
+ const backfilledAlerts = () =>
+ knex(TableName.Alert)
+ .where({ resourceType: RESOURCE_TYPE, createdByActorType: "platform" })
+ .whereNull("createdByActorId")
+ .where("createdAt", "<=", record.migration_time);
const channelIds = (await knex(TableName.AlertChannelMembership)
- .whereIn("alertId", alertIds)
+ .whereIn("alertId", backfilledAlerts().select("id"))
.pluck("channelId")) as string[];
- await knex(TableName.Alert)
- .where({ resourceType: RESOURCE_TYPE, createdByActorType: "platform" })
- .whereNull("createdByActorId")
- .delete();
+ await backfilledAlerts().delete();
for (let i = 0; i < channelIds.length; i += BATCH_SIZE) {
await knex(TableName.AlertChannel)
.whereIn("id", channelIds.slice(i, i + BATCH_SIZE))
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 6978024fa9..facdc6c7cd 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1092,7 +1092,8 @@ export const registerRoutes = async (
userGroupMembershipDAL,
orgDAL,
projectDAL,
- projectMembershipDAL
+ projectMembershipDAL,
+ groupProjectDAL
});
const alertEngine = alertEngineFactory({
alertChannelDAL,
diff --git a/backend/src/server/routes/v1/alert-channel-schemas.ts b/backend/src/server/routes/v1/alert-channel-schemas.ts
new file mode 100644
index 0000000000..e9ee22c904
--- /dev/null
+++ b/backend/src/server/routes/v1/alert-channel-schemas.ts
@@ -0,0 +1,26 @@
+import { z } from "zod";
+
+import { AlertChannelType } from "@app/services/alert/alert-channel-types";
+import { AlertPrincipalType, MAX_RECIPIENTS_PER_CHANNEL } from "@app/services/alert/alert-types";
+
+export const ChannelRecipientSchema = z.object({
+ principalType: z.nativeEnum(AlertPrincipalType),
+ principalId: z.string().min(1)
+});
+
+export const CreateChannelInputSchema = z.object({
+ name: z.string().min(1).max(255),
+ channelType: z.nativeEnum(AlertChannelType),
+ config: z.record(z.unknown()).default({}),
+ enabled: z.boolean().optional(),
+ recipients: z.array(ChannelRecipientSchema).max(MAX_RECIPIENTS_PER_CHANNEL).optional()
+});
+
+export const UpdateChannelInputSchema = z.object({
+ id: z.string().uuid().optional(),
+ name: z.string().min(1).max(255),
+ channelType: z.nativeEnum(AlertChannelType),
+ config: z.record(z.unknown()).optional(),
+ enabled: z.boolean().optional(),
+ recipients: z.array(ChannelRecipientSchema).max(MAX_RECIPIENTS_PER_CHANNEL).optional()
+});
diff --git a/backend/src/server/routes/v1/alert-router.ts b/backend/src/server/routes/v1/alert-router.ts
index a4ca960e77..24b96d551c 100644
--- a/backend/src/server/routes/v1/alert-router.ts
+++ b/backend/src/server/routes/v1/alert-router.ts
@@ -4,34 +4,10 @@ import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AlertChannelType } from "@app/services/alert/alert-channel-types";
-import {
- AlertPrincipalType,
- MAX_CHANNELS_PER_ALERT,
- MAX_RECIPIENTS_PER_CHANNEL
-} from "@app/services/alert/alert-types";
+import { MAX_CHANNELS_PER_ALERT, MAX_RECIPIENTS_PER_CHANNEL } from "@app/services/alert/alert-types";
import { AuthMode } from "@app/services/auth/auth-type";
-const ChannelRecipientSchema = z.object({
- principalType: z.nativeEnum(AlertPrincipalType),
- principalId: z.string().min(1)
-});
-
-const CreateChannelInputSchema = z.object({
- name: z.string().min(1).max(255),
- channelType: z.nativeEnum(AlertChannelType),
- config: z.record(z.unknown()).default({}),
- enabled: z.boolean().optional(),
- recipients: z.array(ChannelRecipientSchema).max(MAX_RECIPIENTS_PER_CHANNEL).optional()
-});
-
-const UpdateChannelInputSchema = z.object({
- id: z.string().uuid().optional(),
- name: z.string().min(1).max(255),
- channelType: z.nativeEnum(AlertChannelType),
- config: z.record(z.unknown()).optional(),
- enabled: z.boolean().optional(),
- recipients: z.array(ChannelRecipientSchema).max(MAX_RECIPIENTS_PER_CHANNEL).optional()
-});
+import { ChannelRecipientSchema, CreateChannelInputSchema, UpdateChannelInputSchema } from "./alert-channel-schemas";
const AlertResponseSchema = z.object({
id: z.string().uuid(),
diff --git a/backend/src/server/routes/v1/reminder-routers/secret-reminder-router.ts b/backend/src/server/routes/v1/reminder-routers/secret-reminder-router.ts
index a8d8f55c78..ebd7396678 100644
--- a/backend/src/server/routes/v1/reminder-routers/secret-reminder-router.ts
+++ b/backend/src/server/routes/v1/reminder-routers/secret-reminder-router.ts
@@ -5,9 +5,12 @@ import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { MAX_CHANNELS_PER_ALERT } from "@app/services/alert/alert-types";
import { AuthMode } from "@app/services/auth/auth-type";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+import { UpdateChannelInputSchema } from "../alert-channel-schemas";
+
export const registerSecretReminderRouter = async (server: FastifyZodProvider) => {
server.route({
url: "/:secretId",
@@ -25,7 +28,9 @@ export const registerSecretReminderRouter = async (server: FastifyZodProvider) =
repeatDays: z.number().min(1).nullable().optional(),
nextReminderDate: z.string().datetime().nullable().optional(),
fromDate: z.string().datetime().nullable().optional(),
- recipients: z.string().array().optional()
+ recipients: z.string().array().optional(),
+ // The reminder alert's complete channel list, saved with the schedule. Replaces `recipients`.
+ channels: z.array(UpdateChannelInputSchema).min(1).max(MAX_CHANNELS_PER_ALERT).optional()
})
.refine((data) => {
return data.repeatDays || data.nextReminderDate;
@@ -49,7 +54,8 @@ export const registerSecretReminderRouter = async (server: FastifyZodProvider) =
repeatDays: req.body.repeatDays,
nextReminderDate: req.body.nextReminderDate,
fromDate: req.body.fromDate,
- recipients: req.body.recipients
+ recipients: req.body.recipients,
+ channels: req.body.channels
}
});
diff --git a/backend/src/services/alert/alert-recipient-resolver.test.ts b/backend/src/services/alert/alert-recipient-resolver.test.ts
index 9343a40b91..662fbdc294 100644
--- a/backend/src/services/alert/alert-recipient-resolver.test.ts
+++ b/backend/src/services/alert/alert-recipient-resolver.test.ts
@@ -14,6 +14,7 @@ const buildResolver = (opts: {
effectiveProjectUserIds?: string[]; // users currently effective in the project
effectiveProjectGroupIds?: string[]; // groups currently holding a project membership
projectMemberUserIds?: string[]; // users a project member listing returns
+ projectGroupMemberUserIds?: string[]; // users a project group member listing returns
}) => {
const usersById = new Map(opts.users.map((u) => [u.id, u]));
return alertRecipientResolverFactory({
@@ -59,6 +60,9 @@ const buildResolver = (opts: {
} as never,
projectMembershipDAL: {
findAllProjectMembers: async () => (opts.projectMemberUserIds ?? []).map((id) => ({ user: { id } }))
+ } as never,
+ groupProjectDAL: {
+ findAllProjectGroupMembers: async () => (opts.projectGroupMemberUserIds ?? []).map((id) => ({ user: { id } }))
} as never
});
};
@@ -253,6 +257,27 @@ describe("alert recipient resolver — all project members", () => {
});
+ test("includes members who are in the project only through a group", async () => {
+ const resolver = buildResolver({
+ users: [user("u1"), user("u2")],
+ projectMemberUserIds: ["u1"],
+ projectGroupMemberUserIds: ["u1", "u2"],
+ effectiveProjectUserIds: ["u1", "u2"]
+ });
+
+ const result = await resolver.resolveMany(
+ new Map([["c1", [{ principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "proj-1" }]]]),
+ { orgId: "org-1", projectId: "proj-1" }
+ );
+
+ expect(
+ result
+ .get("c1")
+ ?.map((r) => r.email)
+ .sort()
+ });
+
test("still drops members whose org membership was deactivated", async () => {
const resolver = buildResolver({
users: [user("u1"), user("u2")],
diff --git a/backend/src/services/alert/alert-recipient-resolver.ts b/backend/src/services/alert/alert-recipient-resolver.ts
index fd1d00911b..7ac4dee7c7 100644
--- a/backend/src/services/alert/alert-recipient-resolver.ts
+++ b/backend/src/services/alert/alert-recipient-resolver.ts
@@ -1,5 +1,6 @@
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { logger } from "@app/lib/logger";
+import { TGroupProjectDALFactory } from "@app/services/group-project/group-project-dal";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TProjectMembershipDALFactory } from "@app/services/project-membership/project-membership-dal";
@@ -15,6 +16,7 @@ type TAlertRecipientResolverDep = {
orgDAL: Pick<TOrgDALFactory, "findMembership">;
projectDAL: Pick<TProjectDALFactory, "findEffectiveProjectSubjectsMembership">;
projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findAllProjectMembers">;
+ groupProjectDAL: Pick<TGroupProjectDALFactory, "findAllProjectGroupMembers">;
};
type TResolvableRecipient = { principalType: string; principalId: string };
@@ -28,7 +30,8 @@ export const alertRecipientResolverFactory = ({
userGroupMembershipDAL,
orgDAL,
projectDAL,
- projectMembershipDAL
+ projectMembershipDAL,
+ groupProjectDAL
}: TAlertRecipientResolverDep) => {
const resolveMany = async (
rowsByChannel: Map<string, TResolvableRecipient[]>,
@@ -64,8 +67,13 @@ export const alertRecipientResolverFactory = ({
);
const projectMemberIds: string[] = [];
if (wantsProjectMembers && scope.projectId) {
- const members = await projectMembershipDAL.findAllProjectMembers(scope.projectId);
- members.forEach((member) => {
+ // Direct members and members through a project group, so "everyone in the project" matches who
+ // the scope check below lets through.
+ const [directMembers, projectGroupMembers] = await Promise.all([
+ projectMembershipDAL.findAllProjectMembers(scope.projectId),
+ groupProjectDAL.findAllProjectGroupMembers(scope.projectId)
+ ]);
+ [...directMembers, ...projectGroupMembers].forEach((member) => {
projectMemberIds.push(member.user.id);
allUserIds.add(member.user.id);
});
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 424a79f869..7089430c23 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
@@ -89,6 +89,7 @@ describe("secret reminder alert provider", () => {
{
orgId: "org-1",
projectId: "proj-1",
+ reminderId: "rem-1",
secretId: "secret-1",
note: "rotate it",
repeatDays: 30,
diff --git a/backend/src/services/reminder/reminder-dal.ts b/backend/src/services/reminder/reminder-dal.ts
index 86c0c5e85b..4c30d7cf76 100644
--- a/backend/src/services/reminder/reminder-dal.ts
+++ b/backend/src/services/reminder/reminder-dal.ts
@@ -61,6 +61,11 @@ export const reminderDALFactory = (db: TDbClient) => {
return rows.map((row) => row.resourceId);
};
+ const findByIdForUpdate = async (id: string, tx: Knex) => {
+ const reminder = await tx(TableName.Reminder).where({ id }).forUpdate().first();
+ return reminder;
+ };
+
// Recipients are not stored here: they live on the reminder's alert email channel.
const findSecretReminder = async (secretId: string, tx?: Knex) => {
const reminder = await (tx || db.replicaNode())(TableName.Reminder)
@@ -127,6 +132,7 @@ export const reminderDALFactory = (db: TDbClient) => {
return {
...reminderOrm,
findDueReminders,
+ findByIdForUpdate,
findOrphanedReminderAlertResourceIds,
findSecretReminder,
findSecretReminders,
diff --git a/backend/src/services/reminder/reminder-events.ts b/backend/src/services/reminder/reminder-events.ts
index cd7a2459df..f76d28a6e8 100644
--- a/backend/src/services/reminder/reminder-events.ts
+++ b/backend/src/services/reminder/reminder-events.ts
@@ -17,6 +17,7 @@ export const SecretReminderDuePayloadSchema = z.object({
export type TSecretReminderDueInput = {
orgId: string;
projectId: string;
+ reminderId: string;
secretId: string;
note?: string | null;
repeatDays?: number | null;
@@ -25,14 +26,15 @@ export type TSecretReminderDueInput = {
export const emitSecretReminderDue = (
eventEmitter: TEventEmitter,
- { orgId, projectId, secretId, note, repeatDays, occurrenceDate }: TSecretReminderDueInput,
+ { orgId, projectId, reminderId, secretId, note, repeatDays, occurrenceDate }: TSecretReminderDueInput,
tx: Knex
): Promise<void> =>
eventEmitter.emit(
{
eventType: SECRET_REMINDER_DUE_EVENT,
- // A cron retry after a partial run must not send the same occurrence twice.
- idempotencyKey: `${SECRET_REMINDER_DUE_EVENT}:${secretId}:${occurrenceDate}`,
+ // A cron retry after a partial run must not send the same occurrence twice. Keyed on the reminder
+ // rather than the secret, so a reminder deleted and set again for a date that already fired still sends.
+ idempotencyKey: `${SECRET_REMINDER_DUE_EVENT}:${reminderId}:${occurrenceDate}`,
payload: {
orgId,
projectId,
diff --git a/backend/src/services/reminder/reminder-service.test.ts b/backend/src/services/reminder/reminder-service.test.ts
index 80f49cc0d3..ebe40189a7 100644
--- a/backend/src/services/reminder/reminder-service.test.ts
+++ b/backend/src/services/reminder/reminder-service.test.ts
@@ -1,3 +1,4 @@
+import { createMongoAbility } from "@casl/ability";
import { vi } from "vitest";
import { SECRET_REMINDER_DUE_EVENT, SECRET_REMINDER_RESOURCE_TYPE } from "./reminder-events";
@@ -28,6 +29,8 @@ const reminder = (over: Partial<TDueReminder> = {}): TDueReminder => ({
const buildService = (opts: {
due?: TDueReminder[];
+ // The row as the dispatch transaction reads it back; defaults to the row as it was found due.
+ current?: (due: TDueReminder) => TDueReminder | undefined;
emitFails?: (secretId: string) => boolean;
orphanBatches?: string[][];
}) => {
@@ -46,6 +49,11 @@ const buildService = (opts: {
window = range;
return opts.due ?? [];
},
+ findByIdForUpdate: async (id: string) => {
+ const due = (opts.due ?? []).find((row) => row.id === id);
+ if (!due) return undefined;
+ return opts.current ? opts.current(due) : due;
+ },
transaction: async (cb: (tx: unknown) => Promise<unknown>) => {
const tx = { id: `tx-${log.length}` };
log.push("begin");
@@ -98,7 +106,7 @@ describe("reminder dispatch", () => {
expect(emitted).toHaveLength(1);
expect(emitted[0]).toMatchObject({
eventType: SECRET_REMINDER_DUE_EVENT,
- idempotencyKey: `${SECRET_REMINDER_DUE_EVENT}:secret-1:2026-10-10`,
+ idempotencyKey: `${SECRET_REMINDER_DUE_EVENT}:rem-1:2026-10-10`,
payload: {
orgId: "org-1",
projectId: "proj-1",
@@ -146,6 +154,24 @@ describe("reminder dispatch", () => {
expect(updates.map((update) => update.id)).toEqual(["rem-2"]);
});
+ test("skips a reminder cancelled after the due list was read", async () => {
+ const { service, emitted, updates, deletes } = buildService({ due: [reminder()], current: () => undefined });
+ await service.dispatchDueReminders({ now });
+ expect(emitted).toHaveLength(0);
+ expect(updates).toHaveLength(0);
+ expect(deletes).toHaveLength(0);
+ });
+
+ test("leaves a reminder rescheduled after the due list was read on its new date", async () => {
+ const { service, emitted, updates } = buildService({
+ due: [reminder()],
+ current: (due) => ({ ...due, nextReminderDate: new Date("2026-12-01T00:00:00.000Z") })
+ });
+ await service.dispatchDueReminders({ now });
+ expect(emitted).toHaveLength(0);
+ expect(updates).toHaveLength(0);
+ });
+
test("skips a reminder with no secret", async () => {
const { service, emitted } = buildService({ due: [reminder({ secretId: null })] });
await service.dispatchDueReminders({ now });
@@ -204,9 +230,21 @@ const buildWriteService = (opts: { existingAlert?: TStoredAlert; projectUserIds?
eventEmitter: { emit: async () => {} },
projectDAL: { findById: async () => ({ id: "proj-1", orgId: "org-1" }) },
secretV2BridgeDAL: {
- findOneWithTags: async () => ({ id: "secret-1", key: "DB_PASSWORD", projectId: "proj-1" }),
+ findOneWithTags: async () => ({
+ id: "secret-1",
+ key: "DB_PASSWORD",
+ projectId: "proj-1",
+ folderId: "folder-1",
+ tags: []
+ }),
invalidateSecretCacheByProjectId: async () => {}
},
+ folderDAL: {
+ findSecretPathByFolderIds: async () => [{ id: "folder-1", path: "/", environmentSlug: "dev" }]
+ },
+ permissionService: {
+ getProjectPermission: async () => ({ permission: createMongoAbility([{ action: "manage", subject: "all" }]) })
+ },
alertService: {
filterRecipientsInScope: async (_scope: unknown, recipients: { principalType: string; principalId: string }[]) =>
opts.projectUserIds ? recipients.filter((r) => opts.projectUserIds!.includes(r.principalId)) : recipients,
@@ -296,12 +334,41 @@ describe("reminder alert sync", () => {
]);
});
- test("falls back to everyone when every listed recipient has left", async () => {
- const { service, created } = buildWriteService({ projectUserIds: [] });
- await service.createReminderInternal(createInput(["user-gone"]));
- expect((created[0] as { channels: { recipients: unknown }[] }).channels[0].recipients).toEqual([
- { principalType: "project-members", principalId: "proj-1" }
- ]);
+ test("refuses a recipient list with nobody left in the project rather than sending to everyone", async () => {
+ const { service, calls } = buildWriteService({ projectUserIds: [] });
+ await expect(service.createReminderInternal(createInput(["user-gone"]))).rejects.toThrow(
+ /None of the selected reminder recipients/
+ );
+ expect(calls).toEqual([]);
+ });
+
+ test("given channels, saves them as the alert's complete channel list", async () => {
+ const channels = [
+ {
+ name: "Email",
+ channelType: "email",
+ recipients: [{ principalType: "group", principalId: "group-1" }]
+ },
+ { name: "Webhook", channelType: "webhook", config: { url: "https://example.com" } }
+ ];
+ const save = (service: ReturnType<typeof buildWriteService>["service"]) =>
+ service.createReminder({
+ actor: "user",
+ actorId: "user-1",
+ actorOrgId: "org-1",
+ actorAuthMethod: null,
+ reminder: { secretId: "secret-1", repeatDays: 30, recipients: ["user-1"], channels }
+ } as never);
+
+ const existing = buildWriteService({
+ existingAlert: { id: "alert-1", name: "Reminder for OLD_NAME", resourceId: "secret-1", channels: [] }
+ });
+ await save(existing.service);
+ expect(existing.updated).toEqual([{ alertId: "alert-1", name: "Reminder for DB_PASSWORD", channels }]);
+
+ const fresh = buildWriteService();
+ await save(fresh.service);
+ expect(fresh.created).toEqual([expect.objectContaining({ resourceId: "secret-1", channels })]);
});
test("more than 20 recipients are split across email channels", async () => {
diff --git a/backend/src/services/reminder/reminder-service.ts b/backend/src/services/reminder/reminder-service.ts
index 7ea024d2f5..7f849cd072 100644
--- a/backend/src/services/reminder/reminder-service.ts
+++ b/backend/src/services/reminder/reminder-service.ts
@@ -80,38 +80,68 @@ export const reminderServiceFactory = ({
return bySecret;
};
- // The reminder API only knows user ids, so it owns the alert's email channels and leaves every other
- // channel (Slack, webhook, PagerDuty) as the user configured it. An empty list keeps the reminder's
- // original meaning: everyone in the project.
+ // Given `channels`, they are the alert's complete channel list. Otherwise the reminder API only knows
+ // user ids, so it owns the alert's email channels and leaves every other channel (Slack, webhook,
+ // PagerDuty) as the user configured it. An empty list keeps the reminder's original meaning: everyone
+ // in the project.
const $syncReminderAlert = async ({
secretId,
secretKey,
projectId,
recipients,
+ channels,
createdBy
}: {
secretId: string;
secretKey: string;
projectId: string;
recipients?: string[] | null;
+ channels?: TAlertChannelInput[];
createdBy: { actorType: ActorType; actorId: string | null };
}) => {
const project = await projectDAL.findById(projectId);
if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
+ const [existing] = await alertService.findAlertsForResources({
+ resourceType: SECRET_REMINDER_RESOURCE_TYPE,
+ resourceIds: [secretId]
+ });
+
+ if (channels) {
+ if (existing) {
+ await alertService.updateAlertInternal({ alertId: existing.id, name: reminderAlertName(secretKey), channels });
+ } else {
+ await alertService.createAlertInternal({
+ name: reminderAlertName(secretKey),
+ resourceType: SECRET_REMINDER_RESOURCE_TYPE,
+ resourceId: secretId,
+ eventType: SECRET_REMINDER_DUE_EVENT,
+ condition: null,
+ orgId: project.orgId,
+ projectId,
+ channels,
+ createdBy
+ });
+ }
+ return;
+ }
+
// 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 },
- [...new Set(recipients ?? [])].map((principalId) => ({ principalType: AlertPrincipalType.USER, principalId }))
+ 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
+ // chose, so a list with nobody left in it is refused instead.
+ if (requested.length && !inScope.length) {
+ throw new BadRequestError({
+ message: "None of the selected reminder recipients are members of this project. Choose recipients again."
+ });
+ }
const emailRecipients = inScope.length
? inScope
: [{ principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: projectId }];
-
- const [existing] = await alertService.findAlertsForResources({
- resourceType: SECRET_REMINDER_RESOURCE_TYPE,
- resourceIds: [secretId]
- });
const existingEmailChannels =
existing?.channels.filter((channel) => channel.channelType === AlertChannelType.EMAIL) ?? [];
@@ -188,6 +218,7 @@ export const reminderServiceFactory = ({
repeatDays,
nextReminderDate: nextReminderDateInput,
recipients,
+ channels,
projectId,
fromDate: fromDateInput,
createdBy
@@ -198,6 +229,7 @@ export const reminderServiceFactory = ({
repeatDays?: number | null;
nextReminderDate?: string | null;
recipients?: string[] | null;
+ channels?: TAlertChannelInput[];
fromDate?: string | null;
projectId: string;
createdBy: { actorType: ActorType; actorId: string | null };
@@ -223,7 +255,7 @@ export const reminderServiceFactory = ({
// The alert goes first, outside any transaction because encrypting channel config can call out to
// KMS. If the reminder write then fails, an alert with no reminder never fires and is reused next time.
- await $syncReminderAlert({ secretId, secretKey, projectId, recipients, createdBy });
+ await $syncReminderAlert({ secretId, secretKey, projectId, recipients, channels, createdBy });
const existingReminder = await reminderDAL.findOne({ secretId });
let reminderId: string;
@@ -346,22 +378,28 @@ export const reminderServiceFactory = ({
try {
// Delivery happens in the alert module after commit, so nothing slow runs in this transaction.
await reminderDAL.transaction(async (tx) => {
+ // The due list was read before this transaction, so a reminder cancelled or rescheduled since
+ // must not fire on its old date or have its new one overwritten.
+ const current = await reminderDAL.findByIdForUpdate(reminder.id, tx);
+ if (!current || current.nextReminderDate.getTime() !== reminder.nextReminderDate.getTime()) return;
+
await emitSecretReminderDue(
eventEmitter,
{
orgId: reminder.orgId,
projectId: reminder.projectId,
+ reminderId: reminder.id,
secretId,
- note: reminder.message,
- repeatDays: reminder.repeatDays,
- occurrenceDate: toUtcDateString(reminder.nextReminderDate)
+ note: current.message,
+ repeatDays: current.repeatDays,
+ occurrenceDate: toUtcDateString(current.nextReminderDate)
},
tx
);
- if (reminder.repeatDays) {
+ if (current.repeatDays) {
await reminderDAL.updateById(
reminder.id,
- { nextReminderDate: advanceReminderDate(reminder.nextReminderDate, reminder.repeatDays, now) },
+ { nextReminderDate: advanceReminderDate(current.nextReminderDate, current.repeatDays, now) },
tx
);
} else {
diff --git a/backend/src/services/reminder/reminder-types.ts b/backend/src/services/reminder/reminder-types.ts
index defc8ad19a..0b05fcea3b 100644
--- a/backend/src/services/reminder/reminder-types.ts
+++ b/backend/src/services/reminder/reminder-types.ts
@@ -1,5 +1,6 @@
import { Knex } from "knex";
+import { TAlertChannelInput } from "../alert/alert-channel-service-types";
import { ActorAuthMethod, ActorType } from "../auth/auth-type";
export type TReminder = {
@@ -25,6 +26,7 @@ export type TCreateReminderDTO = {
fromDate?: string | null;
nextReminderDate?: string | null;
recipients?: string[] | null;
+ channels?: TAlertChannelInput[];
};
};
diff --git a/backend/src/services/secret/secret-queue.ts b/backend/src/services/secret/secret-queue.ts
index 6d896cdd7c..99cb2d2495 100644
--- a/backend/src/services/secret/secret-queue.ts
+++ b/backend/src/services/secret/secret-queue.ts
@@ -303,6 +303,7 @@ export const secretQueueFactory = ({
});
} catch (err) {
logger.error(err, "Failed to create secret reminder.");
+ if (err instanceof BadRequestError) throw err;
throw new BadRequestError({
name: "SecretReminderCreateFailed",
message: "Failed to create secret reminder."
diff --git a/frontend/src/hooks/api/reminders/queries.tsx b/frontend/src/hooks/api/reminders/queries.tsx
index 557bc24eac..eb9baa6c7a 100644
--- a/frontend/src/hooks/api/reminders/queries.tsx
+++ b/frontend/src/hooks/api/reminders/queries.tsx
@@ -12,7 +12,14 @@ export const useCreateReminder = (secretId: string) => {
const queryClient = useQueryClient();
return useMutation<Reminder, object, CreateReminderDTO>({
- mutationFn: async ({ message, repeatDays, nextReminderDate, recipients, fromDate }) => {
+ mutationFn: async ({
+ message,
+ repeatDays,
+ nextReminderDate,
+ recipients,
+ fromDate,
+ channels
+ }) => {
const { data } = await apiRequest.post<{ reminder: Reminder }>(
`/api/v1/reminders/secrets/${secretId}`,
{
@@ -20,7 +27,8 @@ export const useCreateReminder = (secretId: string) => {
repeatDays,
nextReminderDate,
recipients,
- fromDate
+ fromDate,
+ channels
}
);
return data.reminder;
diff --git a/frontend/src/hooks/api/reminders/types.ts b/frontend/src/hooks/api/reminders/types.ts
index cbe96aeaf5..d4bb0fb636 100644
--- a/frontend/src/hooks/api/reminders/types.ts
+++ b/frontend/src/hooks/api/reminders/types.ts
@@ -1,3 +1,5 @@
+import { TAlertChannelInput } from "../alerts/types";
+
export type CreateReminderDTO = {
message?: string | null;
repeatDays?: number | null;
@@ -5,6 +7,7 @@ export type CreateReminderDTO = {
fromDate?: Date | null;
secretId: string;
recipients?: string[];
+ channels?: TAlertChannelInput[];
};
export type DeleteReminderDTO = {
@@ -12,4 +15,4 @@ export type DeleteReminderDTO = {
reminderId: string;
};
-export type Reminder = { id: string } & CreateReminderDTO;
+export type Reminder = { id: string } & Omit<CreateReminderDTO, "channels">;
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretEditTableRow.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretEditTableRow.tsx
index ff9326b9eb..06339e44a4 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretEditTableRow.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretEditTableRow.tsx
@@ -1233,7 +1233,7 @@ export const SecretEditTableRow = ({
</PopoverContent>
</Popover>
<Sheet open={isReminderOpen} onOpenChange={setIsReminderOpen}>
- <SheetContent className="flex h-full max-h-full flex-col gap-y-0 sm:max-w-lg">
+ <SheetContent className="flex h-full max-h-full flex-col gap-y-0">
<SheetHeader className="border-b">
<SheetTitle>{reminder ? "Edit Reminder" : "Add Reminder"}</SheetTitle>
<SheetDescription>
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretReminderForm.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretReminderForm.tsx
index 1088d40ac6..669094d4f4 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretReminderForm.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretReminderForm.tsx
@@ -39,12 +39,10 @@ import {
AlertPrincipalType,
AlertResourceType,
channelFormSchema,
- fetchAlerts,
TChannelForm,
toChannelForm,
toChannelInput,
- useListAlerts,
- useUpdateAlert
+ useListAlerts
} from "@app/hooks/api/alerts";
import { dashboardKeys } from "@app/hooks/api/dashboard/queries";
import { useCreateReminder, useDeleteReminder } from "@app/hooks/api/reminders";
@@ -137,20 +135,23 @@ export const SecretReminderForm = ({
const { mutateAsync: createReminder, isPending: isCreating } = useCreateReminder(secretId);
const { mutateAsync: deleteReminder, isPending: isDeleting } = useDeleteReminder(secretId);
- const { mutateAsync: updateAlert, isPending: isUpdatingAlert } = useUpdateAlert();
-
- const alertFilters = {
- resourceType: AlertResourceType.SecretReminder,
- projectId,
- resourceId: secretId
- };
- const { data: alerts, isPending: isAlertLoading } = useListAlerts(alertFilters, {
- enabled: Boolean(reminder)
- });
- const alert = alerts?.[0];
const isEditMode = Boolean(reminder);
+ const {
+ data: alerts,
+ isPending: isAlertLoading,
+ isError: isAlertError,
+ isSuccess: isAlertLoaded
+ } = useListAlerts(
+ { resourceType: AlertResourceType.SecretReminder, projectId, resourceId: secretId },
+ { enabled: isEditMode }
+ );
+ const alert = alerts?.[0];
+ // Until an existing reminder's channels load, the form holds the default channel,
+ // so saving would replace the real ones.
+ const areChannelsReady = !isEditMode || isAlertLoaded;
+
const canEditSecret = permission.can(
ProjectPermissionSecretActions.Edit,
subject(ProjectPermissionSub.Secrets, {
@@ -204,7 +205,7 @@ export const SecretReminderForm = ({
if (alert) setValue("channels", alert.channels.map(toChannelForm), { shouldDirty: false });
}, [alert, setValue]);
- const isPending = isCreating || isDeleting || isUpdatingAlert;
+ const isPending = isCreating || isDeleting;
const invalidateQueries = useCallback(() => {
queryClient.invalidateQueries({
@@ -236,40 +237,14 @@ export const SecretReminderForm = ({
);
const onSubmit = async (data: TFormSchema) => {
- // The reminder API saves the schedule and keeps the alert's email recipients in step with the users
- // it is given. The alert update that follows then sets every channel exactly as the form has them.
- const emailUserIds = data.channels
- .filter((channel) => channel.channelType === AlertChannelType.Email)
- .flatMap((channel) => channel.recipients)
- .filter((recipient) => recipient.principalType === AlertPrincipalType.User)
- .map((recipient) => recipient.principalId);
-
await createReminder({
repeatDays: data.repeatDays,
message: data.message,
- recipients: [...new Set(emailUserIds)],
secretId,
nextReminderDate: data.nextReminderDate,
- fromDate: data.fromDate
- });
-
- const [savedAlert] = await queryClient.fetchQuery({
- queryKey: alertKeys.list(alertFilters),
- queryFn: () => fetchAlerts(alertFilters),
- staleTime: 0
+ fromDate: data.fromDate,
+ channels: data.channels.map(toChannelInput)
});
- if (savedAlert) {
- // Saving the schedule can replace email channels, so an id the form still holds may be gone.
- const savedChannelIds = new Set(savedAlert.channels.map((channel) => channel.id));
- await updateAlert({
- alertId: savedAlert.id,
- channels: data.channels.map((channel) =>
- toChannelInput(
- channel.id && !savedChannelIds.has(channel.id) ? { ...channel, id: undefined } : channel
- )
- )
- });
- }
invalidateQueries();
@@ -460,9 +435,15 @@ export const SecretReminderForm = ({
</FieldContent>
</Field>
- {reminder && isAlertLoading ? (
+ {isEditMode && isAlertLoading && (
<p className="text-xs text-muted">Loading channels...</p>
- ) : (
+ )}
+ {isEditMode && isAlertError && (
+ <p className="text-xs text-danger">
+ Couldn&apos;t load this reminder&apos;s channels. Close and reopen to try again.
+ </p>
+ )}
+ {areChannelsReady && (
<ChannelsField
projectId={projectId}
resourceType={AlertResourceType.SecretReminder}
@@ -500,8 +481,8 @@ export const SecretReminderForm = ({
variant="project"
size="xs"
type="submit"
- isDisabled={!isDirty || isPending}
- isPending={isCreating || isUpdatingAlert}
+ isDisabled={!isDirty || isPending || !areChannelsReady}
+ isPending={isCreating}
>
{isEditMode ? "Update" : "Create"} Reminder
</Button>