Skip to content

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

Merge remote-tracking branch 'origin/main' into feat/secret-reminder-alerts-ui

Calvin93605c4e4d60
diff --cc backend/src/db/migrations/20260929130000_migrate-secret-reminders-to-alerts.ts
index 820033362c,0000000000..fbe735373e
mode 100644,000000..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
@@@ -1,264 -1,0 +1,265 @@@
+/* 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,
+ 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;
+ 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. 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 = [
+ ...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 }
++ { orgId: reminder.orgId, projectId: reminder.projectId, userIds, groupIds: [] },
++ knex
+ )
+ : { userIds: new Set<string>() };
+ const kept = userIds.filter((userId) => inScope.userIds.has(userId));
+ 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.filter(({ id }) => recipientsByReminder.has(id))) {
+ 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) 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)
+ .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 += recipientsByReminder.size;
+ }
+
+ 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;
+
+ // 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", backfilledAlerts().select("id"))
+ .pluck("channelId")) as string[];
+
+ 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))
+ .delete();
+ }
+}
+
+const config = { transaction: false };
+export { config };
diff --cc backend/src/server/routes/index.ts
index fa8adc44f5,39a2658b4b..9085fc74d6
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@@ -249,10 -251,10 +251,12 @@@ import { alertProviderRegistryFactory
import { alertQueueServiceFactory } from "@app/services/alert/alert-queue";
import { alertRecipientResolverFactory } from "@app/services/alert/alert-recipient-resolver";
import { alertServiceFactory } from "@app/services/alert/alert-service";
+ import { certManagerApplicationAlertDALFactory } from "@app/services/alert/providers/cert-manager-application-alert-dal";
+ import { certManagerApplicationAlertProviderFactory } from "@app/services/alert/providers/cert-manager-application-alert-provider";
import { identityCredentialAlertDALFactory } from "@app/services/alert/providers/identity-credential-alert-dal";
import { identityCredentialAlertProviderFactory } from "@app/services/alert/providers/identity-credential-alert-provider";
+import { secretReminderAlertDALFactory } from "@app/services/alert/providers/secret-reminder-alert-dal";
+import { secretReminderAlertProviderFactory } from "@app/services/alert/providers/secret-reminder-alert-provider";
import { announcementServiceFactory } from "@app/services/announcement/announcement-service";
import { appConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { appConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
@@@ -1087,20 -1097,19 +1097,28 @@@ export const registerRoutes = async
permissionService
})
);
+ alertProviderRegistry.register(
+ secretReminderAlertProviderFactory({
+ secretReminderAlertDAL: secretReminderAlertDALFactory(db),
+ folderDAL,
+ permissionService
+ })
+ );
+ alertProviderRegistry.register(
+ certManagerApplicationAlertProviderFactory({
+ certManagerApplicationAlertDAL,
+ permissionService,
+ licenseService
+ })
+ );
const alertRecipientResolver = alertRecipientResolverFactory({
userDAL,
userGroupMembershipDAL,
orgDAL,
projectDAL,
+ projectMembershipDAL,
- groupProjectDAL
++ groupProjectDAL,
+ emailDomainDAL
});
const alertEngine = alertEngineFactory({
alertChannelDAL,
@@@ -1148,10 -1158,10 +1167,11 @@@
alertDAL,
alertChannelDAL,
alertChannelMembershipDAL,
+ alertChannelRecipientDAL,
alertChannelService,
kmsService,
- alertProviderRegistry
+ alertProviderRegistry,
+ alertHistoryDAL
});
const alertChannelTestService = alertChannelTestServiceFactory({
alertChannelDAL,
diff --cc backend/src/server/routes/v1/alert-router.ts
index 24b96d551c,b71e006191..714d17f70c
--- a/backend/src/server/routes/v1/alert-router.ts
+++ b/backend/src/server/routes/v1/alert-router.ts
@@@ -1,13 -1,41 +1,20 @@@
+ import { FastifyRequest } from "fastify";
import { z } from "zod";
- 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 { AlertChannelType } from "@app/services/alert/alert-channel-types";
- import { MAX_CHANNELS_PER_ALERT, MAX_RECIPIENTS_PER_CHANNEL } from "@app/services/alert/alert-types";
+ import {
+ AlertAuditAction,
- AlertPrincipalType,
+ AlertRunStatus,
+ AlertTelemetryAction,
+ 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().trim().min(1).max(255)
-});
-
-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 --cc backend/src/services/alert/alert-channel-service.test.ts
index 6631f66909,495f769ee4..0e94070302
--- a/backend/src/services/alert/alert-channel-service.test.ts
+++ b/backend/src/services/alert/alert-channel-service.test.ts
@@@ -81,19 -81,16 +83,20 @@@ const buildService = (opts?: { seed?: T
}: {
userIds: string[];
groupIds: string[];
- }) => ({
- effectiveUserIds: userIds,
- effectiveGroupIds: groupIds
- })
+ tx?: unknown;
+ }) => {
+ scopeCheckTxs.push(scopeTx);
+ return {
+ effectiveUserIds: opts?.projectUserIds ? userIds.filter((id) => opts.projectUserIds!.includes(id)) : userIds,
+ effectiveGroupIds: groupIds
+ };
+ }
},
- groupDAL: { find: async (filter: { $in?: { id?: string[] } }) => (filter.$in?.id ?? []).map((id) => ({ id })) }
+ groupDAL: { find: async (filter: { $in?: { id?: string[] } }) => (filter.$in?.id ?? []).map((id) => ({ id })) },
+ emailDomainDAL: { find: async () => [{ domain: "verified-example.com" }] }
} as unknown as TAlertChannelServiceFactoryDep);
- return { service, store, recipients };
+ return { service, store, recipients, scopeCheckTxs };
};
const seedRow = (
@@@ -265,118 -357,12 +363,128 @@@ describe("alert channel service", () =
});
await expect(
- service.updateChannelInTx({ channelId: "ch-1", config: { webhookUrl: "" } }, channel as never, cipher, tx)
+ service.updateChannelInTx(
+ { recipientScope: RECIPIENT_SCOPE, channelId: "ch-1", config: { webhookUrl: "" } },
+ channel as never,
+ cipher,
+ tx
+ )
).rejects.toThrow(/Invalid slack channel config/);
});
+
+ test("accepts all project members on a channel in the same project", async () => {
+ const { service, recipients } = buildService();
+ const channel = await service.createChannelInTx(
+ {
+ name: "Email",
+ channelType: AlertChannelType.EMAIL,
+ config: {},
+ recipients: [{ principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "proj-1" }],
+ orgId: "org-1",
+ projectId: "proj-1",
++ recipientScope: { projectId: "proj-1", allowEmailAddresses: false },
+ ...CREATOR
+ },
+ encryptor as never,
+ tx
+ );
+ expect(recipients.get(channel.id)).toEqual([
+ { channelId: channel.id, principalType: "project-members", principalId: "proj-1" }
+ ]);
+ });
+
+ test("rejects all project members on an org-scoped channel", async () => {
+ const { service } = buildService();
+ await expect(
+ service.createChannelInTx(
+ {
+ name: "Email",
+ channelType: AlertChannelType.EMAIL,
+ config: {},
+ recipients: [{ principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "proj-1" }],
+ orgId: "org-1",
++ recipientScope: { projectId: null, allowEmailAddresses: false },
+ ...CREATOR
+ },
+ encryptor as never,
+ tx
+ )
+ ).rejects.toThrow("All project members can only be notified by a project alert");
+ });
+
+ test("rejects all project members that names another project", async () => {
+ const { service } = buildService();
+ await expect(
+ service.createChannelInTx(
+ {
+ name: "Email",
+ channelType: AlertChannelType.EMAIL,
+ config: {},
+ recipients: [{ principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "other-project" }],
+ orgId: "org-1",
+ projectId: "proj-1",
++ recipientScope: { projectId: "proj-1", allowEmailAddresses: false },
+ ...CREATOR
+ },
+ encryptor as never,
+ tx
+ )
+ ).rejects.toThrow("All project members must refer to the alert's own project");
+ });
+
+ test("checks recipient scope inside the caller's transaction", async () => {
+ const { service, scopeCheckTxs } = buildService();
+ await service.createChannelInTx(
+ {
+ name: "Email",
+ channelType: AlertChannelType.EMAIL,
+ config: {},
+ recipients: [{ principalType: AlertPrincipalType.USER, principalId: "user-1" }],
+ orgId: "org-1",
+ projectId: "proj-1",
++ recipientScope: { projectId: "proj-1", allowEmailAddresses: false },
+ ...CREATOR
+ },
+ encryptor as never,
+ tx
+ );
+ expect(scopeCheckTxs).toEqual([tx]);
+ });
+
+ test("accepts a platform creator with no actor id", async () => {
+ const { service, store } = buildService();
+ const channel = await service.createChannelInTx(
+ {
+ name: "Email",
+ channelType: AlertChannelType.EMAIL,
+ config: {},
+ recipients: [{ principalType: AlertPrincipalType.USER, principalId: "user-1" }],
+ orgId: "org-1",
++ recipientScope: { projectId: null, allowEmailAddresses: false },
+ createdByActorId: null,
+ createdByActorType: "platform"
+ },
+ encryptor as never,
+ tx
+ );
+ expect(store.get(channel.id)).toMatchObject({ createdByActorId: null, createdByActorType: "platform" });
+ });
+
+ test("filterRecipientsInScope drops users who left the project and keeps the rest", async () => {
+ const { service } = buildService({ projectUserIds: ["user-1"] });
+ const kept = await service.filterRecipientsInScope(
+ { orgId: "org-1", projectId: "proj-1" },
+ [
+ { principalType: AlertPrincipalType.USER, principalId: "user-1" },
+ { principalType: AlertPrincipalType.USER, principalId: "user-gone" },
+ { principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "proj-1" },
+ { principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "other-project" }
+ ],
+ tx
+ );
+ expect(kept).toEqual([
+ { principalType: "user", principalId: "user-1" },
+ { principalType: "project-members", principalId: "proj-1" }
+ ]);
+ });
});
diff --cc backend/src/services/alert/alert-channel-service.ts
index 6bcd09657d,3442d9d36d..94e31795d9
--- a/backend/src/services/alert/alert-channel-service.ts
+++ b/backend/src/services/alert/alert-channel-service.ts
@@@ -46,7 -49,8 +49,8 @@@ export type TCreateChannelInTxInput =
recipients?: TChannelRecipientInput[];
orgId: string;
projectId?: string | null;
+ recipientScope: TAlertRecipientScope;
- createdByActorId: string;
+ createdByActorId: string | null;
createdByActorType: string;
};
@@@ -66,41 -71,67 +71,91 @@@ export const alertChannelServiceFactor
alertChannelRecipientDAL,
orgDAL,
projectDAL,
- groupDAL
+ groupDAL,
+ emailDomainDAL
}: TAlertChannelServiceFactoryDep) => {
+ const $recipientIdsByType = (recipients: TChannelRecipientInput[]) => ({
+ userIds: [
+ ...new Set(recipients.filter((r) => r.principalType === AlertPrincipalType.USER).map((r) => r.principalId))
+ ],
+ groupIds: [
+ ...new Set(recipients.filter((r) => r.principalType === AlertPrincipalType.GROUP).map((r) => r.principalId))
+ ]
+ });
+
+ const $assertProjectMembersRecipients = (
+ projectId: string | null | undefined,
+ recipients: TChannelRecipientInput[]
+ ) => {
+ const projectMembers = recipients.filter((r) => r.principalType === AlertPrincipalType.PROJECT_MEMBERS);
+ if (projectMembers.length === 0) return;
+ if (!projectId) {
+ throw new BadRequestError({ message: "All project members can only be notified by a project alert" });
+ }
+ if (projectMembers.some((r) => r.principalId !== projectId)) {
+ throw new BadRequestError({ message: "All project members must refer to the alert's own project" });
+ }
+ };
+
+ const $assertNoDuplicateRecipients = (recipients: TChannelRecipientInput[]) => {
+ const seen = new Set<string>();
+ const duplicates = new Set<string>();
+ recipients.forEach((recipient) => {
+ const principalId =
+ recipient.principalType === AlertPrincipalType.EMAIL
+ ? recipient.principalId.toLowerCase()
+ : recipient.principalId;
+ const key = `${recipient.principalType}:${principalId}`;
+ if (seen.has(key)) duplicates.add(recipient.principalId);
+ seen.add(key);
+ });
+ if (duplicates.size) {
+ throw new BadRequestError({ message: `Duplicate recipients: ${[...duplicates].join(", ")}` });
+ }
+ };
+
+ const $validateEmailRecipients = async (orgId: string, emails: string[], tx?: Knex) => {
+ if (!emails.length) return;
+
+ const malformed = emails.filter((email) => !z.string().email().safeParse(email).success);
+ if (malformed.length) {
+ throw new BadRequestError({ message: `Invalid email recipients: ${malformed.join(", ")}` });
+ }
+
+ const verifiedDomains = await findVerifiedEmailDomains(emailDomainDAL, orgId, tx);
+ const unverified = emails.filter((email) => !isOnVerifiedDomain(email, verifiedDomains));
+ if (unverified.length) {
+ throw new BadRequestError({
+ message: `Email recipients must use one of your organization's verified domains (Organization Settings > SSO > Email Domains). Not on a verified domain: ${unverified.join(", ")}`
+ });
+ }
+ };
+
+ const assertRecipientTypesAllowed = (scope: TAlertRecipientScope, recipients: TChannelRecipientInput[]) => {
+ if (!scope.allowEmailAddresses && recipients.some((r) => r.principalType === AlertPrincipalType.EMAIL)) {
+ throw new BadRequestError({ message: "This alert type doesn't accept email address recipients" });
+ }
+ };
+
// Confirms every recipient principal (user/group) actually belongs to the channel's scope so an
// alert can't be made to notify a foreign principal.
- const $validateRecipients = async (
+ const validateRecipients = async (
orgId: string,
- projectId: string | null | undefined,
+ scope: TAlertRecipientScope,
recipients: TChannelRecipientInput[],
tx?: Knex
) => {
+ const { projectId } = scope;
+ assertRecipientTypesAllowed(scope, recipients);
+ $assertNoDuplicateRecipients(recipients);
+ $assertProjectMembersRecipients(projectId, recipients);
- const { userIds, groupIds } = $recipientIdsByType(recipients);
+
+ const idsOfType = (principalType: AlertPrincipalType) =>
+ recipients.filter((r) => r.principalType === principalType).map((r) => r.principalId);
+ const userIds = idsOfType(AlertPrincipalType.USER);
+ const groupIds = idsOfType(AlertPrincipalType.GROUP);
+
+ await $validateEmailRecipients(orgId, idsOfType(AlertPrincipalType.EMAIL), tx);
if (userIds.length === 0 && groupIds.length === 0) return;
const inScope = await resolvePrincipalsInScope(
@@@ -236,33 -269,6 +293,34 @@@
}
};
+ // For callers that carry recipient lists from outside the alert module (eg reminder recipients that
+ // were never pruned when someone left the project), where an out-of-scope id should be dropped
+ // rather than fail the whole write.
+ const filterRecipientsInScope = async (
+ scope: { orgId: string; projectId?: string | null },
+ recipients: TChannelRecipientInput[],
+ tx?: Knex
+ ): Promise<TChannelRecipientInput[]> => {
+ const { userIds, groupIds } = $recipientIdsByType(recipients);
+ const inScope =
+ userIds.length || groupIds.length
+ ? await resolvePrincipalsInScope(
+ { orgDAL, projectDAL, groupDAL },
- { orgId: scope.orgId, projectId: scope.projectId, userIds, groupIds, tx }
++ { orgId: scope.orgId, projectId: scope.projectId, userIds, groupIds },
++ tx
+ )
+ : { userIds: new Set<string>(), groupIds: new Set<string>() };
+
+ return recipients.filter((r) => {
+ if (r.principalType === AlertPrincipalType.USER) return inScope.userIds.has(r.principalId);
+ if (r.principalType === AlertPrincipalType.GROUP) return inScope.groupIds.has(r.principalId);
+ if (r.principalType === AlertPrincipalType.PROJECT_MEMBERS) {
+ return Boolean(scope.projectId) && r.principalId === scope.projectId;
+ }
+ return false;
+ });
+ };
+
const deleteChannelInTx = async (channelId: string, tx: Knex): Promise<void> => {
await alertChannelDAL.deleteById(channelId, tx);
};
@@@ -303,6 -311,7 +363,8 @@@
updateChannelInTx,
deleteChannelInTx,
getDetailsForChannels,
+ validateRecipients,
- assertRecipientTypesAllowed
++ assertRecipientTypesAllowed,
+ filterRecipientsInScope
};
};
diff --cc backend/src/services/alert/alert-recipient-resolver.test.ts
index 662fbdc294,5598e13883..798725d0c8
--- a/backend/src/services/alert/alert-recipient-resolver.test.ts
+++ b/backend/src/services/alert/alert-recipient-resolver.test.ts
@@@ -13,8 -13,7 +13,9 @@@ const buildResolver = (opts:
invitedUserIds?: string[]; // users invited to the org who never accepted
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
+ verifiedDomains?: string[];
}) => {
const usersById = new Map(opts.users.map((u) => [u.id, u]));
return alertRecipientResolverFactory({
@@@ -58,11 -57,8 +59,14 @@@
effectiveGroupIds: groupIds.filter((id) => (opts.effectiveProjectGroupIds ?? []).includes(id))
})
} as never,
+ projectMembershipDAL: {
+ findAllProjectMembers: async () => (opts.projectMemberUserIds ?? []).map((id) => ({ user: { id } }))
+ } as never,
+ groupProjectDAL: {
+ findAllProjectGroupMembers: async () => (opts.projectGroupMemberUserIds ?? []).map((id) => ({ user: { id } }))
++ } as never,
+ emailDomainDAL: {
+ find: async () => (opts.verifiedDomains ?? []).map((domain) => ({ domain }))
} as never
});
};
@@@ -233,103 -229,24 +237,122 @@@ describe("alert recipient resolver —
const emails = (result.get("c1") ?? []).map((r) => r.email);
expect(emails).toEqual(["[email protected]"]);
+ });
+
+ test("drops a plain email whose domain is no longer verified", async () => {
+ const resolver = buildResolver({ users: [], verifiedDomains: ["verified.example.com"] });
+
+ const result = await resolver.resolveMany(
+ new Map([
+ [
+ "c1",
+ [
+ { principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" },
+ { principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" }
+ ]
+ ]
+ ]),
+ { orgId: "org-1", projectId: null }
+ );
+
+ expect((result.get("c1") ?? []).map((r) => r.email)).toEqual(["[email protected]"]);
});
});
+
+describe("alert recipient resolver — all project members", () => {
+ test("expands to the project's current members", async () => {
+ const resolver = buildResolver({
+ users: [user("u1"), user("u2")],
+ projectMemberUserIds: ["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("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")],
+ orgUserIds: ["u1"],
+ deactivatedUserIds: ["u2"],
+ projectMemberUserIds: ["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)).toEqual(["[email protected]"]);
+ });
+
+ test("ignores a project members recipient that names another project", async () => {
+ const resolver = buildResolver({
+ users: [user("u1")],
+ projectMemberUserIds: ["u1"],
+ effectiveProjectUserIds: ["u1"]
+ });
+
+ const result = await resolver.resolveMany(
+ new Map([["c1", [{ principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "other-project" }]]]),
+ { orgId: "org-1", projectId: "proj-1" }
+ );
+
+ expect(result.get("c1")).toEqual([]);
+ });
+
+ test("emails a user once when listed directly and through project members", async () => {
+ const resolver = buildResolver({
+ users: [user("u1")],
+ projectMemberUserIds: ["u1"],
+ effectiveProjectUserIds: ["u1"]
+ });
+
+ const result = await resolver.resolveMany(
+ new Map([
+ [
+ "c1",
+ [
+ { principalType: AlertPrincipalType.USER, principalId: "u1" },
+ { principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: "proj-1" }
+ ]
+ ]
+ ]),
+ { orgId: "org-1", projectId: "proj-1" }
+ );
+
+ expect(result.get("c1")).toHaveLength(1);
+ });
+});
diff --cc backend/src/services/alert/alert-recipient-resolver.ts
index 3ef64a6aa3,9e2a871f18..c9da4cca44
--- a/backend/src/services/alert/alert-recipient-resolver.ts
+++ b/backend/src/services/alert/alert-recipient-resolver.ts
@@@ -1,9 -1,8 +1,10 @@@
+ import { TEmailDomainDALFactory } from "@app/ee/services/email-domain/email-domain-dal";
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";
import { TUserDALFactory } from "@app/services/user/user-dal";
import { TAlertRecipient } from "./alert-channel-types";
@@@ -15,8 -14,7 +16,9 @@@ type TAlertRecipientResolverDep =
userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
orgDAL: Pick<TOrgDALFactory, "findMembership">;
projectDAL: Pick<TProjectDALFactory, "findEffectiveProjectSubjectsMembership">;
+ projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findAllProjectMembers">;
+ groupProjectDAL: Pick<TGroupProjectDALFactory, "findAllProjectGroupMembers">;
+ emailDomainDAL: Pick<TEmailDomainDALFactory, "find">;
};
type TResolvableRecipient = { principalType: string; principalId: string };
@@@ -30,8 -28,7 +32,9 @@@ export const alertRecipientResolverFact
userGroupMembershipDAL,
orgDAL,
projectDAL,
+ projectMembershipDAL,
- groupProjectDAL
++ groupProjectDAL,
+ emailDomainDAL
}: TAlertRecipientResolverDep) => {
const resolveMany = async (
rowsByChannel: Map<string, TResolvableRecipient[]>,
@@@ -101,13 -82,11 +110,16 @@@
case AlertPrincipalType.GROUP:
if (inScopeGroupIds.has(recipient.principalId)) {
(groupMembers.get(recipient.principalId) ?? []).forEach((userId) => userIds.add(userId));
+ }
+ break;
+ case AlertPrincipalType.PROJECT_MEMBERS:
+ if (scope.projectId && recipient.principalId === scope.projectId) {
+ projectMemberIds.forEach((userId) => userIds.add(userId));
}
break;
+ case AlertPrincipalType.EMAIL:
+ emails.add(recipient.principalId.toLowerCase());
+ break;
default:
logger.warn(`Unknown alert recipient principal type '${recipient.principalType}'`);
}
diff --cc backend/src/services/alert/alert-service.test.ts
index f57683f124,6d923e4c2c..18d32b8e93
--- a/backend/src/services/alert/alert-service.test.ts
+++ b/backend/src/services/alert/alert-service.test.ts
@@@ -27,9 -30,15 +33,13 @@@ const buildService = (opts?:
assertPermission?: (input: TAlertPermissionInput) => Promise<void>;
resourceScopeThrows?: boolean;
duplicateExists?: boolean;
+ createError?: Error;
+ resolvedProjectId?: string;
+ atOrgScope?: boolean;
- // Runs right after a find() has taken its snapshot, to stand in for a concurrent transaction
- // committing between two statements of ours.
- afterFindAlerts?: (alerts: Map<string, Record<string, unknown>>) => void;
}) => {
const permissionCalls: TAlertPermissionInput[] = [];
+ const gatedChannelTypeCalls: string[][] = [];
+ const recipientProjectIds: (string | null)[] = [];
const provider: IResourceAlertProvider = {
resourceType: RESOURCE_TYPE,
events: [
@@@ -63,14 -77,9 +78,15 @@@
const alerts = new Map<string, Record<string, unknown>>();
const channels = new Map<string, TChannelRow>(); // channelId -> row
const memberships = new Map<string, string[]>(); // alertId -> channelIds
+ const findFilters: Array<Record<string, unknown>> = [];
let channelSeq = 0;
+ const matches = (row: Record<string, unknown>, filter: Record<string, unknown>) => {
+ const { $in: inFilter, ...equality } = filter as { $in?: Record<string, unknown[]> };
+ const inMatch = Object.entries(inFilter ?? {}).every(([key, values]) => values.includes(row[key]));
+ return inMatch && Object.entries(equality).every(([key, value]) => value === undefined || row[key] === value);
+ };
+
const detach = (channelId: string) => {
memberships.forEach((ids, alertId) =>
memberships.set(
@@@ -96,6 -105,12 +113,10 @@@
return row;
},
findActiveById: async (id: string) => alerts.get(id),
+ findActiveByScope: async (filter: Record<string, unknown>) => {
+ findFilters.push(filter);
- return [...alerts.values()].filter((row) =>
- Object.entries(filter).every(([key, value]) => value === undefined || row[key] === value)
- );
++ return [...alerts.values()].filter((row) => matches(row, filter));
+ },
findScopedDuplicate: async () => (opts?.duplicateExists ? { id: "dup" } : undefined),
updateById: async (id: string, data: Record<string, unknown>) => {
// Mirror knex, which throws "Empty .update() call detected!" on an empty patch.
@@@ -353,6 -444,119 +439,51 @@@ describe("alert service", () =>
);
});
- const listBase = {
- resourceType: RESOURCE_TYPE,
- resourceId: null,
- eventType: "test.resource.expiration",
- condition: null,
- enabled: true,
- orgId: "org-1",
- createdAt: new Date(),
- updatedAt: new Date()
- };
-
- test("org-scoped list returns only org-level alerts, never other projects'", async () => {
- const { service, alerts, findFilters } = buildService();
- alerts.set("org-alert", { id: "org-alert", name: "org", projectId: null, ...listBase });
- alerts.set("proj-alert", { id: "proj-alert", name: "proj", projectId: "proj-x", ...listBase });
-
- const result = await service.listAlerts({ resourceType: RESOURCE_TYPE, ...actor });
-
- expect(result.map((a) => a.id)).toEqual(["org-alert"]);
- expect(findFilters[0]).toMatchObject({ projectId: null });
- });
-
+ test("create and list resolve the project from the resource when projectId is omitted", async () => {
+ const { service, permissionCalls, findFilters } = buildService({ resolvedProjectId: "proj-resolved" });
+
+ const created = await service.createAlert(validCreate);
+ expect(created.projectId).toBe("proj-resolved");
+
+ await service.listAlerts({ resourceType: RESOURCE_TYPE, resourceId: "resource-1", ...actor });
+ expect(findFilters.at(-1)).toMatchObject({ projectId: "proj-resolved" });
+ expect(permissionCalls.every((call) => call.projectId === "proj-resolved")).toBe(true);
+ });
+
- test("project-scoped list filters to the requested project", async () => {
- const { service, alerts, findFilters } = buildService();
- alerts.set("org-alert", { id: "org-alert", name: "org", projectId: null, ...listBase });
- alerts.set("proj-alert", { id: "proj-alert", name: "proj", projectId: "proj-x", ...listBase });
-
- const result = await service.listAlerts({ resourceType: RESOURCE_TYPE, projectId: "proj-x", ...actor });
-
- expect(result.map((a) => a.id)).toEqual(["proj-alert"]);
- expect(findFilters[0]).toMatchObject({ projectId: "proj-x" });
- });
-
- test("update reconciles channels: keeps the referenced ones, deletes the rest, adds new", async () => {
- const { service, memberships } = buildService();
- const created = await service.createAlert(validCreate);
- expect(memberships.get("alert-1")).toHaveLength(2);
-
- const keep = created.channels.find((c) => c.channelType === AlertChannelType.WEBHOOK)!;
- const updated = await service.updateAlert({
- alertId: "alert-1",
- channels: [
- { id: keep.id, name: keep.name, channelType: AlertChannelType.WEBHOOK },
- { name: "new-slack", channelType: AlertChannelType.SLACK }
- ],
- ...actor
- });
-
- expect(updated.channels.map((c) => c.channelType).sort()).toEqual([
- AlertChannelType.SLACK,
- AlertChannelType.WEBHOOK
- ]);
- expect(memberships.get("alert-1")).toContain(keep.id);
- expect(memberships.get("alert-1")).toHaveLength(2);
- });
-
+ test("update gates every new channel, even when the alert already has one of that type", async () => {
+ const { service, gatedChannelTypeCalls } = buildService();
+ const created = await service.createAlert(validCreate);
+ const existingWebhook = created.channels.find((c) => c.channelType === AlertChannelType.WEBHOOK)!;
+
+ await service.updateAlert({
+ alertId: "alert-1",
+ channels: [
+ { id: existingWebhook.id, name: existingWebhook.name, channelType: AlertChannelType.WEBHOOK },
+ { name: "second-webhook", channelType: AlertChannelType.WEBHOOK, config: { url: "https://example.com/2" } }
+ ],
+ ...actor
+ });
+
+ expect(gatedChannelTypeCalls.at(-1)).toEqual([AlertChannelType.WEBHOOK]);
+ });
+
+ test("update does not gate channels the alert already has", async () => {
+ const { service, gatedChannelTypeCalls } = buildService();
+ const created = await service.createAlert(validCreate);
+
+ await service.updateAlert({
+ alertId: "alert-1",
+ channels: created.channels.map((c) => ({
+ id: c.id,
+ name: c.name,
+ channelType: c.channelType as AlertChannelType
+ })),
+ ...actor
+ });
+
+ expect(gatedChannelTypeCalls.at(-1)).toEqual([]);
+ });
+
- test("update rejects a channel id that does not belong to the alert", async () => {
- const { service } = buildService();
- await service.createAlert(validCreate);
- await expect(
- service.updateAlert({
- alertId: "alert-1",
- channels: [{ id: "ch-foreign", name: "x", channelType: AlertChannelType.WEBHOOK }],
- ...actor
- })
- ).rejects.toThrow(/does not belong to this alert/);
- });
-
test("update rejects an empty channel list", async () => {
const { service } = buildService();
await service.createAlert(validCreate);
diff --cc backend/src/services/alert/alert-service.ts
index ff8355ce69,6de353ba23..0aacc24746
--- a/backend/src/services/alert/alert-service.ts
+++ b/backend/src/services/alert/alert-service.ts
@@@ -2,20 -2,22 +2,24 @@@ import { Knex } from "knex"
import { z } from "zod";
import { TAlertChannels, TAlerts } from "@app/db/schemas";
+ import { Event as TAuditEvent, EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { DatabaseErrorCode } from "@app/lib/error-codes";
+import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
import { TGenericPermission } from "@app/lib/types";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { getAlertChannelCipher } from "./alert-channel-crypto-fns";
import { TAlertChannelDALFactory } from "./alert-channel-dal";
import { TAlertChannelMembershipDALFactory } from "./alert-channel-membership-dal";
+import { TAlertChannelRecipientDALFactory } from "./alert-channel-recipient-dal";
import { TAlertChannelServiceFactory } from "./alert-channel-service";
-import { TAlertChannelEmbedded, TAlertChannelInput } from "./alert-channel-service-types";
+import { TAlertChannelEmbedded, TAlertChannelInput, TChannelRecipientInput } from "./alert-channel-service-types";
import { TAlertDALFactory } from "./alert-dal";
- import { TAlertProviderRegistry } from "./alert-provider-registry";
+ import { TAlertHistoryDALFactory } from "./alert-history-dal";
+ import { getRecipientScope } from "./alert-principal-scope-fns";
+ import { getAlertResourceName, resolveAlertProjectId, TAlertProviderRegistry } from "./alert-provider-registry";
import {
+ TAlertLastRun,
TAlertResponse,
TCreateAlertDTO,
TDeleteAlertDTO,
@@@ -49,10 -86,10 +93,11 @@@ export const alertServiceFactory = (
alertDAL,
alertChannelDAL,
alertChannelMembershipDAL,
+ alertChannelRecipientDAL,
alertChannelService,
kmsService,
- alertProviderRegistry
+ alertProviderRegistry,
+ alertHistoryDAL
}: TAlertServiceFactoryDep) => {
const $getProvider = (resourceType: string): IResourceAlertProvider => {
const provider = alertProviderRegistry.get(resourceType);
@@@ -218,21 -232,63 +240,75 @@@
throw new BadRequestError({ message: "At least one channel is required" });
}
- const input: TNewAlertRows = {
- name: dto.name,
- description: dto.description,
- resourceType: dto.resourceType,
- resourceId: dto.resourceId,
- eventType: dto.eventType,
- condition: dto.condition,
- enabled: dto.enabled,
+ await provider.assertChannelTypesAllowed?.({
orgId: dto.actorOrgId,
- projectId: dto.projectId ?? null,
- channels: dto.channels,
- createdBy: { actorType: dto.actor, actorId: dto.actorId }
- };
- const cipher = await getAlertChannelCipher(kmsService, input);
- return alertDAL.transaction((tx) => $createAlertRows(input, event, cipher, tx));
+ channelTypes: dto.channels.map((channel) => channel.channelType)
+ });
+
+ const scope = { orgId: dto.actorOrgId, projectId: projectId ?? null };
+ const cipher = await getAlertChannelCipher(kmsService, scope);
+
+ const { created, channels } = await alertDAL.transaction(async (tx) => {
- const createdAlert = await alertDAL.create(
- {
- name: dto.name,
- description: dto.description,
- resourceType: dto.resourceType,
- resourceId: dto.resourceId,
- eventType: dto.eventType,
- triggerType: event.triggerType,
- condition: dto.condition != null ? JSON.stringify(dto.condition) : null,
- enabled: dto.enabled ?? true,
- orgId: dto.actorOrgId,
- projectId,
- createdByActorId: dto.actorId,
- createdByActorType: dto.actor
- },
- tx
- );
++ let createdAlert: TAlerts;
++ try {
++ createdAlert = await alertDAL.create(
++ {
++ name: dto.name,
++ description: dto.description,
++ resourceType: dto.resourceType,
++ resourceId: dto.resourceId,
++ eventType: dto.eventType,
++ triggerType: event.triggerType,
++ condition: dto.condition != null ? JSON.stringify(dto.condition) : null,
++ enabled: dto.enabled ?? true,
++ orgId: dto.actorOrgId,
++ projectId,
++ createdByActorId: dto.actorId,
++ createdByActorType: dto.actor
++ },
++ tx
++ );
++ } catch (err) {
++ // findScopedDuplicate reads the replica, so two concurrent creates can both pass it.
++ if (
++ err instanceof DatabaseError &&
++ (err.error as { code?: string })?.code === DatabaseErrorCode.UniqueViolation
++ ) {
++ throw new BadRequestError({ message: "An alert for this resource and event already exists" });
++ }
++ throw err;
++ }
+
+ for (const channelInput of dto.channels) {
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ const channel = await alertChannelService.createChannelInTx(
+ {
+ name: channelInput.name,
+ channelType: channelInput.channelType,
+ config: channelInput.config ?? {},
+ enabled: channelInput.enabled,
+ recipients: channelInput.recipients,
+ orgId: dto.actorOrgId,
+ projectId: projectId ?? null,
+ recipientScope: getRecipientScope(provider, projectId),
+ createdByActorId: dto.actorId,
+ createdByActorType: dto.actor
+ },
+ cipher.encryptor,
+ tx
+ );
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ await alertChannelMembershipDAL.insertMany([{ alertId: createdAlert.id, channelId: channel.id }], tx);
+ }
+
+ const attachedChannels = await alertChannelDAL.findByAlertId(createdAlert.id, {}, tx);
+ const details = await alertChannelService.getDetailsForChannels(attachedChannels, cipher, tx);
+ return { created: createdAlert, channels: details };
+ });
+
+ return $assembleResponse(provider, created, channels, {
+ resourceName: await $getResourceName(provider, created)
+ });
};
const getAlertById = async (dto: TGetAlertDTO): Promise<TAlertResponse> => {
@@@ -343,7 -425,8 +445,8 @@@
recipients: channelInput.recipients,
orgId: alert.orgId,
projectId: alert.projectId,
+ recipientScope,
- createdByActorId: alert.createdByActorId,
+ createdByActorId: alert.createdByActorId ?? null,
createdByActorType: alert.createdByActorType
},
cipher.encryptor,
@@@ -473,111 -574,33 +594,137 @@@
tx?: Knex
): Promise<number> => $reapAlerts({ resourceType, resourceId }, tx);
+ const findAlertChannelSummariesForResources = (input: { resourceType: string; resourceIds: string[] }, tx?: Knex) =>
+ alertDAL.findChannelSummariesForResources(input, tx);
+
+ const deleteAlertsForDeletedResources = async (
+ { resourceType, resourceIds }: { resourceType: string; resourceIds: string[] },
+ tx?: Knex
+ ): Promise<number> => {
+ if (resourceIds.length === 0) return 0;
+ const run = (trx: Knex) => $deleteAlertsByFilter({ resourceType, $in: { resourceId: resourceIds } }, trx);
+ return tx ? run(tx) : alertDAL.transaction(run);
+ };
+
+ // For a resource that is recreated under a new id (eg a secret moved between folders), so its alerts
+ // and their history follow it instead of being rebuilt.
+ const repointAlertsForResource = async (
+ {
+ resourceType,
+ fromResourceId,
+ toResourceId
+ }: { resourceType: string; fromResourceId: string; toResourceId: string },
+ tx: Knex
+ ): Promise<void> => {
+ await alertDAL.update({ resourceType, resourceId: fromResourceId }, { resourceId: toResourceId }, tx);
+ };
+
+ // For a resource recreated under a new id while the original stays (eg a secret moved out of a folder
+ // whose approval policy holds the source until the request merges), so both keep working alerts.
+ // Channel configs are copied still encrypted: both ids belong to the same project and share its cipher,
+ // so no KMS call is needed and this is safe inside the caller's transaction.
+ const copyAlertsForResource = async (
+ {
+ resourceType,
+ fromResourceId,
+ toResourceId
+ }: { resourceType: string; fromResourceId: string; toResourceId: string },
+ tx: Knex
+ ): Promise<void> => {
+ const alerts = await alertDAL.find({ resourceType, resourceId: fromResourceId }, { tx });
+ if (alerts.length === 0) return;
+
+ const channels = await alertChannelDAL.findByAlertIds(
+ alerts.map((alert) => alert.id),
+ tx
+ );
+ const recipients = await alertChannelRecipientDAL.findByChannelIds(
+ channels.map((channel) => channel.id),
+ tx
+ );
+
+ for (const alert of alerts) {
+ const { id: alertId, createdAt, updatedAt, condition, ...alertFields } = alert;
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ const copiedAlert = await alertDAL.create(
+ {
+ ...alertFields,
+ resourceId: toResourceId,
+ condition: condition != null ? JSON.stringify(condition) : null
+ },
+ tx
+ );
+ for (const channel of channels.filter((row) => row.alertId === alertId)) {
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ const copiedChannel = await alertChannelDAL.create(
+ {
+ name: channel.name,
+ channelType: channel.channelType,
+ encryptedConfig: channel.encryptedConfig,
+ enabled: channel.enabled,
+ orgId: channel.orgId,
+ projectId: channel.projectId,
+ createdByActorId: channel.createdByActorId,
+ createdByActorType: channel.createdByActorType
+ },
+ tx
+ );
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ await alertChannelMembershipDAL.insertMany([{ alertId: copiedAlert.id, channelId: copiedChannel.id }], tx);
+ const channelRecipients = recipients.filter((recipient) => recipient.channelId === channel.id);
+ if (channelRecipients.length > 0) {
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ await alertChannelRecipientDAL.insertMany(
+ channelRecipients.map(({ principalType, principalId }) => ({
+ channelId: copiedChannel.id,
+ principalType,
+ principalId
+ })),
+ tx
+ );
+ }
+ }
+ }
+ };
+
+ const findRecipientsForResources = (
+ input: { resourceType: string; resourceIds: string[]; channelType: string; principalType: string },
+ tx?: Knex
+ ) => alertDAL.findRecipientsForResources(input, tx);
+
+ const filterRecipientsInScope = (
+ scope: { orgId: string; projectId?: string | null },
+ recipients: TChannelRecipientInput[],
+ tx?: Knex
+ ) => alertChannelService.filterRecipientsInScope(scope, recipients, tx);
+
+ const getTelemetryEvent = (
+ action: AlertTelemetryAction,
+ alert: {
+ resourceType: string;
+ orgId: string;
+ projectId: string | null;
+ resourceId: string | null;
+ eventType: string;
+ }
+ ) =>
+ alertProviderRegistry.get(alert.resourceType)?.getTelemetryEvent?.({
+ action,
+ orgId: alert.orgId,
+ projectId: alert.projectId,
+ resourceId: alert.resourceId,
+ eventType: alert.eventType
+ });
+
+ const getAuditEvent = (input: TAlertAuditInput): TAuditEvent => {
+ const resourceType =
+ input.action === AlertAuditAction.TestChannel ? input.test.resourceType : input.alert.resourceType;
+ return alertProviderRegistry.get(resourceType)?.getAuditEvent?.(input) ?? buildGenericAlertAuditEvent(input);
+ };
+
return {
+ getTelemetryEvent,
+ getAuditEvent,
createAlert,
getAlertById,
listAlerts,
diff --cc backend/src/services/alert/alert-types.ts
index 4d49ee26e1,7702a81ff3..0e5e117555
--- a/backend/src/services/alert/alert-types.ts
+++ b/backend/src/services/alert/alert-types.ts
@@@ -7,8 -9,7 +9,9 @@@ import { TAlertPayload } from "./alert-
export enum AlertPrincipalType {
USER = "user",
GROUP = "group",
- EMAIL = "email"
++ EMAIL = "email",
+ // Everyone in the channel's project at send time. principalId is the project id.
+ PROJECT_MEMBERS = "project-members"
}
export enum AlertTriggerType {
diff --cc backend/src/services/alert/providers/secret-reminder-alert-provider.test.ts
index a5fb091059,0000000000..e4b97cdacc
mode 100644,000000..100644
--- a/backend/src/services/alert/providers/secret-reminder-alert-provider.test.ts
+++ b/backend/src/services/alert/providers/secret-reminder-alert-provider.test.ts
@@@ -1,259 -1,0 +1,259 @@@
+import { createMongoAbility } from "@casl/ability";
+import { vi } from "vitest";
+
+import {
+ emitSecretReminderDue,
+ SECRET_REMINDER_DUE_EVENT,
+ SECRET_REMINDER_RESOURCE_TYPE
+} from "@app/services/reminder/reminder-events";
+
+import { AlertPermissionAction, TAlertContext } from "../alert-types";
+import { TReminderSecret } from "./secret-reminder-alert-dal";
+import { secretReminderAlertProviderFactory } from "./secret-reminder-alert-provider";
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ SITE_URL: "https://app.infisical.com" })
+}));
+
+const SECRET: TReminderSecret = {
+ secretId: "secret-1",
+ secretKey: "DB_PASSWORD",
+ secretType: "shared",
+ folderId: "folder-1",
+ orgId: "org-1",
+ projectId: "proj-1",
+ envSlug: "prod",
+ envName: "Production",
+ tagSlugs: ["payments"]
+};
+
+const buildProvider = (
+ opts: { secrets?: TReminderSecret[]; rules?: { action: string; subject: string }[]; unresolvedPath?: boolean } = {}
+) => {
+ const permissionCalls: unknown[] = [];
+ const provider = secretReminderAlertProviderFactory({
+ secretReminderAlertDAL: {
+ findReminderSecrets: async (ids: string[]) =>
+ (opts.secrets ?? [SECRET]).filter((secret) => ids.includes(secret.secretId)),
+ primaryNode: () => ({}) as never
+ },
+ folderDAL: {
+ findSecretPathByFolderIds: async () => (opts.unresolvedPath ? [] : [{ id: "folder-1", path: "/payments" }])
+ } as never,
+ permissionService: {
+ getProjectPermission: async (input: unknown) => {
+ permissionCalls.push(input);
+ return {
+ permission: createMongoAbility(
+ (opts.rules ?? [
+ { action: "edit", subject: "secrets" },
+ { action: "describeSecret", subject: "secrets" }
+ ]) as never
+ )
+ };
+ }
+ } as never
+ });
+ return { provider, permissionCalls };
+};
+
+const alertContext: TAlertContext = {
+ id: "alert-1",
+ name: "Reminder for DB_PASSWORD",
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceType: SECRET_REMINDER_RESOURCE_TYPE,
+ resourceId: "secret-1",
+ eventType: SECRET_REMINDER_DUE_EVENT,
+ condition: null
+};
+
+const dueEvent = (payload: Record<string, unknown> = {}) => ({
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: "secret-1",
+ eventType: SECRET_REMINDER_DUE_EVENT,
+ condition: null,
+ targetIds: ["secret-1"],
+ payload: { note: "rotate it", repeatDays: 30, occurrenceDate: "2026-10-10", ...payload }
+});
+
+const actor = { actor: "user", actorId: "user-1", actorAuthMethod: null, actorOrgId: "org-1" } as never;
+
+describe("secret reminder alert provider", () => {
+ test("delivers what the reminder cron emits", async () => {
+ let emitted: Record<string, unknown> | undefined;
+ await emitSecretReminderDue(
+ {
+ emit: async (event) => {
+ emitted = event.payload;
+ }
+ },
+ {
+ orgId: "org-1",
+ projectId: "proj-1",
+ reminderId: "rem-1",
+ secretId: "secret-1",
+ note: "rotate it",
+ repeatDays: 30,
+ occurrenceDate: "2026-10-10"
+ },
+ {} as never
+ );
+
+ const { provider } = buildProvider();
- const targets = await provider.findTargetsByIds({
++ const targets = await provider.findEventTargets({
+ ...dueEvent(),
+ targetIds: emitted!.targetIds as string[],
+ payload: emitted!
+ });
+
+ expect(targets).toHaveLength(1);
+ expect(provider.targetId(targets[0])).toBe("secret-1:2026-10-10");
+ });
+
+ test("drops a secret that is gone or sits in a soft-deleted environment", async () => {
+ const { provider } = buildProvider({ secrets: [] });
- expect(await provider.findTargetsByIds(dueEvent())).toEqual([]);
++ expect(await provider.findEventTargets(dueEvent())).toEqual([]);
+ });
+
+ test("drops a secret whose folder path cannot be resolved", async () => {
+ const { provider } = buildProvider({ unresolvedPath: true });
- expect(await provider.findTargetsByIds(dueEvent())).toEqual([]);
++ expect(await provider.findEventTargets(dueEvent())).toEqual([]);
+ });
+
+ test("drops a secret that does not belong to the event's project", async () => {
+ const { provider } = buildProvider({ secrets: [{ ...SECRET, projectId: "proj-2" }] });
- expect(await provider.findTargetsByIds(dueEvent())).toEqual([]);
++ expect(await provider.findEventTargets(dueEvent())).toEqual([]);
+ });
+
+ test("rejects an unreadable payload instead of delivering a blank reminder", async () => {
+ const { provider } = buildProvider();
- await expect(provider.findTargetsByIds(dueEvent({ occurrenceDate: "10/10/2026" }))).rejects.toThrow(
++ await expect(provider.findEventTargets(dueEvent({ occurrenceDate: "10/10/2026" }))).rejects.toThrow(
+ "Unreadable 'secret.reminder.due' payload"
+ );
+ });
+
+ test("the payload names the secret's current key, environment, path, schedule and note", async () => {
+ const { provider } = buildProvider({ secrets: [{ ...SECRET, secretKey: "DB_PASSWORD_V2" }] });
- const targets = await provider.findTargetsByIds(dueEvent());
++ const targets = await provider.findEventTargets(dueEvent());
+ const payload = provider.buildPayload(alertContext, targets, "https://view");
+
+ expect(payload.summary).toBe("Reminder for secret 'DB_PASSWORD_V2' in Production");
+ expect(payload.items[0].fields).toEqual([
+ { label: "Environment", value: "Production" },
+ { label: "Path", value: "/payments" },
+ { label: "Schedule", value: "Every 30 days" },
+ { label: "Due", value: "October 10, 2026" },
+ { label: "Note", value: "rotate it" }
+ ]);
+ });
+
+ test("a one-time reminder without a note says so and omits the note", async () => {
+ const { provider } = buildProvider();
- const targets = await provider.findTargetsByIds(dueEvent({ repeatDays: null, note: null }));
++ const targets = await provider.findEventTargets(dueEvent({ repeatDays: null, note: null }));
+ const payload = provider.buildPayload(alertContext, targets, "https://view");
+
+ expect(payload.items[0].fields).toContainEqual({ label: "Schedule", value: "One time" });
+ expect(payload.items[0].fields?.some((field) => field.label === "Note")).toBe(false);
+ });
+
+ test("links to the secret on the overview page", async () => {
+ const { provider } = buildProvider();
+ const url = new URL(await provider.buildViewUrl(alertContext));
+
+ expect(url.pathname).toBe("/organizations/org-1/projects/secret-management/proj-1/overview");
+ expect(url.searchParams.get("secretPath")).toBe("/payments");
+ expect(url.searchParams.get("environments")).toBe('["prod"]');
+ expect(url.searchParams.get("search")).toBe("DB_PASSWORD");
+ });
+
+ test("refuses to authorize anything not bound to a single secret", async () => {
+ const { provider } = buildProvider();
+ await expect(
+ provider.assertPermission({
+ action: AlertPermissionAction.Read,
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: null,
+ actor
+ })
+ ).rejects.toThrow("Secret reminders can only be managed for a single secret");
+ });
+
+ test("reading a reminder needs describe access to its secret", async () => {
+ const { provider } = buildProvider({ rules: [] });
+ await expect(
+ provider.assertPermission({
+ action: AlertPermissionAction.Read,
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: "secret-1",
+ actor
+ })
+ ).rejects.toThrow();
+ });
+
+ test("changing a reminder needs edit access to its secret", async () => {
+ const { provider } = buildProvider({ rules: [{ action: "describeSecret", subject: "secrets" }] });
+ await expect(
+ provider.assertPermission({
+ action: AlertPermissionAction.Edit,
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: "secret-1",
+ actor
+ })
+ ).rejects.toThrow();
+ });
+
+ test("allows edit when the caller can edit the secret", async () => {
+ const { provider, permissionCalls } = buildProvider();
+ await provider.assertPermission({
+ action: AlertPermissionAction.Edit,
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: "secret-1",
+ actor
+ });
+ expect(permissionCalls).toHaveLength(1);
+ });
+
+ test("rejects a secret from another project or org as not found", async () => {
+ const { provider } = buildProvider();
+ await expect(
+ provider.assertResourceInScope({ orgId: "org-1", projectId: "proj-2", resourceId: "secret-1" })
+ ).rejects.toThrow("Secret with ID 'secret-1' not found in this project");
+ await expect(
+ provider.assertResourceInScope({ orgId: "org-2", projectId: "proj-1", resourceId: "secret-1" })
+ ).rejects.toThrow("not found in this project");
+ });
+
+ test("refuses to authorize a secret whose folder path cannot be resolved, rather than checking the root", async () => {
+ const { provider, permissionCalls } = buildProvider({ unresolvedPath: true });
+ await expect(
+ provider.assertPermission({
+ action: AlertPermissionAction.Edit,
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: "secret-1",
+ actor
+ })
+ ).rejects.toThrow("Secret with ID 'secret-1' not found in this project");
+ expect(permissionCalls).toHaveLength(0);
+ });
+
+ test("rejects an org-scoped reminder alert", async () => {
+ const { provider } = buildProvider();
+ await expect(
+ provider.assertResourceInScope({ orgId: "org-1", projectId: null, resourceId: "secret-1" })
+ ).rejects.toThrow("Secret reminders must be managed within a project");
+ });
+
+ test("rejects a personal secret", async () => {
+ const { provider } = buildProvider({ secrets: [{ ...SECRET, secretType: "personal" }] });
+ await expect(
+ provider.assertResourceInScope({ orgId: "org-1", projectId: "proj-1", resourceId: "secret-1" })
+ ).rejects.toThrow("Reminders can only be set on shared secrets");
+ });
+});
diff --cc backend/src/services/alert/providers/secret-reminder-alert-provider.ts
index 1317bdc3f9,0000000000..95b357977a
mode 100644,000000..100644
--- a/backend/src/services/alert/providers/secret-reminder-alert-provider.ts
+++ b/backend/src/services/alert/providers/secret-reminder-alert-provider.ts
@@@ -1,245 -1,0 +1,245 @@@
+import { ForbiddenError, subject } from "@casl/ability";
+import { z } from "zod";
+
+import { ActionProjectType, SecretType } from "@app/db/schemas";
+import { throwIfMissingSecretReadValueOrDescribePermission } from "@app/ee/services/permission/permission-fns";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { ProjectPermissionSecretActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
+import { getConfig } from "@app/lib/config/env";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import {
+ SECRET_REMINDER_DUE_EVENT,
+ SECRET_REMINDER_RESOURCE_TYPE,
+ SecretReminderDuePayloadSchema
+} from "@app/services/reminder/reminder-events";
+import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
+
+import { TAlertPayload } from "../alert-channel-types";
+import {
+ AlertPermissionAction,
+ AlertTriggerType,
+ IEventAlertProvider,
+ TAlertContext,
+ TAlertPermissionInput,
- TFindTargetsByIdsInput
++ TFindEventTargetsInput
+} from "../alert-types";
+import { TReminderSecret, TSecretReminderAlertDALFactory } from "./secret-reminder-alert-dal";
+
+const SecretReminderConditionSchema = z.object({}).nullish();
+
+export type TSecretReminderTarget = TReminderSecret & {
+ secretPath: string;
+ note: string | null;
+ repeatDays: number | null;
+ occurrenceDate: string;
+};
+
+export type TSecretReminderAlertProviderDep = {
+ secretReminderAlertDAL: Pick<TSecretReminderAlertDALFactory, "findReminderSecrets" | "primaryNode">;
+ folderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+};
+
+const describeSchedule = (repeatDays: number | null): string => {
+ if (!repeatDays) return "One time";
+ return repeatDays === 1 ? "Every day" : `Every ${repeatDays} days`;
+};
+
+const formatDate = (isoDate: string): string =>
+ new Date(`${isoDate}T00:00:00.000Z`).toLocaleDateString("en-US", {
+ year: "numeric",
+ month: "long",
+ day: "numeric",
+ timeZone: "UTC"
+ });
+
+export const secretReminderAlertProviderFactory = ({
+ secretReminderAlertDAL,
+ folderDAL,
+ permissionService
+}: TSecretReminderAlertProviderDep): IEventAlertProvider<TSecretReminderTarget> => {
+ const $loadSecretsWithPath = async (secretIds: string[]) => {
+ const secrets = await secretReminderAlertDAL.findReminderSecrets(secretIds);
+ const paths = new Map<string, string>();
+ const folderIdsByProject = new Map<string, string[]>();
+ secrets.forEach((secret) => {
+ folderIdsByProject.set(secret.projectId, [...(folderIdsByProject.get(secret.projectId) ?? []), secret.folderId]);
+ });
+ for (const [projectId, folderIds] of folderIdsByProject) {
+ // The path decides what a permission check allows, so it comes from the primary like the secret:
+ // a replica that has not seen a new folder would otherwise leave it unresolved.
+ // eslint-disable-next-line no-await-in-loop -- reminders fire per secret, so this is one project
+ const folders = await folderDAL.findSecretPathByFolderIds(
+ projectId,
+ folderIds,
+ secretReminderAlertDAL.primaryNode()
+ );
+ folders.forEach((folder) => {
+ if (folder?.path) paths.set(folder.id, folder.path);
+ });
+ }
+ // A secret whose path cannot be resolved is left out rather than treated as sitting at the root,
+ // which would check permissions against the wrong path.
+ return secrets.flatMap((secret) => {
+ const secretPath = paths.get(secret.folderId);
+ return secretPath ? [{ ...secret, secretPath }] : [];
+ });
+ };
+
- const findTargetsByIds = async (input: TFindTargetsByIdsInput): Promise<TSecretReminderTarget[]> => {
++ const findEventTargets = async (input: TFindEventTargetsInput): Promise<TSecretReminderTarget[]> => {
+ if (input.eventType !== SECRET_REMINDER_DUE_EVENT) return [];
+
+ const parsed = SecretReminderDuePayloadSchema.safeParse(input.payload);
+ if (!parsed.success) {
+ throw new Error(
+ `Unreadable '${SECRET_REMINDER_DUE_EVENT}' payload: ${parsed.error.issues
+ .map((issue) => `${issue.path.join(".")} ${issue.message}`)
+ .join(", ")}`
+ );
+ }
+
+ const secrets = await $loadSecretsWithPath(input.targetIds);
+ return secrets
+ .filter(
+ (secret) =>
+ secret.orgId === input.orgId &&
+ secret.projectId === input.projectId &&
+ secret.secretType === SecretType.Shared
+ )
+ .map((secret) => ({
+ ...secret,
+ note: parsed.data.note ?? null,
+ repeatDays: parsed.data.repeatDays ?? null,
+ occurrenceDate: parsed.data.occurrenceDate
+ }));
+ };
+
+ const buildViewUrl = async (alert: TAlertContext): Promise<string> => {
+ const base = `${getConfig().SITE_URL}/organizations/${alert.orgId}/projects/secret-management/${alert.projectId}/overview`;
+ if (!alert.resourceId) return base;
+
+ const [secret] = await $loadSecretsWithPath([alert.resourceId]);
+ if (!secret) return base;
+
+ const query = new URLSearchParams({
+ secretPath: secret.secretPath,
+ environments: JSON.stringify([secret.envSlug]),
+ search: secret.secretKey
+ });
+ return `${base}?${query.toString()}`;
+ };
+
+ // Uses the secret's current key rather than the alert's stored name, which goes stale on a rename.
+ const buildPayload = (alert: TAlertContext, targets: TSecretReminderTarget[], viewUrl: string): TAlertPayload => {
+ const [first] = targets;
+ return {
+ alert: {
+ id: alert.id,
+ name: alert.name,
+ orgId: alert.orgId,
+ ...(alert.projectId ? { projectId: alert.projectId } : {}),
+ resourceType: alert.resourceType,
+ ...(first ? { condition: describeSchedule(first.repeatDays) } : {}),
+ viewUrl
+ },
+ eventKey: SECRET_REMINDER_DUE_EVENT,
+ eventLabel: "Reminder",
+ webhookType: "com.infisical.secret.reminder.due",
+ resourceKind: "Secret",
+ resourceOwnerKind: "Secret",
+ severity: "info",
+ summary: first ? `Reminder for secret '${first.secretKey}' in ${first.envName}` : "Secret reminder",
+ items: targets.map((target) => ({
+ id: `${target.secretId}:${target.occurrenceDate}`,
+ title: target.secretKey,
+ fields: [
+ { label: "Environment", value: target.envName },
+ { label: "Path", value: target.secretPath },
+ { label: "Schedule", value: describeSchedule(target.repeatDays) },
+ { label: "Due", value: formatDate(target.occurrenceDate) },
+ ...(target.note ? [{ label: "Note", value: target.note }] : [])
+ ]
+ }))
+ };
+ };
+
+ const $loadInScopeSecret = async (input: {
+ orgId: string;
+ projectId?: string | null;
+ resourceId?: string | null;
+ }) => {
+ if (!input.projectId) {
+ throw new BadRequestError({ message: "Secret reminders must be managed within a project" });
+ }
+ if (!input.resourceId) {
+ // A reminder alert's name carries its secret key, so a listing across a project would reveal keys
+ // the caller may not be allowed to see.
+ throw new BadRequestError({ message: "Secret reminders can only be managed for a single secret" });
+ }
+ const [secret] = await $loadSecretsWithPath([input.resourceId]);
+ if (!secret || secret.orgId !== input.orgId || secret.projectId !== input.projectId) {
+ throw new NotFoundError({ message: `Secret with ID '${input.resourceId}' not found in this project` });
+ }
+ if (secret.secretType !== SecretType.Shared) {
+ throw new BadRequestError({ message: "Reminders can only be set on shared secrets" });
+ }
+ return secret;
+ };
+
+ const assertResourceInScope = async (input: {
+ orgId: string;
+ projectId?: string | null;
+ resourceId?: string | null;
+ }): Promise<void> => {
+ await $loadInScopeSecret(input);
+ };
+
+ const assertPermission = async (input: TAlertPermissionInput): Promise<void> => {
+ const secret = await $loadInScopeSecret(input);
+ const { permission } = await permissionService.getProjectPermission({
+ actor: input.actor.actor,
+ actorId: input.actor.actorId,
+ projectId: secret.projectId,
+ actorAuthMethod: input.actor.actorAuthMethod,
+ actorOrgId: input.actor.actorOrgId,
+ actionProjectType: ActionProjectType.SecretManager
+ });
+ const subjectFields = {
+ environment: secret.envSlug,
+ secretPath: secret.secretPath,
+ secretName: secret.secretKey,
+ secretTags: secret.tagSlugs
+ };
+
+ if (input.action === AlertPermissionAction.Read) {
+ throwIfMissingSecretReadValueOrDescribePermission(
+ permission,
+ ProjectPermissionSecretActions.DescribeSecret,
+ subjectFields
+ );
+ return;
+ }
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionSecretActions.Edit,
+ subject(ProjectPermissionSub.Secrets, subjectFields)
+ );
+ };
+
+ return {
+ resourceType: SECRET_REMINDER_RESOURCE_TYPE,
+ events: [
+ {
+ key: SECRET_REMINDER_DUE_EVENT,
+ triggerType: AlertTriggerType.Event,
+ conditionSchema: SecretReminderConditionSchema
+ }
+ ],
- findTargetsByIds,
++ findEventTargets,
+ buildViewUrl,
+ buildPayload,
+ targetId: (target) => `${target.secretId}:${target.occurrenceDate}`,
+ assertPermission,
+ assertResourceInScope
+ };
+};
diff --cc backend/src/services/secret-folder/secret-folder-service.ts
index 27c5e4552f,c5faab2894..b3e05e6765
--- a/backend/src/services/secret-folder/secret-folder-service.ts
+++ b/backend/src/services/secret-folder/secret-folder-service.ts
@@@ -116,8 -117,9 +117,9 @@@ type TSecretFolderServiceFactoryDep =
honeyTokenDAL: Pick<THoneyTokenDALFactory, "find">;
secretImportDAL: Pick<TSecretImportDALFactory, "findImportByFolderIds">;
secretV2BridgeService: Pick<TSecretV2BridgeServiceFactory, "dispatchSecretMoveSideEffects">;
+ secretValidationRuleService: Pick<TSecretValidationRuleServiceFactory, "validateSecrets">;
reminderDAL: Pick<TReminderDALFactory, "findSecretReminders" | "delete">;
- reminderService: Pick<TReminderServiceFactory, "batchCreateReminders">;
+ reminderService: Pick<TReminderServiceFactory, "batchCreateReminders" | "moveReminderAlerts" | "copyReminderAlerts">;
keyStore: Pick<TKeyStoreFactory, "acquireLock">;
};
diff --cc backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts
index d8d6fb0e66,3840787aab..26352cc941
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts
@@@ -34,6 -34,12 +34,11 @@@ import { INFISICAL_SECRET_VALUE_HIDDEN_
import { TSecretQueueFactory } from "../secret/secret-queue";
import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
import { TSecretImportDALFactory } from "../secret-import/secret-import-dal";
-import { TSecretReminderRecipient } from "../secret-reminder-recipients/secret-reminder-recipients-types";
+ import {
+ describeSecretValidationFailures,
+ SecretValidationError
+ } from "../secret-validation-rule/secret-validation-rule-errors";
+ import { createSecretBlindIndexer, TSecretBlindIndexer, TSecretValueBlindIndexes } from "./secret-blind-index-fns";
import { expandSecretReferencesFactory, getAllSecretReferences } from "./secret-reference-fns";
import { TSecretV2BridgeDALFactory } from "./secret-v2-bridge-dal";
import {
diff --cc backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
index d441e393ba,9a23fd1114..2345f3d772
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
@@@ -312,7 -315,8 +315,8 @@@ export type TFnSecretMove =
>;
secretQueueService: Pick<TSecretQueueFactory, "syncSecrets">;
reminderDAL: Pick<TReminderDALFactory, "findSecretReminders" | "delete">;
- reminderService: Pick<TReminderServiceFactory, "batchCreateReminders">;
+ reminderService: Pick<TReminderServiceFactory, "batchCreateReminders" | "moveReminderAlerts" | "copyReminderAlerts">;
+ secretValidationRuleService: Pick<TSecretValidationRuleServiceFactory, "validateSecrets">;
};
export type TFnSecretMoveResult = {
diff --cc frontend/src/hooks/api/alerts/types.ts
index 7e84f126a5,779c289a47..17074da079
--- a/frontend/src/hooks/api/alerts/types.ts
+++ b/frontend/src/hooks/api/alerts/types.ts
@@@ -20,15 -19,32 +20,34 @@@ export enum AlertChannelType
export enum AlertPrincipalType {
User = "user",
Group = "group",
- Email = "email"
++ Email = "email",
+ ProjectMembers = "project-members"
}
+ export enum AlertRunStatus {
+ Success = "success",
+ Partial = "partial",
+ Failed = "failed"
+ }
+
+ export enum CertificateAlertResourceType {
+ Application = "cert-manager.application"
+ }
+
+ export enum CertificateAlertEventType {
+ Expiry = "cert-manager.application.certificate.expiry",
+ Issuance = "cert-manager.application.certificate.issuance",
+ Renewal = "cert-manager.application.certificate.renewal",
+ Revocation = "cert-manager.application.certificate.revocation"
+ }
+
export const MIN_ALERT_BEFORE_DAYS = 1;
export const MAX_ALERT_BEFORE_DAYS = 90;
+ export const MAX_CERTIFICATE_ALERT_BEFORE_DAYS = 365;
export const ALERT_RESOURCE_TYPE_LABELS: Record<AlertResourceType, string> = {
- [AlertResourceType.IdentityAuthentication]: "Machine Identity Authentication"
+ [AlertResourceType.IdentityAuthentication]: "Machine Identity Authentication",
+ [AlertResourceType.SecretReminder]: "Secret Reminder"
};
export const ALERT_EVENT_TYPE_LABELS: Record<AlertEventType, string> = {
diff --cc frontend/src/views/Alerts/ChannelCard.tsx
index 1dde359df8,7ef4deb6a8..9af850e102
--- a/frontend/src/views/Alerts/ChannelCard.tsx
+++ b/frontend/src/views/Alerts/ChannelCard.tsx
@@@ -22,7 -22,8 +22,8 @@@ import { useScopeVariant } from "@app/h
import {
ALERT_CHANNEL_TYPE_LABELS,
AlertChannelType,
+ TAlertChannelRecipient,
- TAlertForm,
+ TChannelsForm,
toChannelInput,
useTestAlertChannel
} from "@app/hooks/api/alerts";
diff --cc frontend/src/views/Alerts/ChannelsField.tsx
index 6f8abd0795,f87fd4633e..48cf4bb639
--- a/frontend/src/views/Alerts/ChannelsField.tsx
+++ b/frontend/src/views/Alerts/ChannelsField.tsx
@@@ -13,12 -5,12 +5,12 @@@ import
ALERT_CHANNEL_TYPE_LABELS,
AlertChannelType,
AlertPrincipalType,
- TAlertForm,
- TChannelForm
+ TChannelForm,
+ TChannelsForm
} from "@app/hooks/api/alerts";
+ import { AddChannelMenu } from "./AddChannelMenu";
import { ChannelCard } from "./ChannelCard";
- import { getChannelIcon } from "./channelIcons";
type Props = {
projectId?: string;
diff --cc frontend/src/views/Alerts/index.ts
index 9c96cc2c66,6c261bf074..6fc865eace
--- a/frontend/src/views/Alerts/index.ts
+++ b/frontend/src/views/Alerts/index.ts
@@@ -1,3 -1,6 +1,6 @@@
export { AddAlertModal } from "./AddAlertModal";
+ export { AddChannelMenu } from "./AddChannelMenu";
export { AlertAction } from "./AlertAction";
- export { ChannelsField } from "./ChannelsField";
+ export { ChannelCard, type TChannelRecipientsRenderProps } from "./ChannelCard";
+ export { canReceiveAlerts } from "./ChannelRecipientsField";
-export { buildNextChannel } from "./ChannelsField";
++export { buildNextChannel, ChannelsField } from "./ChannelsField";