Skip to content

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

add alarm engine

Thiago Araujo da Silva4b5a02fc947a
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 68491f7ba0..42c060863b 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -79,6 +79,7 @@ import { RequestMemoizer } from "@app/lib/request-context/request-memoizer";
import { TAuthMode } from "@app/server/plugins/auth/inject-identity";
import { TAccountRecoveryServiceFactory } from "@app/services/account-recovery/account-recovery-service";
import { TAdditionalPrivilegeServiceFactory } from "@app/services/additional-privilege/additional-privilege-service";
+import { TAlarmServiceFactory } from "@app/services/alarm/alarm-service";
import { TAnnouncementServiceFactory } from "@app/services/announcement/announcement-service";
import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
import { TAppConnectionCredentialRotationServiceFactory } from "@app/services/app-connection/credential-rotation";
@@ -439,6 +440,7 @@ declare module "fastify" {
projectEventsSSE: TProjectEventsSSEService;
identityAuthTemplate: TIdentityAuthTemplateServiceFactory;
notification: TNotificationServiceFactory;
+ alarm: TAlarmServiceFactory;
announcement: TAnnouncementServiceFactory;
offlineUsageReport: TOfflineUsageReportServiceFactory;
orgProductStats: TOrgProductStatsServiceFactory;
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 594cf5cd45..1b157ee726 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -41,6 +41,21 @@ import {
TAiMcpServerUserCredentials,
TAiMcpServerUserCredentialsInsert,
TAiMcpServerUserCredentialsUpdate,
+ TAlarmChannels,
+ TAlarmChannelsInsert,
+ TAlarmChannelsUpdate,
+ TAlarmHistory,
+ TAlarmHistoryInsert,
+ TAlarmHistoryTarget,
+ TAlarmHistoryTargetInsert,
+ TAlarmHistoryTargetUpdate,
+ TAlarmHistoryUpdate,
+ TAlarmRecipients,
+ TAlarmRecipientsInsert,
+ TAlarmRecipientsUpdate,
+ TAlarms,
+ TAlarmsInsert,
+ TAlarmsUpdate,
TAppConnectionCredentialRotations,
TAppConnectionCredentialRotationsInsert,
TAppConnectionCredentialRotationsUpdate,
@@ -1559,6 +1574,23 @@ declare module "knex/types/tables" {
TResourceMetadataInsert,
TResourceMetadataUpdate
>;
+ [TableName.Alarm]: KnexOriginal.CompositeTableType<TAlarms, TAlarmsInsert, TAlarmsUpdate>;
+ [TableName.AlarmRecipient]: KnexOriginal.CompositeTableType<
+ TAlarmRecipients,
+ TAlarmRecipientsInsert,
+ TAlarmRecipientsUpdate
+ >;
+ [TableName.AlarmChannel]: KnexOriginal.CompositeTableType<
+ TAlarmChannels,
+ TAlarmChannelsInsert,
+ TAlarmChannelsUpdate
+ >;
+ [TableName.AlarmHistory]: KnexOriginal.CompositeTableType<TAlarmHistory, TAlarmHistoryInsert, TAlarmHistoryUpdate>;
+ [TableName.AlarmHistoryTarget]: KnexOriginal.CompositeTableType<
+ TAlarmHistoryTarget,
+ TAlarmHistoryTargetInsert,
+ TAlarmHistoryTargetUpdate
+ >;
[TableName.AppConnection]: KnexOriginal.CompositeTableType<
TAppConnections,
TAppConnectionsInsert,
diff --git a/backend/src/db/migrations/20260714120000_add-alarms.ts b/backend/src/db/migrations/20260714120000_add-alarms.ts
new file mode 100644
index 0000000000..3538ac4d3e
--- /dev/null
+++ b/backend/src/db/migrations/20260714120000_add-alarms.ts
@@ -0,0 +1,106 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasTable(TableName.Alarm))) {
+ await knex.schema.createTable(TableName.Alarm, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ t.string("name").notNullable();
+ t.text("description").nullable();
+ t.string("resourceType").notNullable();
+ t.string("resourceId").nullable();
+ t.string("eventType").notNullable();
+ t.jsonb("condition").nullable();
+ t.jsonb("filters").nullable();
+ t.boolean("enabled").notNullable().defaultTo(true);
+ t.uuid("orgId").notNullable();
+ t.string("projectId").nullable();
+ t.uuid("createdByUserId").nullable();
+ t.timestamps(true, true, true);
+
+ t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
+ t.foreign("createdByUserId").references("id").inTable(TableName.Users).onDelete("SET NULL");
+ t.index("orgId");
+ t.index("projectId");
+ t.index("createdByUserId");
+ t.index(["resourceType", "enabled"]);
+ });
+ }
+
+ if (!(await knex.schema.hasTable(TableName.AlarmRecipient))) {
+ await knex.schema.createTable(TableName.AlarmRecipient, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ t.uuid("alarmId").notNullable();
+ t.string("principalType").notNullable();
+ t.string("principalId").notNullable();
+ t.timestamps(true, true, true);
+
+ t.foreign("alarmId").references("id").inTable(TableName.Alarm).onDelete("CASCADE");
+ t.index("alarmId");
+ t.unique(["alarmId", "principalType", "principalId"]);
+ });
+ }
+
+ if (!(await knex.schema.hasTable(TableName.AlarmChannel))) {
+ await knex.schema.createTable(TableName.AlarmChannel, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ t.uuid("alarmId").notNullable();
+ t.string("channelType").notNullable();
+ t.binary("encryptedConfig").notNullable();
+ t.boolean("enabled").notNullable().defaultTo(true);
+ t.timestamps(true, true, true);
+
+ t.foreign("alarmId").references("id").inTable(TableName.Alarm).onDelete("CASCADE");
+ t.index("alarmId");
+ });
+ }
+
+ if (!(await knex.schema.hasTable(TableName.AlarmHistory))) {
+ await knex.schema.createTable(TableName.AlarmHistory, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ t.uuid("alarmId").notNullable();
+ // Not notNullable: the now() default is applied DB-side, and keeping it nullable lets the
+ // generated Insert type treat it as optional (matching pki_alert_history).
+ t.timestamp("triggeredAt").defaultTo(knex.fn.now());
+ t.string("status").notNullable();
+ t.text("error").nullable();
+ t.timestamps(true, true, true);
+
+ t.foreign("alarmId").references("id").inTable(TableName.Alarm).onDelete("CASCADE");
+ // Composite covers the FK plus the dedup lookup (by alarm, ordered/filtered by time).
+ t.index(["alarmId", "triggeredAt"]);
+ });
+ }
+
+ if (!(await knex.schema.hasTable(TableName.AlarmHistoryTarget))) {
+ await knex.schema.createTable(TableName.AlarmHistoryTarget, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ t.uuid("alarmHistoryId").notNullable();
+ t.string("targetId").notNullable();
+ t.timestamps(true, true, true);
+
+ t.foreign("alarmHistoryId").references("id").inTable(TableName.AlarmHistory).onDelete("CASCADE");
+ t.index(["alarmHistoryId", "targetId"]);
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.AlarmHistoryTarget)) {
+ await knex.schema.dropTable(TableName.AlarmHistoryTarget);
+ }
+ if (await knex.schema.hasTable(TableName.AlarmHistory)) {
+ await knex.schema.dropTable(TableName.AlarmHistory);
+ }
+ if (await knex.schema.hasTable(TableName.AlarmChannel)) {
+ await knex.schema.dropTable(TableName.AlarmChannel);
+ }
+ if (await knex.schema.hasTable(TableName.AlarmRecipient)) {
+ await knex.schema.dropTable(TableName.AlarmRecipient);
+ }
+ if (await knex.schema.hasTable(TableName.Alarm)) {
+ await knex.schema.dropTable(TableName.Alarm);
+ }
+}
diff --git a/backend/src/db/schemas/alarm-channels.ts b/backend/src/db/schemas/alarm-channels.ts
new file mode 100644
index 0000000000..b824d14e84
--- /dev/null
+++ b/backend/src/db/schemas/alarm-channels.ts
@@ -0,0 +1,24 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { zodBuffer } from "@app/lib/zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AlarmChannelsSchema = z.object({
+ id: z.string().uuid(),
+ alarmId: z.string().uuid(),
+ channelType: z.string(),
+ encryptedConfig: zodBuffer,
+ enabled: z.boolean().default(true),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TAlarmChannels = z.infer<typeof AlarmChannelsSchema>;
+export type TAlarmChannelsInsert = Omit<z.input<typeof AlarmChannelsSchema>, TImmutableDBKeys>;
+export type TAlarmChannelsUpdate = Partial<Omit<z.input<typeof AlarmChannelsSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/alarm-history-target.ts b/backend/src/db/schemas/alarm-history-target.ts
new file mode 100644
index 0000000000..7fb206c801
--- /dev/null
+++ b/backend/src/db/schemas/alarm-history-target.ts
@@ -0,0 +1,20 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AlarmHistoryTargetSchema = z.object({
+ id: z.string().uuid(),
+ alarmHistoryId: z.string().uuid(),
+ targetId: z.string(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TAlarmHistoryTarget = z.infer<typeof AlarmHistoryTargetSchema>;
+export type TAlarmHistoryTargetInsert = Omit<z.input<typeof AlarmHistoryTargetSchema>, TImmutableDBKeys>;
+export type TAlarmHistoryTargetUpdate = Partial<Omit<z.input<typeof AlarmHistoryTargetSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/alarm-history.ts b/backend/src/db/schemas/alarm-history.ts
new file mode 100644
index 0000000000..2ac6f27627
--- /dev/null
+++ b/backend/src/db/schemas/alarm-history.ts
@@ -0,0 +1,22 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AlarmHistorySchema = z.object({
+ id: z.string().uuid(),
+ alarmId: z.string().uuid(),
+ triggeredAt: z.date().nullable().optional(),
+ status: z.string(),
+ error: z.string().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TAlarmHistory = z.infer<typeof AlarmHistorySchema>;
+export type TAlarmHistoryInsert = Omit<z.input<typeof AlarmHistorySchema>, TImmutableDBKeys>;
+export type TAlarmHistoryUpdate = Partial<Omit<z.input<typeof AlarmHistorySchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/alarm-recipients.ts b/backend/src/db/schemas/alarm-recipients.ts
new file mode 100644
index 0000000000..2b90ddefdf
--- /dev/null
+++ b/backend/src/db/schemas/alarm-recipients.ts
@@ -0,0 +1,21 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AlarmRecipientsSchema = z.object({
+ id: z.string().uuid(),
+ alarmId: z.string().uuid(),
+ principalType: z.string(),
+ principalId: z.string(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TAlarmRecipients = z.infer<typeof AlarmRecipientsSchema>;
+export type TAlarmRecipientsInsert = Omit<z.input<typeof AlarmRecipientsSchema>, TImmutableDBKeys>;
+export type TAlarmRecipientsUpdate = Partial<Omit<z.input<typeof AlarmRecipientsSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/alarms.ts b/backend/src/db/schemas/alarms.ts
new file mode 100644
index 0000000000..fe4c1af01e
--- /dev/null
+++ b/backend/src/db/schemas/alarms.ts
@@ -0,0 +1,29 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AlarmsSchema = z.object({
+ id: z.string().uuid(),
+ name: z.string(),
+ description: z.string().nullable().optional(),
+ resourceType: z.string(),
+ resourceId: z.string().nullable().optional(),
+ eventType: z.string(),
+ condition: z.unknown().nullable().optional(),
+ filters: z.unknown().nullable().optional(),
+ enabled: z.boolean().default(true),
+ orgId: z.string().uuid(),
+ projectId: z.string().nullable().optional(),
+ createdByUserId: z.string().uuid().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TAlarms = z.infer<typeof AlarmsSchema>;
+export type TAlarmsInsert = Omit<z.input<typeof AlarmsSchema>, TImmutableDBKeys>;
+export type TAlarmsUpdate = Partial<Omit<z.input<typeof AlarmsSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index f81a71be50..eeb17be853 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -11,6 +11,11 @@ export * from "./ai-mcp-endpoints";
export * from "./ai-mcp-server-tools";
export * from "./ai-mcp-server-user-credentials";
export * from "./ai-mcp-servers";
+export * from "./alarm-channels";
+export * from "./alarm-history";
+export * from "./alarm-history-target";
+export * from "./alarm-recipients";
+export * from "./alarms";
export * from "./app-connection-credential-rotations";
export * from "./app-connections";
export * from "./approval-policies";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index 153f6abc07..8bd281da43 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -44,6 +44,11 @@ export enum TableName {
PkiAlertHistoryCertificate = "pki_alert_history_certificate",
PkiCollection = "pki_collections",
PkiCollectionItem = "pki_collection_items",
+ Alarm = "alarms",
+ AlarmRecipient = "alarm_recipients",
+ AlarmChannel = "alarm_channels",
+ AlarmHistory = "alarm_history",
+ AlarmHistoryTarget = "alarm_history_target",
Groups = "groups",
GroupProjectMembership = "group_project_memberships",
GroupProjectMembershipRole = "group_project_membership_roles",
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
index 3640f0bf0b..d5fedd770e 100644
--- a/backend/src/lib/cron/cron-job.ts
+++ b/backend/src/lib/cron/cron-job.ts
@@ -42,7 +42,8 @@ export const CronJobName = {
AuditLogStreamOutboxStaleClaimSweeper: "audit-log-stream-outbox-stale-claim-sweeper",
AuditLogStreamOutboxCleanup: "audit-log-stream-outbox-cleanup",
LicenseUsageFlush: "license-usage-flush",
- PamCredentialRotationQueueRotations: "pam-credential-rotation-queue-rotations"
+ PamCredentialRotationQueueRotations: "pam-credential-rotation-queue-rotations",
+ DailyAlarmProcessing: "daily-alarm-processing"
} as const;
// ── tuning constants ──────────────────────────────────────────────────────────
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 022287a3d3..ab7f49de73 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -101,6 +101,7 @@ export enum QueueName {
InvalidateCache = "invalidate-cache",
SecretScanningV2 = "secret-scanning-v2",
UserNotification = "user-notification",
+ AlarmDispatch = "alarm-dispatch",
AuditReportGeneration = "audit-report-generation",
PamSessionExpiration = "pam-session-expiration",
PamDiscoveryScan = "pam-discovery-scan",
@@ -169,6 +170,7 @@ export enum QueueJobs {
DailyReminders = "daily-reminders",
SecretReminderMigration = "secret-reminder-migration",
UserNotification = "user-notification-job",
+ AlarmDispatch = "alarm-dispatch-job",
GenerateAuditReport = "generate-audit-report-job",
HealthAlert = "health-alert",
CertificateV3DailyAutoRenewal = "certificate-v3-daily-auto-renewal",
@@ -478,6 +480,10 @@ export type TQueueJobTypes = {
name: QueueJobs.UserNotification;
payload: { notifications: TCreateUserNotificationDTO[] };
};
+ [QueueName.AlarmDispatch]: {
+ name: QueueJobs.AlarmDispatch;
+ payload: { alarmId: string };
+ };
[QueueName.AuditReportGeneration]: {
name: QueueJobs.GenerateAuditReport;
payload: { auditReportId: string };
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 84ae62e5f9..2cfbe10d79 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -236,6 +236,17 @@ import { accessTokenQueueServiceFactory } from "@app/services/access-token-queue
import { accountRecoveryServiceFactory } from "@app/services/account-recovery/account-recovery-service";
import { additionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";
import { additionalPrivilegeServiceFactory } from "@app/services/additional-privilege/additional-privilege-service";
+import { alarmChannelDALFactory } from "@app/services/alarm/alarm-channel-dal";
+import { alarmDALFactory } from "@app/services/alarm/alarm-dal";
+import { alarmEngineFactory } from "@app/services/alarm/alarm-engine";
+import { alarmHistoryDALFactory } from "@app/services/alarm/alarm-history-dal";
+import { alarmProviderRegistryFactory } from "@app/services/alarm/alarm-provider-registry";
+import { alarmQueueServiceFactory } from "@app/services/alarm/alarm-queue";
+import { alarmRecipientDALFactory } from "@app/services/alarm/alarm-recipient-dal";
+import { alarmRecipientResolverFactory } from "@app/services/alarm/alarm-recipient-resolver";
+import { alarmServiceFactory } from "@app/services/alarm/alarm-service";
+import { identityCredentialAlarmDALFactory } from "@app/services/alarm/providers/identity-credential-alarm-dal";
+import { identityCredentialAlarmProviderFactory } from "@app/services/alarm/providers/identity-credential-alarm-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";
@@ -999,6 +1010,45 @@ export const registerRoutes = async (
const notificationService = notificationServiceFactory({ notificationQueue, userNotificationDAL });
+ const alarmDAL = alarmDALFactory(db);
+ const alarmChannelDAL = alarmChannelDALFactory(db);
+ const alarmRecipientDAL = alarmRecipientDALFactory(db);
+ const alarmHistoryDAL = alarmHistoryDALFactory(db);
+ const alarmProviderRegistry = alarmProviderRegistryFactory();
+ alarmProviderRegistry.register(
+ identityCredentialAlarmProviderFactory({
+ identityCredentialAlarmDAL: identityCredentialAlarmDALFactory(db),
+ permissionService
+ })
+ );
+ const alarmRecipientResolver = alarmRecipientResolverFactory({ userDAL, orgDAL, userGroupMembershipDAL });
+ const alarmEngine = alarmEngineFactory({
+ alarmChannelDAL,
+ alarmRecipientDAL,
+ alarmHistoryDAL,
+ alarmProviderRegistry,
+ alarmRecipientResolver,
+ kmsService,
+ orgDAL,
+ notificationService,
+ smtpService
+ });
+ const alarmQueue = alarmQueueServiceFactory({
+ cronJob,
+ queueService,
+ alarmDAL,
+ alarmProviderRegistry,
+ alarmEngine
+ });
+ const alarmService = alarmServiceFactory({
+ alarmDAL,
+ alarmChannelDAL,
+ alarmRecipientDAL,
+ alarmHistoryDAL,
+ alarmProviderRegistry,
+ kmsService
+ });
+
const auditLogStreamService = auditLogStreamServiceFactory({
licenseService,
permissionService,
@@ -3848,6 +3898,7 @@ export const registerRoutes = async (
projectCleanupQueue.init();
usageEventQueue.init();
healthAlert.init();
+ alarmQueue.init();
auditLogStreamOutboxQueue.init();
pkiSyncCleanup.init();
pamDiscoveryService.init();
@@ -4035,6 +4086,7 @@ export const registerRoutes = async (
projectEvents: projectEventsService,
projectEventsSSE: projectEventsSSEService,
notification: notificationService,
+ alarm: alarmService,
announcement: announcementService,
mfaSession: mfaSessionService,
membershipUser: membershipUserService,
diff --git a/backend/src/server/routes/v1/alarm-router.ts b/backend/src/server/routes/v1/alarm-router.ts
new file mode 100644
index 0000000000..dc5e3cd391
--- /dev/null
+++ b/backend/src/server/routes/v1/alarm-router.ts
@@ -0,0 +1,187 @@
+import { z } from "zod";
+
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AlarmChannelType } from "@app/services/alarm/alarm-channel-types";
+import { AlarmPrincipalType, AlarmRunStatus } from "@app/services/alarm/alarm-types";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+const RecipientInputSchema = z.object({
+ principalType: z.nativeEnum(AlarmPrincipalType),
+ principalId: z.string().min(1)
+});
+
+const ChannelInputSchema = z.object({
+ channelType: z.nativeEnum(AlarmChannelType),
+ config: z.record(z.unknown()).default({}),
+ enabled: z.boolean().optional()
+});
+
+const AlarmResponseSchema = z.object({
+ id: z.string().uuid(),
+ name: z.string(),
+ description: z.string().nullable(),
+ resourceType: z.string(),
+ resourceId: z.string().nullable(),
+ eventType: z.string(),
+ condition: z.unknown().nullable(),
+ filters: z.unknown().nullable(),
+ enabled: z.boolean(),
+ orgId: z.string(),
+ projectId: z.string().nullable(),
+ recipients: z.array(z.object({ principalType: z.string(), principalId: z.string() })),
+ channels: z.array(
+ z.object({
+ id: z.string().uuid(),
+ channelType: z.string(),
+ config: z.record(z.unknown()),
+ enabled: z.boolean(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+ })
+ ),
+ lastRun: z
+ .object({ timestamp: z.date(), status: z.nativeEnum(AlarmRunStatus), error: z.string().nullable() })
+ .nullable(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export const registerAlarmRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "POST",
+ url: "/",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "createAlarm",
+ body: z.object({
+ name: z.string().min(1).max(255),
+ description: z.string().max(1000).optional(),
+ resourceType: z.string().min(1),
+ resourceId: z.string().nullable().optional(),
+ eventType: z.string().min(1),
+ condition: z.unknown().optional(),
+ filters: z.unknown().optional(),
+ enabled: z.boolean().optional(),
+ projectId: z.string().nullable().optional(),
+ recipients: z.array(RecipientInputSchema).default([]),
+ channels: z.array(ChannelInputSchema).min(1)
+ }),
+ response: { 200: z.object({ alarm: AlarmResponseSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const alarm = await server.services.alarm.createAlarm({
+ ...req.body,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+ return { alarm };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "listAlarms",
+ querystring: z.object({
+ resourceType: z.string().min(1),
+ resourceId: z.string().optional(),
+ projectId: z.string().optional(),
+ enabled: z.coerce.boolean().optional()
+ }),
+ response: { 200: z.object({ alarms: AlarmResponseSchema.array() }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const alarms = await server.services.alarm.listAlarms({
+ ...req.query,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+ return { alarms };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:alarmId",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "getAlarmById",
+ params: z.object({ alarmId: z.string().uuid() }),
+ response: { 200: z.object({ alarm: AlarmResponseSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const alarm = await server.services.alarm.getAlarmById({
+ alarmId: req.params.alarmId,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+ return { alarm };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:alarmId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "updateAlarm",
+ params: z.object({ alarmId: z.string().uuid() }),
+ body: z.object({
+ name: z.string().min(1).max(255).optional(),
+ description: z.string().max(1000).nullable().optional(),
+ condition: z.unknown().optional(),
+ filters: z.unknown().optional(),
+ enabled: z.boolean().optional(),
+ recipients: z.array(RecipientInputSchema).optional(),
+ channels: z.array(ChannelInputSchema).min(1).optional()
+ }),
+ response: { 200: z.object({ alarm: AlarmResponseSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const alarm = await server.services.alarm.updateAlarm({
+ alarmId: req.params.alarmId,
+ ...req.body,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+ return { alarm };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:alarmId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "deleteAlarm",
+ params: z.object({ alarmId: z.string().uuid() }),
+ response: { 200: z.object({ alarm: z.object({ id: z.string().uuid() }) }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const alarm = await server.services.alarm.deleteAlarm({
+ alarmId: req.params.alarmId,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+ return { alarm };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.ts
index 7506bc0353..95b19c7d23 100644
--- a/backend/src/server/routes/v1/index.ts
+++ b/backend/src/server/routes/v1/index.ts
@@ -11,6 +11,7 @@ import { registerSecretSyncRouter, SECRET_SYNC_REGISTER_ROUTER_MAP } from "@app/
import { registerAccountRecoveryRouter } from "./account-recovery-router";
import { registerAdminRouter } from "./admin-router";
+import { registerAlarmRouter } from "./alarm-router";
import { registerAnnouncementRouter } from "./announcement-router";
import { APPROVAL_POLICY_REGISTER_ROUTER_MAP } from "./approval-policy-routers";
import { registerAuthRoutes } from "./auth-router";
@@ -138,6 +139,7 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
await server.register(registerOrgAdminRouter, { prefix: "/organization-admin" });
await server.register(registerUserRouter, { prefix: "/user" });
await server.register(registerNotificationRouter, { prefix: "/notifications" });
+ await server.register(registerAlarmRouter, { prefix: "/alarms" });
await server.register(registerAnnouncementRouter, { prefix: "/announcement" });
await server.register(registerInviteOrgRouter, { prefix: "/invite-org" });
await server.register(registerUserActionRouter, { prefix: "/user-action" });
diff --git a/backend/src/services/alarm/alarm-channel-constants.ts b/backend/src/services/alarm/alarm-channel-constants.ts
new file mode 100644
index 0000000000..440c97b8c7
--- /dev/null
+++ b/backend/src/services/alarm/alarm-channel-constants.ts
@@ -0,0 +1,11 @@
+export const ALARM_CHANNEL_RETRY_CONFIG = { maxRetries: 3, delayMs: 3000 };
+
+export const RETRYABLE_NETWORK_ERRORS = [
+ "ECONNREFUSED",
+ "ENOTFOUND",
+ "ETIMEDOUT",
+ "ECONNRESET",
+ "ECONNABORTED",
+ "ENETUNREACH",
+ "EHOSTUNREACH"
+];
diff --git a/backend/src/services/alarm/alarm-channel-crypto-fns.ts b/backend/src/services/alarm/alarm-channel-crypto-fns.ts
new file mode 100644
index 0000000000..9175ed9b54
--- /dev/null
+++ b/backend/src/services/alarm/alarm-channel-crypto-fns.ts
@@ -0,0 +1,21 @@
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
+
+export type TAlarmEncryptor = (data: { plainText: Buffer }) => { cipherTextBlob: Buffer };
+export type TAlarmDecryptor = (data: { cipherTextBlob: Buffer }) => Buffer;
+
+export const getAlarmChannelCipher = (
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">,
+ scope: { orgId: string; projectId?: string | null }
+) =>
+ kmsService.createCipherPairWithDataKey(
+ scope.projectId
+ ? { type: KmsDataKey.SecretManager, projectId: scope.projectId }
+ : { type: KmsDataKey.Organization, orgId: scope.orgId }
+ );
+
+export const encryptChannelConfig = (config: unknown, encryptor: TAlarmEncryptor): Buffer =>
+ encryptor({ plainText: Buffer.from(JSON.stringify(config)) }).cipherTextBlob;
+
+export const decryptChannelConfig = <T = unknown>(encryptedConfig: Buffer, decryptor: TAlarmDecryptor): T =>
+ JSON.parse(decryptor({ cipherTextBlob: encryptedConfig }).toString()) as T;
diff --git a/backend/src/services/alarm/alarm-channel-dal.ts b/backend/src/services/alarm/alarm-channel-dal.ts
new file mode 100644
index 0000000000..7c685fe4a1
--- /dev/null
+++ b/backend/src/services/alarm/alarm-channel-dal.ts
@@ -0,0 +1,50 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName, TAlarmChannels, TAlarmChannelsInsert } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify, selectAllTableCols } from "@app/lib/knex";
+
+export type TAlarmChannelDALFactory = ReturnType<typeof alarmChannelDALFactory>;
+
+export const alarmChannelDALFactory = (db: TDbClient) => {
+ const alarmChannelOrm = ormify(db, TableName.AlarmChannel);
+
+ const insertMany = async (data: TAlarmChannelsInsert[], tx?: Knex): Promise<TAlarmChannels[]> => {
+ try {
+ if (!data.length) return [];
+ const res = await (tx || db)(TableName.AlarmChannel).insert(data).returning("*");
+ return res as TAlarmChannels[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "InsertMany" });
+ }
+ };
+
+ const findByAlarmId = async (alarmId: string, tx?: Knex): Promise<TAlarmChannels[]> => {
+ try {
+ const channels = await (tx || db.replicaNode())(TableName.AlarmChannel)
+ .where(`${TableName.AlarmChannel}.alarmId`, alarmId)
+ .select(selectAllTableCols(TableName.AlarmChannel))
+ .orderBy(`${TableName.AlarmChannel}.createdAt`, "asc");
+
+ return channels as TAlarmChannels[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindByAlarmId" });
+ }
+ };
+
+ const deleteByAlarmId = async (alarmId: string, tx?: Knex): Promise<number> => {
+ try {
+ return await (tx || db)(TableName.AlarmChannel).where(`${TableName.AlarmChannel}.alarmId`, alarmId).del();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "DeleteByAlarmId" });
+ }
+ };
+
+ return {
+ ...alarmChannelOrm,
+ insertMany,
+ findByAlarmId,
+ deleteByAlarmId
+ };
+};
diff --git a/backend/src/services/alarm/alarm-channel-types.ts b/backend/src/services/alarm/alarm-channel-types.ts
new file mode 100644
index 0000000000..826f6478a2
--- /dev/null
+++ b/backend/src/services/alarm/alarm-channel-types.ts
@@ -0,0 +1,113 @@
+import RE2 from "re2";
+import { z } from "zod";
+
+import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
+import { NotificationType } from "@app/services/notification/notification-types";
+import { TSmtpService } from "@app/services/smtp/smtp-service";
+
+export enum AlarmChannelType {
+ IN_APP = "in-app",
+ EMAIL = "email",
+ SLACK = "slack",
+ WEBHOOK = "webhook",
+ PAGERDUTY = "pagerduty"
+}
+
+export type TAlarmSeverity = "critical" | "error" | "warning" | "info";
+
+export type TAlarmItem = {
+ id: string;
+ title: string; // primary label (e.g. certificate common name, client-secret description)
+ identifier?: string; // secondary label (e.g. serial number, client-secret id)
+ fields?: Array<{ label: string; value: string }>; // extra display key-values (expiry date, days left, reason)
+};
+
+export type TAlarmPayload = {
+ alarm: {
+ id: string;
+ name: string;
+ orgId: string;
+ projectId?: string;
+ resourceType: string; // dot-namespaced, e.g. "pki.certificate"
+ condition?: string; // display label for the "when", e.g. "30d"
+ viewUrl: string; // deep link into the app, built by the provider
+ };
+ eventKey: string; // dot-namespaced event, e.g. "pki.certificate.expiration"
+ eventLabel: string; // human label, e.g. "Expiration"
+ webhookType: string; // CloudEvents `type` string, e.g. "com.infisical.pki.certificate.expiration"
+ resourceKind: string; // display noun, e.g. "Certificate", "Client Secret"
+ severity: TAlarmSeverity;
+ summary: string; // one-line human summary
+ items: TAlarmItem[];
+ // Required by the in-app channel; ignored by the others. Kept optional so endpoint-only alarms
+ // need not supply it.
+ notificationType?: NotificationType;
+};
+
+export type TChannelResult = { success: boolean; error?: string };
+
+export type TAlarmRecipient = {
+ userId?: string;
+ email: string;
+ firstName?: string | null;
+};
+
+export type TAlarmChannelDeps = {
+ smtpService: Pick<TSmtpService, "sendMail">;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
+};
+
+export type TAlarmChannelSendContext = {
+ channelId: string;
+ config: unknown; // raw config; each channel validates against its own schema
+ payload: TAlarmPayload;
+ recipient?: TAlarmRecipient; // present for directed channels
+ deps: TAlarmChannelDeps;
+};
+
+export type TAlarmChannelDefinition = {
+ type: AlarmChannelType;
+ directed: boolean;
+ configSchema: z.ZodTypeAny;
+ send: (ctx: TAlarmChannelSendContext) => Promise<TChannelResult>;
+};
+
+export const EmailChannelConfigSchema = z.object({}).strip();
+
+export const InAppChannelConfigSchema = z.object({}).strip();
+
+export const WebhookChannelConfigSchema = z.object({
+ url: z
+ .string()
+ .url()
+ .refine((url) => url.startsWith("https://"), "Webhook URL must use HTTPS"),
+ signingSecret: z.string().max(256).optional().nullable()
+});
+
+export const SlackChannelConfigSchema = z.object({
+ webhookUrl: z
+ .string()
+ .url()
+ .refine((url) => url.startsWith("https://"), "Slack webhook URL must use HTTPS")
+ .refine((url) => {
+ try {
+ return new URL(url).hostname === "hooks.slack.com";
+ } catch {
+ return false;
+ }
+ }, "Slack webhook URL must be from hooks.slack.com")
+});
+
+export const pagerDutyIntegrationKeyRegex = new RE2("^[a-f0-9]{32}$", "i");
+
+export const PagerDutyChannelConfigSchema = z.object({
+ integrationKey: z
+ .string()
+ .refine((val) => pagerDutyIntegrationKeyRegex.test(val), "Integration key must be a 32-character hex string")
+});
+
+export type TEmailChannelConfig = z.infer<typeof EmailChannelConfigSchema>;
+export type TInAppChannelConfig = z.infer<typeof InAppChannelConfigSchema>;
+export type TWebhookChannelConfig = z.infer<typeof WebhookChannelConfigSchema>;
+export type TSlackChannelConfig = z.infer<typeof SlackChannelConfigSchema>;
+export type TPagerDutyChannelConfig = z.infer<typeof PagerDutyChannelConfigSchema>;
diff --git a/backend/src/services/alarm/alarm-dal.ts b/backend/src/services/alarm/alarm-dal.ts
new file mode 100644
index 0000000000..33465ecc2a
--- /dev/null
+++ b/backend/src/services/alarm/alarm-dal.ts
@@ -0,0 +1,31 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName, TAlarms } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify, selectAllTableCols } from "@app/lib/knex";
+
+export type TAlarmDALFactory = ReturnType<typeof alarmDALFactory>;
+
+export const alarmDALFactory = (db: TDbClient) => {
+ const alarmOrm = ormify(db, TableName.Alarm);
+
+ const findEnabledByResourceType = async (resourceType: string, tx?: Knex): Promise<TAlarms[]> => {
+ try {
+ const alarms = await (tx || db.replicaNode())(TableName.Alarm)
+ .where(`${TableName.Alarm}.resourceType`, resourceType)
+ .where(`${TableName.Alarm}.enabled`, true)
+ .select(selectAllTableCols(TableName.Alarm))
+ .orderBy(`${TableName.Alarm}.createdAt`, "asc");
+
+ return alarms as TAlarms[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindEnabledByResourceType" });
+ }
+ };
+
+ return {
+ ...alarmOrm,
+ findEnabledByResourceType
+ };
+};
diff --git a/backend/src/services/alarm/alarm-engine.test.ts b/backend/src/services/alarm/alarm-engine.test.ts
new file mode 100644
index 0000000000..70a53ac541
--- /dev/null
+++ b/backend/src/services/alarm/alarm-engine.test.ts
@@ -0,0 +1,179 @@
+import { z } from "zod";
+
+import { NotificationType } from "@app/services/notification/notification-types";
+
+import { TAlarmPayload } from "./alarm-channel-types";
+import { alarmEngineFactory, TAlarmEngineDep } from "./alarm-engine";
+import { alarmProviderRegistryFactory } from "./alarm-provider-registry";
+import { AlarmPrincipalType, AlarmRunStatus, IResourceAlarmProvider, TAlarmContext } from "./alarm-types";
+
+type TTarget = { id: string };
+
+const RESOURCE_TYPE = "test.resource";
+
+const makeAlarm = () => ({
+ id: "alarm-1",
+ name: "test-alarm",
+ description: null,
+ resourceType: RESOURCE_TYPE,
+ resourceId: null,
+ eventType: "test.resource.expiration",
+ condition: { alertBefore: "30d" },
+ filters: null,
+ enabled: true,
+ orgId: "org-1",
+ projectId: null,
+ createdByUserId: null,
+ createdAt: new Date(),
+ updatedAt: new Date()
+});
+
+const makeProvider = (targets: TTarget[]): IResourceAlarmProvider<TTarget> => ({
+ resourceType: RESOURCE_TYPE,
+ eventTypes: ["test.resource.expiration"],
+ conditionSchema: z.any(),
+ findDueTargets: async () => targets,
+ assertPermission: async () => undefined,
+ assertResourceInScope: async () => undefined,
+ targetId: (target) => target.id,
+ buildPayload: (_alarm: TAlarmContext, matched: TTarget[]): TAlarmPayload => ({
+ alarm: {
+ id: "alarm-1",
+ name: "test-alarm",
+ orgId: "org-1",
+ resourceType: RESOURCE_TYPE,
+ viewUrl: "https://app.infisical.com/x"
+ },
+ eventKey: "test.resource.expiration",
+ eventLabel: "Expiration",
+ webhookType: "com.infisical.test.resource.expiration",
+ resourceKind: "Test Resource",
+ severity: "warning",
+ summary: `${matched.length} expiring`,
+ notificationType: NotificationType.ALARM_CHANNEL_FAILED,
+ items: matched.map((target) => ({ id: target.id, title: target.id }))
+ })
+});
+
+// A KMS mock whose decryptor is the identity function, so encryptedConfig is just JSON bytes.
+const kmsServiceMock = {
+ createCipherPairWithDataKey: async () => ({
+ encryptor: ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: plainText }),
+ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob
+ })
+};
+
+const encConfig = (config: unknown) => Buffer.from(JSON.stringify(config));
+
+const buildEngine = (opts: {
+ targets: TTarget[];
+ channels: Array<{ id: string; channelType: string; encryptedConfig: Buffer; enabled: boolean }>;
+ recentlyAlarmed?: string[];
+ recipients?: Array<{ userId: string; email: string; firstName?: string | null }>;
+}) => {
+ const registry = alarmProviderRegistryFactory();
+ registry.register(makeProvider(opts.targets) as IResourceAlarmProvider);
+
+ const sentMail: Array<{ recipients: string[] }> = [];
+ const createdNotifications: unknown[][] = [];
+ const historyWrites: Array<{ targetIds: string[]; status: string }> = [];
+
+ const engine = alarmEngineFactory({
+ alarmChannelDAL: { findByAlarmId: async () => opts.channels },
+ alarmRecipientDAL: {
+ findByAlarmId: async () => [
+ {
+ id: "r1",
+ alarmId: "alarm-1",
+ principalType: AlarmPrincipalType.USER,
+ principalId: "u1",
+ createdAt: new Date(),
+ updatedAt: new Date()
+ }
+ ]
+ },
+ alarmHistoryDAL: {
+ findRecentlyAlarmedTargets: async () => opts.recentlyAlarmed ?? [],
+ createWithTargets: async (_alarmId: string, targetIds: string[], options: { status: string }) => {
+ historyWrites.push({ targetIds, status: options.status });
+ return {} as never;
+ }
+ },
+ alarmProviderRegistry: registry,
+ alarmRecipientResolver: {
+ resolve: async () => opts.recipients ?? [{ userId: "u1", email: "[email protected]", firstName: "U" }]
+ },
+ kmsService: kmsServiceMock,
+ orgDAL: { findOrgMembersByRole: async () => [] },
+ notificationService: {
+ createUserNotifications: async (data: unknown[]) => {
+ createdNotifications.push(data);
+ }
+ },
+ smtpService: {
+ sendMail: async (opt: { recipients: string[] }) => {
+ sentMail.push({ recipients: opt.recipients });
+ }
+ }
+ } as unknown as TAlarmEngineDep);
+
+ return { engine, sentMail, createdNotifications, historyWrites };
+};
+
+describe("alarm engine", () => {
+ test("dispatches email + in-app to resolved recipients and records history", async () => {
+ const { engine, sentMail, createdNotifications, historyWrites } = buildEngine({
+ targets: [{ id: "t1" }, { id: "t2" }],
+ channels: [
+ { id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true },
+ { id: "c-inapp", channelType: "in-app", encryptedConfig: encConfig({}), enabled: true }
+ ]
+ });
+
+ await engine.runAlarm(makeAlarm());
+
+ expect(sentMail).toHaveLength(1);
+ expect(sentMail[0].recipients).toEqual(["[email protected]"]);
+ expect(createdNotifications).toHaveLength(1); // in-app delivery, not a failure fallback
+ expect(historyWrites).toHaveLength(1);
+ expect(historyWrites[0].targetIds).toEqual(["t1", "t2"]);
+ expect(historyWrites[0].status).toBe(AlarmRunStatus.SUCCESS);
+ });
+
+ test("dedups targets already alarmed within the window", async () => {
+ const { engine, historyWrites } = buildEngine({
+ targets: [{ id: "t1" }, { id: "t2" }],
+ channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }],
+ recentlyAlarmed: ["t1"]
+ });
+
+ await engine.runAlarm(makeAlarm());
+
+ expect(historyWrites).toHaveLength(1);
+ expect(historyWrites[0].targetIds).toEqual(["t2"]);
+ });
+
+ test("skips entirely when all targets were recently alarmed", async () => {
+ const { engine, historyWrites, sentMail } = buildEngine({
+ targets: [{ id: "t1" }],
+ channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }],
+ recentlyAlarmed: ["t1"]
+ });
+
+ await engine.runAlarm(makeAlarm());
+
+ expect(sentMail).toHaveLength(0);
+ expect(historyWrites).toHaveLength(0);
+ });
+
+ test("writes no history when there are no enabled channels", async () => {
+ const { engine, historyWrites } = buildEngine({
+ targets: [{ id: "t1" }],
+ channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: false }]
+ });
+
+ await engine.runAlarm(makeAlarm());
+
+ expect(historyWrites).toHaveLength(0);
+ });
+});
diff --git a/backend/src/services/alarm/alarm-engine.ts b/backend/src/services/alarm/alarm-engine.ts
new file mode 100644
index 0000000000..17ff990d55
--- /dev/null
+++ b/backend/src/services/alarm/alarm-engine.ts
@@ -0,0 +1,187 @@
+import { OrgMembershipRole, OrgMembershipStatus, TAlarms } from "@app/db/schemas";
+import { logger } from "@app/lib/logger";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
+import { NotificationType } from "@app/services/notification/notification-types";
+import { TOrgDALFactory } from "@app/services/org/org-dal";
+import { TSmtpService } from "@app/services/smtp/smtp-service";
+
+import { decryptChannelConfig, getAlarmChannelCipher } from "./alarm-channel-crypto-fns";
+import { TAlarmChannelDALFactory } from "./alarm-channel-dal";
+import { AlarmChannelType, TAlarmChannelDeps, TAlarmRecipient } from "./alarm-channel-types";
+import { TAlarmHistoryDALFactory } from "./alarm-history-dal";
+import { TAlarmProviderRegistry } from "./alarm-provider-registry";
+import { TAlarmRecipientDALFactory } from "./alarm-recipient-dal";
+import { TAlarmRecipientResolver } from "./alarm-recipient-resolver";
+import { AlarmRunStatus, DEFAULT_DEDUP_WINDOW_HOURS, TAlarmContext } from "./alarm-types";
+import { ALARM_CHANNEL_REGISTRY } from "./channels/alarm-channel-registry";
+
+const FAILURE_NOTIFICATION_MAX_ERROR_LENGTH = 200;
+
+export type TAlarmEngineDep = {
+ alarmChannelDAL: Pick<TAlarmChannelDALFactory, "findByAlarmId">;
+ alarmRecipientDAL: Pick<TAlarmRecipientDALFactory, "findByAlarmId">;
+ alarmHistoryDAL: Pick<TAlarmHistoryDALFactory, "createWithTargets" | "findRecentlyAlarmedTargets">;
+ alarmProviderRegistry: TAlarmProviderRegistry;
+ alarmRecipientResolver: TAlarmRecipientResolver;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ orgDAL: Pick<TOrgDALFactory, "findOrgMembersByRole">;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
+ smtpService: Pick<TSmtpService, "sendMail">;
+};
+
+export type TAlarmEngine = ReturnType<typeof alarmEngineFactory>;
+
+export const alarmEngineFactory = ({
+ alarmChannelDAL,
+ alarmRecipientDAL,
+ alarmHistoryDAL,
+ alarmProviderRegistry,
+ alarmRecipientResolver,
+ kmsService,
+ orgDAL,
+ notificationService,
+ smtpService
+}: TAlarmEngineDep) => {
+ const notifyAdminsOfFailure = async (alarm: TAlarms, viewUrl: string, error: string) => {
+ try {
+ const admins = (await orgDAL.findOrgMembersByRole(alarm.orgId, OrgMembershipRole.Admin)).filter(
+ (admin) => admin.status !== OrgMembershipStatus.Invited && admin.user?.id
+ );
+ if (admins.length === 0) return;
+
+ const truncatedError =
+ error.length > FAILURE_NOTIFICATION_MAX_ERROR_LENGTH
+ ? `${error.substring(0, FAILURE_NOTIFICATION_MAX_ERROR_LENGTH)}...`
+ : error;
+
+ await notificationService.createUserNotifications(
+ admins.map((admin) => ({
+ userId: admin.user.id,
+ orgId: alarm.orgId,
+ type: NotificationType.ALARM_CHANNEL_FAILED,
+ title: `Alarm Channel Failed: ${alarm.name}`,
+ body: `Your alarm **${alarm.name}** failed to deliver on one or more channels: \`${truncatedError}\``,
+ link: viewUrl
+ }))
+ );
+ } catch (err) {
+ logger.error(err, `Failed to notify admins of alarm channel failure [alarmId=${alarm.id}]`);
+ }
+ };
+
+ const runAlarm = async (alarm: TAlarms) => {
+ const provider = alarmProviderRegistry.get(alarm.resourceType);
+ if (!provider) {
+ logger.warn(`No alarm provider registered for resource type '${alarm.resourceType}' [alarmId=${alarm.id}]`);
+ return;
+ }
+
+ const targets = await provider.findDueTargets({
+ orgId: alarm.orgId,
+ projectId: alarm.projectId,
+ resourceId: alarm.resourceId,
+ eventType: alarm.eventType,
+ condition: alarm.condition,
+ filters: alarm.filters
+ });
+ if (targets.length === 0) return;
+
+ const window = provider.dedupWindowHours?.(alarm.condition) ?? DEFAULT_DEDUP_WINDOW_HOURS;
+ const candidateIds = targets.map((target) => provider.targetId(target));
+ const recentlyAlarmed = new Set(await alarmHistoryDAL.findRecentlyAlarmedTargets(alarm.id, candidateIds, window));
+ const dueTargets = targets.filter((target) => !recentlyAlarmed.has(provider.targetId(target)));
+ if (dueTargets.length === 0) return;
+
+ const channels = (await alarmChannelDAL.findByAlarmId(alarm.id)).filter((channel) => channel.enabled);
+ if (channels.length === 0) return;
+
+ const alarmContext: TAlarmContext = {
+ id: alarm.id,
+ name: alarm.name,
+ orgId: alarm.orgId,
+ projectId: alarm.projectId,
+ resourceType: alarm.resourceType,
+ resourceId: alarm.resourceId,
+ eventType: alarm.eventType,
+ condition: alarm.condition,
+ filters: alarm.filters
+ };
+ const payload = provider.buildPayload(alarmContext, dueTargets);
+
+ const { decryptor } = await getAlarmChannelCipher(kmsService, {
+ orgId: alarm.orgId,
+ projectId: alarm.projectId
+ });
+
+ const hasDirectedChannel = channels.some(
+ (channel) => ALARM_CHANNEL_REGISTRY[channel.channelType as AlarmChannelType]?.directed
+ );
+ let recipients: TAlarmRecipient[] = [];
+ if (hasDirectedChannel) {
+ recipients = await alarmRecipientResolver.resolve(alarm.orgId, await alarmRecipientDAL.findByAlarmId(alarm.id));
+ }
+
+ const deps: TAlarmChannelDeps = { smtpService, notificationService };
+
+ const channelResults = await Promise.all(
+ channels.map(async (channel) => {
+ const definition = ALARM_CHANNEL_REGISTRY[channel.channelType as AlarmChannelType];
+ if (!definition) return { channelType: channel.channelType, success: false, error: "Unknown channel type" };
+
+ let config: unknown;
+ try {
+ config = decryptChannelConfig(channel.encryptedConfig, decryptor);
+ } catch (err) {
+ logger.error(err, `Failed to decrypt alarm channel config [channelId=${channel.id}]`);
+ return { channelType: channel.channelType, success: false, error: "Failed to decrypt channel config" };
+ }
+
+ try {
+ if (definition.directed) {
+ const deliveries = recipients.length > 0 ? recipients : [undefined];
+ const results = await Promise.all(
+ deliveries.map((recipient) =>
+ definition.send({ channelId: channel.id, config, payload, recipient, deps })
+ )
+ );
+ const failures = results.filter((result) => !result.success);
+ if (failures.length > 0) {
+ return {
+ channelType: channel.channelType,
+ success: false,
+ error: failures.map((f) => f.error).join("; ")
+ };
+ }
+ return { channelType: channel.channelType, success: true };
+ }
+
+ const result = await definition.send({ channelId: channel.id, config, payload, deps });
+ return { channelType: channel.channelType, ...result };
+ } catch (err) {
+ const error = err instanceof Error ? err.message : "Unknown error";
+ logger.error(err, `Failed to dispatch alarm ${channel.channelType} channel [alarmId=${alarm.id}]`);
+ return { channelType: channel.channelType, success: false, error };
+ }
+ })
+ );
+
+ const errors = channelResults
+ .filter((result) => !result.success && result.error)
+ .map((result) => `${result.channelType}: ${result.error}`);
+ const status = errors.length > 0 ? AlarmRunStatus.FAILED : AlarmRunStatus.SUCCESS;
+ const errorText = errors.length > 0 ? errors.join("\n") : undefined;
+
+ if (errorText) {
+ await notifyAdminsOfFailure(alarm, payload.alarm.viewUrl, errorText);
+ }
+
+ await alarmHistoryDAL.createWithTargets(
+ alarm.id,
+ dueTargets.map((target) => provider.targetId(target)),
+ { status, error: errorText }
+ );
+ };
+
+ return { runAlarm };
+};
diff --git a/backend/src/services/alarm/alarm-history-dal.ts b/backend/src/services/alarm/alarm-history-dal.ts
new file mode 100644
index 0000000000..461760e23d
--- /dev/null
+++ b/backend/src/services/alarm/alarm-history-dal.ts
@@ -0,0 +1,83 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName, TAlarmHistory } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify } from "@app/lib/knex";
+
+export type TAlarmHistoryDALFactory = ReturnType<typeof alarmHistoryDALFactory>;
+
+export const alarmHistoryDALFactory = (db: TDbClient) => {
+ const alarmHistoryOrm = ormify(db, TableName.AlarmHistory);
+
+ const createWithTargets = async (
+ alarmId: string,
+ targetIds: string[],
+ options: { status: string; error?: string }
+ ): Promise<TAlarmHistory> => {
+ try {
+ return await db.transaction(async (tx) => {
+ const [history] = await tx(TableName.AlarmHistory)
+ .insert({ alarmId, status: options.status, error: options.error })
+ .returning("*");
+
+ if (targetIds.length > 0) {
+ await tx(TableName.AlarmHistoryTarget).insert(
+ targetIds.map((targetId) => ({ alarmHistoryId: history.id, targetId }))
+ );
+ }
+
+ return history;
+ });
+ } catch (error) {
+ throw new DatabaseError({ error, name: "CreateWithTargets" });
+ }
+ };
+
+ const findRecentlyAlarmedTargets = async (
+ alarmId: string,
+ targetIds: string[],
+ withinHours: number,
+ tx?: Knex
+ ): Promise<string[]> => {
+ try {
+ if (targetIds.length === 0) return [];
+
+ const DEDUP_DRIFT_BUFFER_MINUTES = 15;
+ const cutoffDate = new Date();
+ cutoffDate.setHours(cutoffDate.getHours() - withinHours);
+ cutoffDate.setMinutes(cutoffDate.getMinutes() + DEDUP_DRIFT_BUFFER_MINUTES);
+
+ const rows = (await (tx || db.replicaNode())(`${TableName.AlarmHistory} as hist`)
+ .join(`${TableName.AlarmHistoryTarget} as tgt`, "hist.id", "tgt.alarmHistoryId")
+ .where("hist.alarmId", alarmId)
+ .where("hist.triggeredAt", ">=", cutoffDate)
+ .whereIn("tgt.targetId", targetIds)
+ .distinct("tgt.targetId")
+ .select("tgt.targetId")) as Array<{ targetId: string }>;
+
+ return rows.map((row) => row.targetId);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindRecentlyAlarmedTargets" });
+ }
+ };
+
+ const findLatestByAlarmId = async (alarmId: string, tx?: Knex): Promise<TAlarmHistory | undefined> => {
+ try {
+ const [latest] = await (tx || db.replicaNode())(TableName.AlarmHistory)
+ .where(`${TableName.AlarmHistory}.alarmId`, alarmId)
+ .orderBy(`${TableName.AlarmHistory}.triggeredAt`, "desc")
+ .limit(1);
+ return latest as TAlarmHistory | undefined;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindLatestByAlarmId" });
+ }
+ };
+
+ return {
+ ...alarmHistoryOrm,
+ createWithTargets,
+ findRecentlyAlarmedTargets,
+ findLatestByAlarmId
+ };
+};
diff --git a/backend/src/services/alarm/alarm-provider-registry.ts b/backend/src/services/alarm/alarm-provider-registry.ts
new file mode 100644
index 0000000000..a7d529849d
--- /dev/null
+++ b/backend/src/services/alarm/alarm-provider-registry.ts
@@ -0,0 +1,22 @@
+import { IResourceAlarmProvider } from "./alarm-types";
+
+export type TAlarmProviderRegistry = ReturnType<typeof alarmProviderRegistryFactory>;
+
+export const alarmProviderRegistryFactory = () => {
+ const providers = new Map<string, IResourceAlarmProvider>();
+
+ const register = (provider: IResourceAlarmProvider) => {
+ if (providers.has(provider.resourceType)) {
+ throw new Error(`Alarm provider already registered for resource type '${provider.resourceType}'`);
+ }
+ providers.set(provider.resourceType, provider);
+ };
+
+ const get = (resourceType: string): IResourceAlarmProvider | undefined => providers.get(resourceType);
+
+ const resourceTypes = (): string[] => [...providers.keys()];
+
+ const list = (): IResourceAlarmProvider[] => [...providers.values()];
+
+ return { register, get, resourceTypes, list };
+};
diff --git a/backend/src/services/alarm/alarm-queue.ts b/backend/src/services/alarm/alarm-queue.ts
new file mode 100644
index 0000000000..1cdada191d
--- /dev/null
+++ b/backend/src/services/alarm/alarm-queue.ts
@@ -0,0 +1,81 @@
+import { getConfig } from "@app/lib/config/env";
+import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
+import { logger } from "@app/lib/logger";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+
+import { TAlarmDALFactory } from "./alarm-dal";
+import { TAlarmEngine } from "./alarm-engine";
+import { TAlarmProviderRegistry } from "./alarm-provider-registry";
+
+type TAlarmQueueServiceFactoryDep = {
+ cronJob: TCronJobFactory;
+ queueService: TQueueServiceFactory;
+ alarmDAL: Pick<TAlarmDALFactory, "findEnabledByResourceType" | "findById">;
+ alarmProviderRegistry: TAlarmProviderRegistry;
+ alarmEngine: Pick<TAlarmEngine, "runAlarm">;
+};
+
+export type TAlarmQueueServiceFactory = ReturnType<typeof alarmQueueServiceFactory>;
+
+const ALARM_DISPATCH_CONCURRENCY = 5;
+
+export const alarmQueueServiceFactory = ({
+ cronJob,
+ queueService,
+ alarmDAL,
+ alarmProviderRegistry,
+ alarmEngine
+}: TAlarmQueueServiceFactoryDep) => {
+ const appCfg = getConfig();
+
+ const enqueueDueAlarms = async () => {
+ for (const resourceType of alarmProviderRegistry.resourceTypes()) {
+ // eslint-disable-next-line no-await-in-loop
+ const alarms = await alarmDAL.findEnabledByResourceType(resourceType);
+ // eslint-disable-next-line no-await-in-loop
+ await Promise.all(
+ alarms.map((alarm) =>
+ queueService.queue(
+ QueueName.AlarmDispatch,
+ QueueJobs.AlarmDispatch,
+ { alarmId: alarm.id },
+ {
+ jobId: `alarm-dispatch-${alarm.id}`,
+ removeOnComplete: true,
+ removeOnFail: { count: 5 },
+ attempts: 3,
+ backoff: { type: "exponential", delay: 5000 }
+ }
+ )
+ )
+ );
+ }
+ };
+
+ const init = () => {
+ queueService.start(
+ QueueName.AlarmDispatch,
+ async (job) => {
+ const { alarmId } = job.data;
+ const alarm = await alarmDAL.findById(alarmId);
+ if (!alarm || !alarm.enabled) return;
+ await alarmEngine.runAlarm(alarm);
+ },
+ { concurrency: ALARM_DISPATCH_CONCURRENCY }
+ );
+
+ cronJob.register({
+ name: CronJobName.DailyAlarmProcessing,
+ pattern: "0 0 * * *",
+ runHashTtlS: 60 * 60 * 24,
+ enabled: !appCfg.isSecondaryInstance,
+ handler: async () => {
+ logger.info("cron[daily-alarm-processing]: enqueueing due alarms");
+ await enqueueDueAlarms();
+ logger.info("cron[daily-alarm-processing]: enqueue complete");
+ }
+ });
+ };
+
+ return { init, enqueueDueAlarms };
+};
diff --git a/backend/src/services/alarm/alarm-recipient-dal.ts b/backend/src/services/alarm/alarm-recipient-dal.ts
new file mode 100644
index 0000000000..433e53b152
--- /dev/null
+++ b/backend/src/services/alarm/alarm-recipient-dal.ts
@@ -0,0 +1,49 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName, TAlarmRecipients, TAlarmRecipientsInsert } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify, selectAllTableCols } from "@app/lib/knex";
+
+export type TAlarmRecipientDALFactory = ReturnType<typeof alarmRecipientDALFactory>;
+
+export const alarmRecipientDALFactory = (db: TDbClient) => {
+ const alarmRecipientOrm = ormify(db, TableName.AlarmRecipient);
+
+ const insertMany = async (data: TAlarmRecipientsInsert[], tx?: Knex): Promise<TAlarmRecipients[]> => {
+ try {
+ if (!data.length) return [];
+ const res = await (tx || db)(TableName.AlarmRecipient).insert(data).returning("*");
+ return res as TAlarmRecipients[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "InsertMany" });
+ }
+ };
+
+ const findByAlarmId = async (alarmId: string, tx?: Knex): Promise<TAlarmRecipients[]> => {
+ try {
+ const recipients = await (tx || db.replicaNode())(TableName.AlarmRecipient)
+ .where(`${TableName.AlarmRecipient}.alarmId`, alarmId)
+ .select(selectAllTableCols(TableName.AlarmRecipient));
+
+ return recipients as TAlarmRecipients[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindByAlarmId" });
+ }
+ };
+
+ const deleteByAlarmId = async (alarmId: string, tx?: Knex): Promise<number> => {
+ try {
+ return await (tx || db)(TableName.AlarmRecipient).where(`${TableName.AlarmRecipient}.alarmId`, alarmId).del();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "DeleteByAlarmId" });
+ }
+ };
+
+ return {
+ ...alarmRecipientOrm,
+ insertMany,
+ findByAlarmId,
+ deleteByAlarmId
+ };
+};
diff --git a/backend/src/services/alarm/alarm-recipient-resolver.ts b/backend/src/services/alarm/alarm-recipient-resolver.ts
new file mode 100644
index 0000000000..263fb5a387
--- /dev/null
+++ b/backend/src/services/alarm/alarm-recipient-resolver.ts
@@ -0,0 +1,80 @@
+import { OrgMembershipRole, OrgMembershipStatus, TAlarmRecipients } from "@app/db/schemas";
+import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
+import { logger } from "@app/lib/logger";
+import { TOrgDALFactory } from "@app/services/org/org-dal";
+import { TUserDALFactory } from "@app/services/user/user-dal";
+
+import { TAlarmRecipient } from "./alarm-channel-types";
+import { AlarmPrincipalType } from "./alarm-types";
+
+type TAlarmRecipientResolverDep = {
+ userDAL: Pick<TUserDALFactory, "find">;
+ orgDAL: Pick<TOrgDALFactory, "findOrgMembersByRole">;
+ userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
+};
+
+export type TAlarmRecipientResolver = ReturnType<typeof alarmRecipientResolverFactory>;
+
+export const alarmRecipientResolverFactory = ({
+ userDAL,
+ orgDAL,
+ userGroupMembershipDAL
+}: TAlarmRecipientResolverDep) => {
+ const resolve = async (orgId: string, recipients: TAlarmRecipients[]): Promise<TAlarmRecipient[]> => {
+ const userIds = new Set<string>();
+ const rawEmails = new Set<string>();
+
+ for (const recipient of recipients) {
+ switch (recipient.principalType) {
+ case AlarmPrincipalType.USER:
+ userIds.add(recipient.principalId);
+ break;
+ case AlarmPrincipalType.ROLE: {
+ // eslint-disable-next-line no-await-in-loop
+ const members = await orgDAL.findOrgMembersByRole(orgId, recipient.principalId as OrgMembershipRole);
+ members
+ .filter((member) => member.status !== OrgMembershipStatus.Invited && member.user?.id)
+ .forEach((member) => userIds.add(member.user.id));
+ break;
+ }
+ case AlarmPrincipalType.GROUP: {
+ // eslint-disable-next-line no-await-in-loop
+ const memberships = await userGroupMembershipDAL.find({ groupId: recipient.principalId });
+ memberships.forEach((membership) => userIds.add(membership.userId));
+ break;
+ }
+ case AlarmPrincipalType.EMAIL:
+ rawEmails.add(recipient.principalId.toLowerCase());
+ break;
+ default:
+ logger.warn(`Unknown alarm recipient principal type '${recipient.principalType}'`);
+ }
+ }
+
+ const resolved: TAlarmRecipient[] = [];
+ const seenEmails = new Set<string>();
+
+ if (userIds.size > 0) {
+ const users = await userDAL.find({ $in: { id: [...userIds] } });
+ users
+ .filter((user) => Boolean(user.email))
+ .forEach((user) => {
+ const email = user.email as string;
+ seenEmails.add(email.toLowerCase());
+ resolved.push({ userId: user.id, email, firstName: user.firstName });
+ });
+ }
+
+ // Add raw-address recipients, skipping any that already resolved via a user (dedup by email).
+ rawEmails.forEach((email) => {
+ if (!seenEmails.has(email)) {
+ seenEmails.add(email);
+ resolved.push({ email });
+ }
+ });
+
+ return resolved;
+ };
+
+ return { resolve };
+};
diff --git a/backend/src/services/alarm/alarm-service-types.ts b/backend/src/services/alarm/alarm-service-types.ts
new file mode 100644
index 0000000000..4b7b42f39c
--- /dev/null
+++ b/backend/src/services/alarm/alarm-service-types.ts
@@ -0,0 +1,85 @@
+import { TGenericPermission } from "@app/lib/types";
+
+import { AlarmChannelType } from "./alarm-channel-types";
+import { AlarmPrincipalType, AlarmRunStatus } from "./alarm-types";
+
+export type TAlarmRecipientInput = {
+ principalType: AlarmPrincipalType;
+ principalId: string;
+};
+
+export type TAlarmChannelInput = {
+ channelType: AlarmChannelType;
+ config: unknown;
+ enabled?: boolean;
+};
+
+export type TCreateAlarmDTO = TGenericPermission & {
+ name: string;
+ description?: string | null;
+ resourceType: string;
+ resourceId?: string | null;
+ eventType: string;
+ condition?: unknown;
+ filters?: unknown;
+ enabled?: boolean;
+ projectId?: string | null;
+ recipients: TAlarmRecipientInput[];
+ channels: TAlarmChannelInput[];
+};
+
+export type TUpdateAlarmDTO = TGenericPermission & {
+ alarmId: string;
+ name?: string;
+ description?: string | null;
+ condition?: unknown;
+ filters?: unknown;
+ enabled?: boolean;
+ recipients?: TAlarmRecipientInput[];
+ channels?: TAlarmChannelInput[];
+};
+
+export type TGetAlarmDTO = TGenericPermission & { alarmId: string };
+
+export type TDeleteAlarmDTO = TGenericPermission & { alarmId: string };
+
+export type TListAlarmsDTO = TGenericPermission & {
+ resourceType: string;
+ resourceId?: string | null;
+ projectId?: string | null;
+ enabled?: boolean;
+};
+
+// Channel config in responses has endpoint secrets redacted (webhook signing secret -> a boolean).
+export type TAlarmChannelResponse = {
+ id: string;
+ channelType: string;
+ config: Record<string, unknown>;
+ enabled: boolean;
+ createdAt: Date;
+ updatedAt: Date;
+};
+
+export type TAlarmRecipientResponse = {
+ principalType: string;
+ principalId: string;
+};
+
+export type TAlarmResponse = {
+ id: string;
+ name: string;
+ description: string | null;
+ resourceType: string;
+ resourceId: string | null;
+ eventType: string;
+ condition: unknown;
+ filters: unknown;
+ enabled: boolean;
+ orgId: string;
+ projectId: string | null;
+ recipients: TAlarmRecipientResponse[];
+ channels: TAlarmChannelResponse[];
+ lastRun: { timestamp: Date; status: AlarmRunStatus; error: string | null } | null;
+ createdAt: Date;
+ updatedAt: Date;
+};
diff --git a/backend/src/services/alarm/alarm-service.test.ts b/backend/src/services/alarm/alarm-service.test.ts
new file mode 100644
index 0000000000..54c7291dcb
--- /dev/null
+++ b/backend/src/services/alarm/alarm-service.test.ts
@@ -0,0 +1,210 @@
+import { z } from "zod";
+
+import { AlarmChannelType, TAlarmPayload } from "./alarm-channel-types";
+import { alarmProviderRegistryFactory } from "./alarm-provider-registry";
+import { alarmServiceFactory, TAlarmServiceFactoryDep } from "./alarm-service";
+import { AlarmPrincipalType, IResourceAlarmProvider, TAlarmPermissionInput } from "./alarm-types";
+
+const RESOURCE_TYPE = "test.resource";
+
+// Identity cipher: encryptedConfig is just JSON bytes of the config.
+const kmsServiceMock = {
+ createCipherPairWithDataKey: async () => ({
+ encryptor: ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: plainText }),
+ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob
+ })
+};
+const encConfig = (config: unknown) => Buffer.from(JSON.stringify(config));
+
+const buildService = (opts?: {
+ assertPermission?: (input: TAlarmPermissionInput) => Promise<void>;
+ resourceScopeThrows?: boolean;
+}) => {
+ const permissionCalls: TAlarmPermissionInput[] = [];
+ const provider: IResourceAlarmProvider = {
+ resourceType: RESOURCE_TYPE,
+ eventTypes: ["test.resource.expiration"],
+ conditionSchema: z.object({ alertBefore: z.string() }),
+ findDueTargets: async () => [],
+ buildPayload: () => ({}) as TAlarmPayload,
+ targetId: () => "t",
+ assertPermission: async (input) => {
+ permissionCalls.push(input);
+ if (opts?.assertPermission) await opts.assertPermission(input);
+ },
+ assertResourceInScope: async (input) => {
+ // Mirror the real contract: no-op when there is no resource to bind-check.
+ if (input.resourceId && opts?.resourceScopeThrows) throw new Error("resource out of scope");
+ }
+ };
+ const registry = alarmProviderRegistryFactory();
+ registry.register(provider);
+
+ const alarms = new Map<string, Record<string, unknown>>();
+ const channels = new Map<string, Array<Record<string, unknown>>>();
+ const recipients = new Map<string, Array<Record<string, unknown>>>();
+
+ const service = alarmServiceFactory({
+ alarmDAL: {
+ transaction: async (cb: (tx: unknown) => unknown) => cb({}),
+ create: async (data: Record<string, unknown>) => {
+ const row = {
+ id: "alarm-1",
+ ...data,
+ condition: data.condition ? (JSON.parse(data.condition as string) as unknown) : null,
+ filters: data.filters ? (JSON.parse(data.filters as string) as unknown) : null,
+ createdAt: new Date(),
+ updatedAt: new Date()
+ };
+ alarms.set(row.id, row);
+ return row;
+ },
+ findById: async (id: string) => alarms.get(id),
+ find: async () => [...alarms.values()],
+ updateById: async (id: string, data: Record<string, unknown>) => {
+ alarms.set(id, { ...alarms.get(id), ...data });
+ return alarms.get(id);
+ },
+ deleteById: async (id: string) => alarms.delete(id)
+ },
+ alarmChannelDAL: {
+ insertMany: async (data: Array<Record<string, unknown>>) => {
+ const withMeta = data.map((c, i) => ({ id: `c${i}`, createdAt: new Date(), updatedAt: new Date(), ...c }));
+ channels.set(data[0].alarmId as string, [...(channels.get(data[0].alarmId as string) ?? []), ...withMeta]);
+ return withMeta;
+ },
+ findByAlarmId: async (alarmId: string) => channels.get(alarmId) ?? [],
+ deleteByAlarmId: async (alarmId: string) => {
+ channels.delete(alarmId);
+ return 0;
+ }
+ },
+ alarmRecipientDAL: {
+ insertMany: async (data: Array<Record<string, unknown>>) => {
+ recipients.set(data[0].alarmId as string, data);
+ return data;
+ },
+ findByAlarmId: async (alarmId: string) => recipients.get(alarmId) ?? [],
+ deleteByAlarmId: async (alarmId: string) => {
+ recipients.delete(alarmId);
+ return 0;
+ }
+ },
+ alarmHistoryDAL: { findLatestByAlarmId: async () => undefined },
+ alarmProviderRegistry: registry,
+ kmsService: kmsServiceMock
+ } as unknown as TAlarmServiceFactoryDep);
+
+ return { service, permissionCalls, alarms, channels };
+};
+
+const actor = {
+ actor: "user" as never,
+ actorId: "user-1",
+ actorAuthMethod: null as never,
+ actorOrgId: "org-1"
+};
+
+const validCreate = {
+ name: "test-alarm",
+ resourceType: RESOURCE_TYPE,
+ eventType: "test.resource.expiration",
+ condition: { alertBefore: "30d" },
+ recipients: [{ principalType: AlarmPrincipalType.USER, principalId: "user-1" }],
+ channels: [
+ { channelType: AlarmChannelType.EMAIL, config: {} },
+ { channelType: AlarmChannelType.IN_APP, config: {} }
+ ],
+ ...actor
+};
+
+describe("alarm service", () => {
+ test("creates an alarm, persists channels + recipients, and checks Create permission", async () => {
+ const { service, permissionCalls } = buildService();
+ const alarm = await service.createAlarm(validCreate);
+
+ expect(alarm.id).toBe("alarm-1");
+ expect(alarm.orgId).toBe("org-1");
+ expect(alarm.channels).toHaveLength(2);
+ expect(alarm.recipients).toEqual([{ principalType: "user", principalId: "user-1" }]);
+ expect(permissionCalls[0].action).toBe("create");
+ expect(permissionCalls[0].orgId).toBe("org-1");
+ });
+
+ test("rejects an unknown resource type", async () => {
+ const { service } = buildService();
+ await expect(service.createAlarm({ ...validCreate, resourceType: "nope.unknown" })).rejects.toThrow();
+ });
+
+ test("runs the provider resource-scope check when resourceId is set", async () => {
+ const { service } = buildService({ resourceScopeThrows: true });
+ await expect(service.createAlarm({ ...validCreate, resourceId: "foreign-resource" })).rejects.toThrow(
+ "resource out of scope"
+ );
+ });
+
+ test("skips the resource-scope check for a filter-based alarm (no resourceId)", async () => {
+ const { service } = buildService({ resourceScopeThrows: true });
+ // No resourceId, so the scope check must not run and creation succeeds.
+ await expect(service.createAlarm(validCreate)).resolves.toBeDefined();
+ });
+
+ test("rejects a condition that fails the provider schema", async () => {
+ const { service } = buildService();
+ await expect(service.createAlarm({ ...validCreate, condition: { wrong: 1 } })).rejects.toThrow();
+ });
+
+ test("rejects an event type the provider does not support", async () => {
+ const { service } = buildService();
+ await expect(service.createAlarm({ ...validCreate, eventType: "test.resource.renewal" })).rejects.toThrow();
+ });
+
+ test("propagates a permission denial from the provider", async () => {
+ const { service } = buildService({
+ assertPermission: async () => {
+ throw new Error("forbidden");
+ }
+ });
+ await expect(service.createAlarm(validCreate)).rejects.toThrow("forbidden");
+ });
+
+ test("redacts the webhook signing secret on read", async () => {
+ const { service, alarms, channels } = buildService();
+ alarms.set("alarm-1", {
+ id: "alarm-1",
+ name: "wh",
+ resourceType: RESOURCE_TYPE,
+ resourceId: null,
+ eventType: "test.resource.expiration",
+ condition: null,
+ filters: null,
+ enabled: true,
+ orgId: "org-1",
+ projectId: null,
+ createdAt: new Date(),
+ updatedAt: new Date()
+ });
+ channels.set("alarm-1", [
+ {
+ id: "c0",
+ channelType: AlarmChannelType.WEBHOOK,
+ encryptedConfig: encConfig({ url: "https://example.com/hook", signingSecret: "s3cr3t" }),
+ enabled: true,
+ createdAt: new Date(),
+ updatedAt: new Date()
+ }
+ ]);
+
+ const alarm = await service.getAlarmById({ alarmId: "alarm-1", ...actor });
+ expect(alarm.channels[0].config).toEqual({ url: "https://example.com/hook", hasSigningSecret: true });
+ expect(alarm.channels[0].config).not.toHaveProperty("signingSecret");
+ });
+
+ test("deletes an alarm after checking Delete permission", async () => {
+ const { service, permissionCalls } = buildService();
+ await service.createAlarm(validCreate);
+ const result = await service.deleteAlarm({ alarmId: "alarm-1", ...actor });
+ expect(result.id).toBe("alarm-1");
+ expect(permissionCalls.some((c) => c.action === "delete")).toBe(true);
+ });
+});
diff --git a/backend/src/services/alarm/alarm-service.ts b/backend/src/services/alarm/alarm-service.ts
new file mode 100644
index 0000000000..b4590fddba
--- /dev/null
+++ b/backend/src/services/alarm/alarm-service.ts
@@ -0,0 +1,400 @@
+import { z } from "zod";
+
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+
+import { decryptChannelConfig, encryptChannelConfig, getAlarmChannelCipher } from "./alarm-channel-crypto-fns";
+import { TAlarmChannelDALFactory } from "./alarm-channel-dal";
+import { AlarmChannelType, TWebhookChannelConfig } from "./alarm-channel-types";
+import { TAlarmDALFactory } from "./alarm-dal";
+import { TAlarmHistoryDALFactory } from "./alarm-history-dal";
+import { TAlarmProviderRegistry } from "./alarm-provider-registry";
+import { TAlarmRecipientDALFactory } from "./alarm-recipient-dal";
+import {
+ TAlarmChannelInput,
+ TAlarmChannelResponse,
+ TAlarmResponse,
+ TCreateAlarmDTO,
+ TDeleteAlarmDTO,
+ TGetAlarmDTO,
+ TListAlarmsDTO,
+ TUpdateAlarmDTO
+} from "./alarm-service-types";
+import { AlarmPermissionAction, AlarmPrincipalType, AlarmRunStatus, IResourceAlarmProvider } from "./alarm-types";
+import { ALARM_CHANNEL_REGISTRY } from "./channels/alarm-channel-registry";
+import { validateSlackWebhookUrl } from "./channels/alarm-channel-slack-fns";
+
+export type TAlarmServiceFactoryDep = {
+ alarmDAL: TAlarmDALFactory;
+ alarmChannelDAL: Pick<TAlarmChannelDALFactory, "insertMany" | "findByAlarmId" | "deleteByAlarmId">;
+ alarmRecipientDAL: Pick<TAlarmRecipientDALFactory, "insertMany" | "findByAlarmId" | "deleteByAlarmId">;
+ alarmHistoryDAL: Pick<TAlarmHistoryDALFactory, "findLatestByAlarmId">;
+ alarmProviderRegistry: TAlarmProviderRegistry;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+};
+
+export type TAlarmServiceFactory = ReturnType<typeof alarmServiceFactory>;
+
+const isValidPrincipalType = (value: string): value is AlarmPrincipalType =>
+ Object.values(AlarmPrincipalType).includes(value as AlarmPrincipalType);
+
+export const alarmServiceFactory = ({
+ alarmDAL,
+ alarmChannelDAL,
+ alarmRecipientDAL,
+ alarmHistoryDAL,
+ alarmProviderRegistry,
+ kmsService
+}: TAlarmServiceFactoryDep) => {
+ const $getProvider = (resourceType: string): IResourceAlarmProvider => {
+ const provider = alarmProviderRegistry.get(resourceType);
+ if (!provider) {
+ throw new BadRequestError({ message: `No alarm provider is registered for resource type '${resourceType}'` });
+ }
+ return provider;
+ };
+
+ const $validate = (
+ provider: IResourceAlarmProvider,
+ input: {
+ eventType?: string;
+ condition?: unknown;
+ channels?: TAlarmChannelInput[];
+ recipients?: { principalType: string }[];
+ }
+ ) => {
+ if (input.eventType && !provider.eventTypes.includes(input.eventType)) {
+ throw new BadRequestError({
+ message: `Event type '${input.eventType}' is not supported by resource type '${provider.resourceType}'`
+ });
+ }
+
+ if (input.condition !== undefined) {
+ try {
+ provider.conditionSchema.parse(input.condition);
+ } catch (err) {
+ const message = err instanceof z.ZodError ? err.issues.map((i) => i.message).join(", ") : "Invalid condition";
+ throw new BadRequestError({ message: `Invalid alarm condition: ${message}` });
+ }
+ }
+
+ (input.recipients ?? []).forEach((recipient) => {
+ if (!isValidPrincipalType(recipient.principalType)) {
+ throw new BadRequestError({ message: `Invalid recipient principal type '${recipient.principalType}'` });
+ }
+ });
+
+ if (input.channels) {
+ if (input.channels.length === 0) {
+ throw new BadRequestError({ message: "At least one channel is required" });
+ }
+
+ const hasDirected = input.channels.some((channel) => ALARM_CHANNEL_REGISTRY[channel.channelType]?.directed);
+ if (hasDirected && (input.recipients ?? []).length === 0) {
+ throw new BadRequestError({ message: "At least one recipient is required for in-app or email channels" });
+ }
+
+ for (const channel of input.channels) {
+ const definition = ALARM_CHANNEL_REGISTRY[channel.channelType];
+ if (!definition) throw new BadRequestError({ message: `Unknown channel type '${channel.channelType}'` });
+
+ try {
+ definition.configSchema.parse(channel.config);
+ } catch (err) {
+ const message =
+ err instanceof z.ZodError ? err.issues.map((i) => i.message).join(", ") : "Invalid channel config";
+ throw new BadRequestError({ message: `Invalid ${channel.channelType} channel config: ${message}` });
+ }
+
+ if (channel.channelType === AlarmChannelType.SLACK) {
+ validateSlackWebhookUrl((channel.config as { webhookUrl: string }).webhookUrl);
+ }
+ }
+ }
+ };
+
+ const $formatResponse = async (alarmId: string): Promise<TAlarmResponse> => {
+ const alarm = await alarmDAL.findById(alarmId);
+ if (!alarm) throw new NotFoundError({ message: `Alarm with ID '${alarmId}' not found` });
+
+ const [channels, recipients, lastRun] = await Promise.all([
+ alarmChannelDAL.findByAlarmId(alarmId),
+ alarmRecipientDAL.findByAlarmId(alarmId),
+ alarmHistoryDAL.findLatestByAlarmId(alarmId)
+ ]);
+
+ const { decryptor } = await getAlarmChannelCipher(kmsService, {
+ orgId: alarm.orgId,
+ projectId: alarm.projectId
+ });
+
+ const channelResponses: TAlarmChannelResponse[] = channels.map((channel) => {
+ const config = decryptChannelConfig<Record<string, unknown>>(channel.encryptedConfig, decryptor);
+ const responseConfig =
+ channel.channelType === AlarmChannelType.WEBHOOK
+ ? {
+ url: (config as TWebhookChannelConfig).url,
+ hasSigningSecret: Boolean((config as TWebhookChannelConfig).signingSecret)
+ }
+ : config;
+
+ return {
+ id: channel.id,
+ channelType: channel.channelType,
+ config: responseConfig,
+ enabled: channel.enabled,
+ createdAt: channel.createdAt,
+ updatedAt: channel.updatedAt
+ };
+ });
+
+ return {
+ id: alarm.id,
+ name: alarm.name,
+ description: alarm.description ?? null,
+ resourceType: alarm.resourceType,
+ resourceId: alarm.resourceId ?? null,
+ eventType: alarm.eventType,
+ condition: alarm.condition ?? null,
+ filters: alarm.filters ?? null,
+ enabled: alarm.enabled,
+ orgId: alarm.orgId,
+ projectId: alarm.projectId ?? null,
+ recipients: recipients.map((recipient) => ({
+ principalType: recipient.principalType,
+ principalId: recipient.principalId
+ })),
+ channels: channelResponses,
+ lastRun: lastRun
+ ? {
+ timestamp: lastRun.triggeredAt ?? lastRun.createdAt,
+ status: lastRun.status as AlarmRunStatus,
+ error: lastRun.error ?? null
+ }
+ : null,
+ createdAt: alarm.createdAt,
+ updatedAt: alarm.updatedAt
+ };
+ };
+
+ const createAlarm = async (dto: TCreateAlarmDTO): Promise<TAlarmResponse> => {
+ const provider = $getProvider(dto.resourceType);
+ $validate(provider, dto);
+
+ await provider.assertPermission({
+ action: AlarmPermissionAction.Create,
+ orgId: dto.actorOrgId,
+ projectId: dto.projectId,
+ resourceId: dto.resourceId,
+ actor: {
+ actor: dto.actor,
+ actorId: dto.actorId,
+ actorAuthMethod: dto.actorAuthMethod,
+ actorOrgId: dto.actorOrgId
+ }
+ });
+
+ await provider.assertResourceInScope({
+ orgId: dto.actorOrgId,
+ projectId: dto.projectId,
+ resourceId: dto.resourceId
+ });
+
+ const { encryptor } = await getAlarmChannelCipher(kmsService, {
+ orgId: dto.actorOrgId,
+ projectId: dto.projectId
+ });
+
+ const alarm = await alarmDAL.transaction(async (tx) => {
+ const created = await alarmDAL.create(
+ {
+ name: dto.name,
+ description: dto.description,
+ resourceType: dto.resourceType,
+ resourceId: dto.resourceId,
+ eventType: dto.eventType,
+ condition: dto.condition != null ? JSON.stringify(dto.condition) : null,
+ filters: dto.filters != null ? JSON.stringify(dto.filters) : null,
+ enabled: dto.enabled ?? true,
+ orgId: dto.actorOrgId,
+ projectId: dto.projectId,
+ createdByUserId: dto.actorId
+ },
+ tx
+ );
+
+ await alarmChannelDAL.insertMany(
+ dto.channels.map((channel) => ({
+ alarmId: created.id,
+ channelType: channel.channelType,
+ encryptedConfig: encryptChannelConfig(channel.config, encryptor),
+ enabled: channel.enabled ?? true
+ })),
+ tx
+ );
+
+ await alarmRecipientDAL.insertMany(
+ dto.recipients.map((recipient) => ({
+ alarmId: created.id,
+ principalType: recipient.principalType,
+ principalId: recipient.principalId
+ })),
+ tx
+ );
+
+ return created;
+ });
+
+ return $formatResponse(alarm.id);
+ };
+
+ const getAlarmById = async (dto: TGetAlarmDTO): Promise<TAlarmResponse> => {
+ const alarm = await alarmDAL.findById(dto.alarmId);
+ if (!alarm) throw new NotFoundError({ message: `Alarm with ID '${dto.alarmId}' not found` });
+
+ const provider = $getProvider(alarm.resourceType);
+ await provider.assertPermission({
+ action: AlarmPermissionAction.Read,
+ orgId: alarm.orgId,
+ projectId: alarm.projectId,
+ resourceId: alarm.resourceId,
+ actor: {
+ actor: dto.actor,
+ actorId: dto.actorId,
+ actorAuthMethod: dto.actorAuthMethod,
+ actorOrgId: dto.actorOrgId
+ }
+ });
+
+ return $formatResponse(alarm.id);
+ };
+
+ const listAlarms = async (dto: TListAlarmsDTO): Promise<TAlarmResponse[]> => {
+ const provider = $getProvider(dto.resourceType);
+ await provider.assertPermission({
+ action: AlarmPermissionAction.Read,
+ orgId: dto.actorOrgId,
+ projectId: dto.projectId,
+ resourceId: dto.resourceId,
+ actor: {
+ actor: dto.actor,
+ actorId: dto.actorId,
+ actorAuthMethod: dto.actorAuthMethod,
+ actorOrgId: dto.actorOrgId
+ }
+ });
+
+ const alarms = await alarmDAL.find({
+ orgId: dto.actorOrgId,
+ resourceType: dto.resourceType,
+ ...(dto.resourceId !== undefined ? { resourceId: dto.resourceId } : {}),
+ ...(dto.projectId !== undefined ? { projectId: dto.projectId } : {}),
+ ...(dto.enabled !== undefined ? { enabled: dto.enabled } : {})
+ });
+
+ return Promise.all(alarms.map((alarm) => $formatResponse(alarm.id)));
+ };
+
+ const updateAlarm = async (dto: TUpdateAlarmDTO): Promise<TAlarmResponse> => {
+ const alarm = await alarmDAL.findById(dto.alarmId);
+ if (!alarm) throw new NotFoundError({ message: `Alarm with ID '${dto.alarmId}' not found` });
+
+ const provider = $getProvider(alarm.resourceType);
+ $validate(provider, {
+ condition: dto.condition,
+ channels: dto.channels,
+ recipients: dto.recipients ?? (dto.channels ? [] : undefined)
+ });
+
+ await provider.assertPermission({
+ action: AlarmPermissionAction.Edit,
+ orgId: alarm.orgId,
+ projectId: alarm.projectId,
+ resourceId: alarm.resourceId,
+ actor: {
+ actor: dto.actor,
+ actorId: dto.actorId,
+ actorAuthMethod: dto.actorAuthMethod,
+ actorOrgId: dto.actorOrgId
+ }
+ });
+
+ const { encryptor } = await getAlarmChannelCipher(kmsService, {
+ orgId: alarm.orgId,
+ projectId: alarm.projectId
+ });
+
+ await alarmDAL.transaction(async (tx) => {
+ await alarmDAL.updateById(
+ alarm.id,
+ {
+ ...(dto.name !== undefined ? { name: dto.name } : {}),
+ ...(dto.description !== undefined ? { description: dto.description } : {}),
+ ...(dto.condition !== undefined
+ ? { condition: dto.condition != null ? JSON.stringify(dto.condition) : null }
+ : {}),
+ ...(dto.filters !== undefined ? { filters: dto.filters != null ? JSON.stringify(dto.filters) : null } : {}),
+ ...(dto.enabled !== undefined ? { enabled: dto.enabled } : {})
+ },
+ tx
+ );
+
+ if (dto.channels) {
+ await alarmChannelDAL.deleteByAlarmId(alarm.id, tx);
+ await alarmChannelDAL.insertMany(
+ dto.channels.map((channel) => ({
+ alarmId: alarm.id,
+ channelType: channel.channelType,
+ encryptedConfig: encryptChannelConfig(channel.config, encryptor),
+ enabled: channel.enabled ?? true
+ })),
+ tx
+ );
+ }
+
+ if (dto.recipients) {
+ await alarmRecipientDAL.deleteByAlarmId(alarm.id, tx);
+ await alarmRecipientDAL.insertMany(
+ dto.recipients.map((recipient) => ({
+ alarmId: alarm.id,
+ principalType: recipient.principalType,
+ principalId: recipient.principalId
+ })),
+ tx
+ );
+ }
+ });
+
+ return $formatResponse(alarm.id);
+ };
+
+ const deleteAlarm = async (dto: TDeleteAlarmDTO): Promise<{ id: string }> => {
+ const alarm = await alarmDAL.findById(dto.alarmId);
+ if (!alarm) throw new NotFoundError({ message: `Alarm with ID '${dto.alarmId}' not found` });
+
+ const provider = $getProvider(alarm.resourceType);
+ await provider.assertPermission({
+ action: AlarmPermissionAction.Delete,
+ orgId: alarm.orgId,
+ projectId: alarm.projectId,
+ resourceId: alarm.resourceId,
+ actor: {
+ actor: dto.actor,
+ actorId: dto.actorId,
+ actorAuthMethod: dto.actorAuthMethod,
+ actorOrgId: dto.actorOrgId
+ }
+ });
+
+ await alarmDAL.deleteById(alarm.id);
+ return { id: alarm.id };
+ };
+
+ return {
+ createAlarm,
+ getAlarmById,
+ listAlarms,
+ updateAlarm,
+ deleteAlarm
+ };
+};
diff --git a/backend/src/services/alarm/alarm-types.ts b/backend/src/services/alarm/alarm-types.ts
new file mode 100644
index 0000000000..99a63d3185
--- /dev/null
+++ b/backend/src/services/alarm/alarm-types.ts
@@ -0,0 +1,90 @@
+import { Knex } from "knex";
+import { z } from "zod";
+
+import { TGenericPermission } from "@app/lib/types";
+
+import { TAlarmPayload } from "./alarm-channel-types";
+
+export enum AlarmPrincipalType {
+ USER = "user",
+ GROUP = "group",
+ ROLE = "role",
+ EMAIL = "email"
+}
+
+export enum AlarmRunStatus {
+ SUCCESS = "success",
+ FAILED = "failed"
+}
+
+export enum AlarmPermissionAction {
+ Read = "read",
+ Create = "create",
+ Edit = "edit",
+ Delete = "delete"
+}
+
+export type TAlarmPermissionInput = {
+ action: AlarmPermissionAction;
+ orgId: string;
+ projectId?: string | null;
+ resourceId?: string | null;
+ actor: TGenericPermission;
+};
+
+export const DEFAULT_DEDUP_WINDOW_HOURS = 24;
+
+export type TAlarmContext = {
+ id: string;
+ name: string;
+ orgId: string;
+ projectId?: string | null;
+ resourceType: string;
+ resourceId?: string | null;
+ eventType: string;
+ condition: unknown;
+ filters: unknown;
+};
+
+export type TFindDueTargetsInput = {
+ orgId: string;
+ projectId?: string | null;
+ resourceId?: string | null;
+ eventType: string;
+ condition: unknown;
+ filters: unknown;
+ tx?: Knex;
+};
+
+export interface IResourceAlarmProvider<TTarget = unknown> {
+ // Dot-namespaced, e.g. "pki.certificate", "identity.ua-secret".
+ resourceType: string;
+ // Event keys this provider understands, e.g. ["pki.certificate.expiration"].
+ eventTypes: string[];
+ // Validates an alarm's `condition` (the "when"), e.g. { alertBefore: "30d" }.
+ conditionSchema: z.ZodTypeAny;
+
+ // Resources currently due to alarm for this alarm's scope + condition. The engine handles dedup
+ // afterwards, so this returns all current matches in the window (not minus already-alarmed).
+ findDueTargets(input: TFindDueTargetsInput): Promise<TTarget[]>;
+
+ // One neutral payload describing all due targets for a firing (channels render it per medium).
+ buildPayload(alarm: TAlarmContext, targets: TTarget[]): TAlarmPayload;
+
+ // Stable id per target, used for dedup and history. Must be stable across cron runs.
+ targetId(target: TTarget): string;
+
+ // Optional per-condition dedup window override (hours). Defaults to DEFAULT_DEDUP_WINDOW_HOURS.
+ dedupWindowHours?(condition: unknown): number;
+
+ // Authorizes a CRUD action on an alarm of this resource type. Throws (e.g. ForbiddenError) if
+ // denied. The alarm module owns no CASL subject of its own: each provider reuses its resource's
+ // existing permissions (e.g. PKI reuses the `pki-alerts` subject, project- or application-scoped).
+ assertPermission(input: TAlarmPermissionInput): Promise<void>;
+
+ // Assert that a resource-bound alarm's resource belongs to the alarm's scope (org, and project
+ // when project-scoped). Called at create. Throws if the resource is out of scope, so an alarm
+ // cannot be bound to a foreign/out-of-scope resource. When there is no resourceId (a filter-based
+ // alarm), there is nothing to bind-check, so implementations return immediately.
+ assertResourceInScope(input: { orgId: string; projectId?: string | null; resourceId?: string | null }): Promise<void>;
+}
diff --git a/backend/src/services/alarm/channels/alarm-channel-email-fns.ts b/backend/src/services/alarm/channels/alarm-channel-email-fns.ts
new file mode 100644
index 0000000000..cd367f3a2a
--- /dev/null
+++ b/backend/src/services/alarm/channels/alarm-channel-email-fns.ts
@@ -0,0 +1,88 @@
+import { delay } from "@app/lib/delay";
+import { logger } from "@app/lib/logger";
+import { SmtpTemplates } from "@app/services/smtp/smtp-service";
+
+import { ALARM_CHANNEL_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "../alarm-channel-constants";
+import {
+ EmailChannelConfigSchema,
+ TAlarmChannelSendContext,
+ TAlarmPayload,
+ TChannelResult
+} from "../alarm-channel-types";
+
+const isEmailErrorRetryable = (err: Error): boolean => {
+ const msg = err.message.toLowerCase();
+ if (RETRYABLE_NETWORK_ERRORS.some((code) => msg.includes(code.toLowerCase()))) return true;
+ if (msg.includes("timeout") || msg.includes("connection")) return true;
+ if (["421", "450", "451", "452"].some((code) => msg.includes(code))) return true;
+ return false;
+};
+
+const buildSubstitutions = (payload: TAlarmPayload) => ({
+ alarmName: payload.alarm.name,
+ eventLabel: payload.eventLabel,
+ resourceKind: payload.resourceKind,
+ summary: payload.summary,
+ condition: payload.alarm.condition,
+ viewUrl: payload.alarm.viewUrl,
+ items: payload.items.map((item) => ({
+ title: item.title,
+ identifier: item.identifier,
+ fields: item.fields ?? []
+ }))
+});
+
+const sendEmail = async (
+ smtpService: TAlarmChannelSendContext["deps"]["smtpService"],
+ recipients: string[],
+ payload: TAlarmPayload
+): Promise<void> => {
+ await smtpService.sendMail({
+ recipients,
+ subjectLine: `Infisical ${payload.resourceKind} ${payload.eventLabel} Alert - ${payload.alarm.name}`,
+ substitutions: buildSubstitutions(payload),
+ template: SmtpTemplates.AlarmNotification
+ });
+};
+
+export const sendEmailNotification = async (ctx: TAlarmChannelSendContext): Promise<TChannelResult> => {
+ EmailChannelConfigSchema.parse(ctx.config);
+
+ if (!ctx.recipient?.email) {
+ return { success: false, error: "No recipient for email channel" };
+ }
+ const recipients = [ctx.recipient.email];
+
+ const { maxRetries, delayMs } = ALARM_CHANNEL_RETRY_CONFIG;
+ let lastError: Error | undefined;
+
+ for (let attempt = 1; attempt <= maxRetries; attempt += 1) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ await sendEmail(ctx.deps.smtpService, recipients, ctx.payload);
+ return { success: true };
+ } catch (err) {
+ lastError = err instanceof Error ? err : new Error(String(err));
+
+ if (!isEmailErrorRetryable(lastError)) {
+ logger.info(
+ { channelId: ctx.channelId, error: lastError.message },
+ `Alarm email error is not retryable (permanent SMTP error) [channelId=${ctx.channelId}]`
+ );
+ return { success: false, error: lastError.message };
+ }
+
+ logger.info(
+ { channelId: ctx.channelId, attempt, maxRetries, error: lastError.message },
+ `Alarm email failed, ${attempt < maxRetries ? `retrying in ${delayMs}ms` : "no more retries"} [channelId=${ctx.channelId}]`
+ );
+
+ if (attempt < maxRetries) {
+ // eslint-disable-next-line no-await-in-loop
+ await delay(delayMs);
+ }
+ }
+ }
+
+ return { success: false, error: lastError?.message };
+};
diff --git a/backend/src/services/alarm/channels/alarm-channel-inapp-fns.ts b/backend/src/services/alarm/channels/alarm-channel-inapp-fns.ts
new file mode 100644
index 0000000000..8f68a4a57a
--- /dev/null
+++ b/backend/src/services/alarm/channels/alarm-channel-inapp-fns.ts
@@ -0,0 +1,32 @@
+import { logger } from "@app/lib/logger";
+
+import { InAppChannelConfigSchema, TAlarmChannelSendContext, TChannelResult } from "../alarm-channel-types";
+
+export const sendInAppNotification = async (ctx: TAlarmChannelSendContext): Promise<TChannelResult> => {
+ InAppChannelConfigSchema.parse(ctx.config);
+
+ if (!ctx.recipient?.userId) {
+ return { success: true };
+ }
+ if (!ctx.payload.notificationType) {
+ return { success: false, error: "Missing notificationType for in-app channel" };
+ }
+
+ try {
+ await ctx.deps.notificationService.createUserNotifications([
+ {
+ userId: ctx.recipient.userId,
+ orgId: ctx.payload.alarm.orgId,
+ type: ctx.payload.notificationType,
+ title: `${ctx.payload.resourceKind} ${ctx.payload.eventLabel}: ${ctx.payload.alarm.name}`,
+ body: ctx.payload.summary,
+ link: ctx.payload.alarm.viewUrl
+ }
+ ]);
+ return { success: true };
+ } catch (err) {
+ const error = err instanceof Error ? err.message : "Unknown error";
+ logger.error(err, `Alarm in-app notification failed [channelId=${ctx.channelId}]`);
+ return { success: false, error };
+ }
+};
diff --git a/backend/src/services/alarm/channels/alarm-channel-pagerduty-fns.ts b/backend/src/services/alarm/channels/alarm-channel-pagerduty-fns.ts
new file mode 100644
index 0000000000..5978b7d180
--- /dev/null
+++ b/backend/src/services/alarm/channels/alarm-channel-pagerduty-fns.ts
@@ -0,0 +1,138 @@
+import { AxiosError } from "axios";
+
+import { delay } from "@app/lib/delay";
+import { logger } from "@app/lib/logger";
+import { safeRequest } from "@app/lib/validator";
+
+import { ALARM_CHANNEL_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "../alarm-channel-constants";
+import {
+ PagerDutyChannelConfigSchema,
+ pagerDutyIntegrationKeyRegex,
+ TAlarmChannelSendContext,
+ TAlarmPayload,
+ TChannelResult
+} from "../alarm-channel-types";
+
+const PAGERDUTY_EVENTS_URL = "https://events.pagerduty.com/v2/enqueue";
+const PAGERDUTY_TIMEOUT = 7 * 1000;
+const MAX_ITEMS_IN_PAYLOAD = 10;
+
+type TPagerDutyPayload = {
+ routing_key: string;
+ event_action: "trigger";
+ dedup_key: string;
+ payload: {
+ summary: string;
+ severity: "critical" | "error" | "warning" | "info";
+ source: string;
+ timestamp: string;
+ component: string;
+ group: string;
+ class: string;
+ custom_details: {
+ alarm_name: string;
+ condition?: string;
+ total_items: number;
+ items: Array<{ title: string; identifier?: string; fields: Record<string, string> }>;
+ view_url: string;
+ };
+ };
+ links: Array<{ href: string; text: string }>;
+};
+
+export const buildPagerDutyPayload = (payload: TAlarmPayload, integrationKey: string): TPagerDutyPayload => {
+ const displayItems = payload.items.slice(0, MAX_ITEMS_IN_PAYLOAD);
+
+ return {
+ routing_key: integrationKey,
+ event_action: "trigger",
+ dedup_key: payload.alarm.id,
+ payload: {
+ summary: payload.summary,
+ severity: payload.severity,
+ source: `infisical-${payload.alarm.resourceType}`,
+ timestamp: new Date().toISOString(),
+ component: payload.resourceKind,
+ group: payload.alarm.projectId ?? payload.alarm.orgId,
+ class: payload.eventKey,
+ custom_details: {
+ alarm_name: payload.alarm.name,
+ ...(payload.alarm.condition ? { condition: payload.alarm.condition } : {}),
+ total_items: payload.items.length,
+ items: displayItems.map((item) => ({
+ title: item.title || "N/A",
+ ...(item.identifier ? { identifier: item.identifier } : {}),
+ fields: Object.fromEntries((item.fields ?? []).map((field) => [field.label, field.value]))
+ })),
+ view_url: payload.alarm.viewUrl
+ }
+ },
+ links: [{ href: payload.alarm.viewUrl, text: "View in Infisical" }]
+ };
+};
+
+const isPagerDutyErrorRetryable = (err: AxiosError): boolean => {
+ const status = err.response?.status;
+ if (status === 400) return false;
+ if (status === 429) return true;
+ if (status && status >= 500) return true;
+ if (err.code && RETRYABLE_NETWORK_ERRORS.includes(err.code)) return true;
+ if (err.message?.toLowerCase().includes("timeout")) return true;
+ return false;
+};
+
+const triggerPagerDutyEvent = async (payload: TPagerDutyPayload): Promise<void> => {
+ await safeRequest.post(PAGERDUTY_EVENTS_URL, payload, {
+ headers: { "Content-Type": "application/json" },
+ timeout: PAGERDUTY_TIMEOUT,
+ signal: AbortSignal.timeout(PAGERDUTY_TIMEOUT)
+ });
+};
+
+export const sendPagerDutyNotification = async (ctx: TAlarmChannelSendContext): Promise<TChannelResult> => {
+ const config = PagerDutyChannelConfigSchema.parse(ctx.config);
+
+ if (!pagerDutyIntegrationKeyRegex.test(config.integrationKey)) {
+ return { success: false, error: "Invalid PagerDuty integration key" };
+ }
+
+ const payload = buildPagerDutyPayload(ctx.payload, config.integrationKey);
+ const { maxRetries, delayMs } = ALARM_CHANNEL_RETRY_CONFIG;
+ let lastError: AxiosError | undefined;
+
+ for (let attempt = 1; attempt <= maxRetries; attempt += 1) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ await triggerPagerDutyEvent(payload);
+ return { success: true };
+ } catch (err) {
+ lastError = err as AxiosError;
+
+ if (!isPagerDutyErrorRetryable(lastError)) {
+ logger.info(
+ { channelId: ctx.channelId, statusCode: lastError.response?.status, error: lastError.message },
+ `Alarm PagerDuty error is not retryable (4xx or non-transient) [channelId=${ctx.channelId}]`
+ );
+ return { success: false, error: lastError.message };
+ }
+
+ logger.info(
+ {
+ channelId: ctx.channelId,
+ attempt,
+ maxRetries,
+ statusCode: lastError.response?.status,
+ error: lastError.message
+ },
+ `Alarm PagerDuty failed, ${attempt < maxRetries ? `retrying in ${delayMs}ms` : "no more retries"} [channelId=${ctx.channelId}]`
+ );
+
+ if (attempt < maxRetries) {
+ // eslint-disable-next-line no-await-in-loop
+ await delay(delayMs);
+ }
+ }
+ }
+
+ return { success: false, error: lastError?.message };
+};
diff --git a/backend/src/services/alarm/channels/alarm-channel-registry.ts b/backend/src/services/alarm/channels/alarm-channel-registry.ts
new file mode 100644
index 0000000000..8ce16bcff3
--- /dev/null
+++ b/backend/src/services/alarm/channels/alarm-channel-registry.ts
@@ -0,0 +1,50 @@
+import {
+ AlarmChannelType,
+ EmailChannelConfigSchema,
+ InAppChannelConfigSchema,
+ PagerDutyChannelConfigSchema,
+ SlackChannelConfigSchema,
+ TAlarmChannelDefinition,
+ WebhookChannelConfigSchema
+} from "../alarm-channel-types";
+import { sendEmailNotification } from "./alarm-channel-email-fns";
+import { sendInAppNotification } from "./alarm-channel-inapp-fns";
+import { sendPagerDutyNotification } from "./alarm-channel-pagerduty-fns";
+import { sendSlackNotification } from "./alarm-channel-slack-fns";
+import { sendWebhookNotification } from "./alarm-channel-webhook-fns";
+
+export const ALARM_CHANNEL_REGISTRY: Record<AlarmChannelType, TAlarmChannelDefinition> = {
+ [AlarmChannelType.IN_APP]: {
+ type: AlarmChannelType.IN_APP,
+ directed: true,
+ configSchema: InAppChannelConfigSchema,
+ send: sendInAppNotification
+ },
+ [AlarmChannelType.EMAIL]: {
+ type: AlarmChannelType.EMAIL,
+ directed: true,
+ configSchema: EmailChannelConfigSchema,
+ send: sendEmailNotification
+ },
+ [AlarmChannelType.SLACK]: {
+ type: AlarmChannelType.SLACK,
+ directed: false,
+ configSchema: SlackChannelConfigSchema,
+ send: sendSlackNotification
+ },
+ [AlarmChannelType.WEBHOOK]: {
+ type: AlarmChannelType.WEBHOOK,
+ directed: false,
+ configSchema: WebhookChannelConfigSchema,
+ send: sendWebhookNotification
+ },
+ [AlarmChannelType.PAGERDUTY]: {
+ type: AlarmChannelType.PAGERDUTY,
+ directed: false,
+ configSchema: PagerDutyChannelConfigSchema,
+ send: sendPagerDutyNotification
+ }
+};
+
+export const getAlarmChannelDefinition = (type: AlarmChannelType): TAlarmChannelDefinition =>
+ ALARM_CHANNEL_REGISTRY[type];
diff --git a/backend/src/services/alarm/channels/alarm-channel-slack-fns.ts b/backend/src/services/alarm/channels/alarm-channel-slack-fns.ts
new file mode 100644
index 0000000000..0920f0834e
--- /dev/null
+++ b/backend/src/services/alarm/channels/alarm-channel-slack-fns.ts
@@ -0,0 +1,183 @@
+import { AxiosError } from "axios";
+
+import { delay } from "@app/lib/delay";
+import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { safeRequest } from "@app/lib/validator";
+
+import { ALARM_CHANNEL_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "../alarm-channel-constants";
+import {
+ SlackChannelConfigSchema,
+ TAlarmChannelSendContext,
+ TAlarmPayload,
+ TAlarmSeverity,
+ TChannelResult
+} from "../alarm-channel-types";
+
+const SLACK_WEBHOOK_TIMEOUT = 7 * 1000;
+const MAX_ITEMS_DISPLAYED = 2;
+
+type TSlackBlock =
+ | { type: "header"; text: { type: "plain_text"; text: string; emoji?: boolean } }
+ | { type: "section"; text: { type: "mrkdwn"; text: string } }
+ | { type: "section"; fields: Array<{ type: "mrkdwn"; text: string }> }
+ | { type: "context"; elements: Array<{ type: "mrkdwn"; text: string }> }
+ | { type: "divider" }
+ | {
+ type: "actions";
+ elements: Array<{
+ type: "button";
+ text: { type: "plain_text"; text: string; emoji?: boolean };
+ url: string;
+ style?: "primary" | "danger";
+ }>;
+ };
+
+type TSlackPayload = {
+ text: string;
+ blocks: TSlackBlock[];
+ attachments?: Array<{ color: string; blocks: TSlackBlock[] }>;
+};
+
+const SEVERITY_COLOR: Record<TAlarmSeverity, string> = {
+ critical: "#da3633",
+ error: "#da3633",
+ warning: "#f0b429",
+ info: "#1f6feb"
+};
+
+export const validateSlackWebhookUrl = (url: string): void => {
+ const parsedUrl = new URL(url);
+
+ if (parsedUrl.protocol !== "https:") {
+ throw new BadRequestError({ message: "Slack webhook URL must use HTTPS" });
+ }
+
+ if (parsedUrl.hostname !== "hooks.slack.com") {
+ throw new BadRequestError({ message: "Invalid Slack webhook URL. Must be from hooks.slack.com" });
+ }
+};
+
+export const buildSlackPayload = (payload: TAlarmPayload): TSlackPayload => {
+ const totalItems = payload.items.length;
+ const displayItems = payload.items.slice(0, MAX_ITEMS_DISPLAYED);
+ const remainingCount = totalItems - displayItems.length;
+ const color = SEVERITY_COLOR[payload.severity];
+
+ const headerText = `${payload.resourceKind} ${payload.eventLabel} Alert: ${payload.alarm.name}`;
+
+ const itemBlocks: TSlackBlock[] = [];
+ displayItems.forEach((item, index) => {
+ const fields: Array<{ type: "mrkdwn"; text: string }> = [
+ { type: "mrkdwn", text: `*Name:*\n${item.title || "N/A"}` }
+ ];
+ if (item.identifier) fields.push({ type: "mrkdwn", text: `*Identifier:*\n\`${item.identifier}\`` });
+ (item.fields ?? []).forEach((field) => {
+ fields.push({ type: "mrkdwn", text: `*${field.label}:*\n${field.value}` });
+ });
+
+ itemBlocks.push({ type: "section", fields });
+ if (index < displayItems.length - 1) itemBlocks.push({ type: "divider" });
+ });
+
+ const alarmInfoFields: Array<{ type: "mrkdwn"; text: string }> = [
+ { type: "mrkdwn", text: `*Alarm:*\n${payload.alarm.name}` }
+ ];
+ if (payload.alarm.condition) {
+ alarmInfoFields.push({ type: "mrkdwn", text: `*Alert Before:*\n${payload.alarm.condition}` });
+ }
+
+ const attachmentBlocks: TSlackBlock[] = [
+ { type: "section", fields: alarmInfoFields },
+ { type: "divider" },
+ { type: "section", text: { type: "mrkdwn", text: payload.summary } },
+ ...itemBlocks
+ ];
+
+ if (remainingCount > 0) {
+ attachmentBlocks.push({
+ type: "context",
+ elements: [{ type: "mrkdwn", text: `_+${remainingCount} more..._` }]
+ });
+ }
+
+ attachmentBlocks.push({
+ type: "actions",
+ elements: [
+ {
+ type: "button",
+ text: { type: "plain_text", text: "View in Infisical", emoji: true },
+ url: payload.alarm.viewUrl,
+ style: "primary"
+ }
+ ]
+ });
+
+ return {
+ text: `${headerText} - ${payload.summary}`,
+ blocks: [{ type: "header", text: { type: "plain_text", text: headerText, emoji: true } }],
+ attachments: [{ color, blocks: attachmentBlocks }]
+ };
+};
+
+const isSlackErrorRetryable = (err: AxiosError): boolean => {
+ const status = err.response?.status;
+ if (status && status >= 500) return true;
+ if (err.code && RETRYABLE_NETWORK_ERRORS.includes(err.code)) return true;
+ if (err.message?.toLowerCase().includes("timeout")) return true;
+ return false;
+};
+
+const triggerSlackWebhook = async (url: string, payload: TSlackPayload): Promise<void> => {
+ await safeRequest.post(url, payload, {
+ headers: { "Content-Type": "application/json" },
+ timeout: SLACK_WEBHOOK_TIMEOUT,
+ signal: AbortSignal.timeout(SLACK_WEBHOOK_TIMEOUT)
+ });
+};
+
+export const sendSlackNotification = async (ctx: TAlarmChannelSendContext): Promise<TChannelResult> => {
+ const config = SlackChannelConfigSchema.parse(ctx.config);
+
+ validateSlackWebhookUrl(config.webhookUrl);
+
+ const payload = buildSlackPayload(ctx.payload);
+ const { maxRetries, delayMs } = ALARM_CHANNEL_RETRY_CONFIG;
+ let lastError: AxiosError | undefined;
+
+ for (let attempt = 1; attempt <= maxRetries; attempt += 1) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ await triggerSlackWebhook(config.webhookUrl, payload);
+ return { success: true };
+ } catch (err) {
+ lastError = err as AxiosError;
+
+ if (!isSlackErrorRetryable(lastError)) {
+ logger.info(
+ { channelId: ctx.channelId, statusCode: lastError.response?.status, error: lastError.message },
+ `Alarm Slack error is not retryable (4xx or non-transient) [channelId=${ctx.channelId}]`
+ );
+ return { success: false, error: lastError.message };
+ }
+
+ logger.info(
+ {
+ channelId: ctx.channelId,
+ attempt,
+ maxRetries,
+ statusCode: lastError.response?.status,
+ error: lastError.message
+ },
+ `Alarm Slack failed, ${attempt < maxRetries ? `retrying in ${delayMs}ms` : "no more retries"} [channelId=${ctx.channelId}]`
+ );
+
+ if (attempt < maxRetries) {
+ // eslint-disable-next-line no-await-in-loop
+ await delay(delayMs);
+ }
+ }
+ }
+
+ return { success: false, error: lastError?.message };
+};
diff --git a/backend/src/services/alarm/channels/alarm-channel-webhook-fns.ts b/backend/src/services/alarm/channels/alarm-channel-webhook-fns.ts
new file mode 100644
index 0000000000..7a02c92034
--- /dev/null
+++ b/backend/src/services/alarm/channels/alarm-channel-webhook-fns.ts
@@ -0,0 +1,134 @@
+import crypto from "node:crypto";
+
+import { AxiosError } from "axios";
+
+import { delay } from "@app/lib/delay";
+import { logger } from "@app/lib/logger";
+import { safeRequest } from "@app/lib/validator";
+
+import { ALARM_CHANNEL_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "../alarm-channel-constants";
+import {
+ TAlarmChannelSendContext,
+ TAlarmPayload,
+ TChannelResult,
+ WebhookChannelConfigSchema
+} from "../alarm-channel-types";
+
+const ALARM_WEBHOOK_TIMEOUT = 7 * 1000;
+
+type TAlarmWebhookPayload = {
+ specversion: "1.0";
+ type: string;
+ source: string;
+ id: string;
+ time: string;
+ datacontenttype: "application/json";
+ subject: string;
+ data: {
+ alarm: { id: string; name: string; resourceType: string; condition?: string };
+ items: TAlarmPayload["items"];
+ metadata: { totalItems: number; viewUrl: string };
+ };
+};
+
+const isWebhookErrorRetryable = (err: AxiosError): boolean => {
+ const status = err.response?.status;
+ if (status && status >= 500) return true;
+ if (err.code && RETRYABLE_NETWORK_ERRORS.includes(err.code)) return true;
+ if (err.message?.toLowerCase().includes("timeout")) return true;
+ return false;
+};
+
+export const buildWebhookPayload = (payload: TAlarmPayload): TAlarmWebhookPayload => ({
+ specversion: "1.0",
+ type: payload.webhookType,
+ source: payload.alarm.projectId
+ ? `/projects/${payload.alarm.projectId}/alarms/${payload.alarm.id}`
+ : `/alarms/${payload.alarm.id}`,
+ id: crypto.randomUUID(),
+ time: new Date().toISOString(),
+ datacontenttype: "application/json",
+ subject: payload.eventKey,
+ data: {
+ alarm: {
+ id: payload.alarm.id,
+ name: payload.alarm.name,
+ resourceType: payload.alarm.resourceType,
+ ...(payload.alarm.condition ? { condition: payload.alarm.condition } : {})
+ },
+ items: payload.items,
+ metadata: {
+ totalItems: payload.items.length,
+ viewUrl: payload.alarm.viewUrl
+ }
+ }
+});
+
+const generateHmacSignature = (data: string, secret: string): string =>
+ crypto.createHmac("sha256", secret).update(data).digest("hex");
+
+const triggerWebhook = async (params: {
+ url: string;
+ payload: TAlarmWebhookPayload;
+ signingSecret?: string | null;
+}): Promise<void> => {
+ const { url, payload, signingSecret } = params;
+ const headers: Record<string, string> = { "Content-Type": "application/json" };
+
+ if (signingSecret) {
+ const payloadString = JSON.stringify(payload);
+ const timestamp = Date.now();
+ const signature = generateHmacSignature(`${timestamp}.${payloadString}`, signingSecret);
+ headers["x-infisical-signature"] = `t=${timestamp},v1=${signature}`;
+ }
+
+ await safeRequest.post(url, payload, {
+ headers,
+ timeout: ALARM_WEBHOOK_TIMEOUT,
+ signal: AbortSignal.timeout(ALARM_WEBHOOK_TIMEOUT)
+ });
+};
+
+export const sendWebhookNotification = async (ctx: TAlarmChannelSendContext): Promise<TChannelResult> => {
+ const config = WebhookChannelConfigSchema.parse(ctx.config);
+
+ const payload = buildWebhookPayload(ctx.payload);
+ const { maxRetries, delayMs } = ALARM_CHANNEL_RETRY_CONFIG;
+ let lastError: AxiosError | undefined;
+
+ for (let attempt = 1; attempt <= maxRetries; attempt += 1) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ await triggerWebhook({ url: config.url, payload, signingSecret: config.signingSecret });
+ return { success: true };
+ } catch (err) {
+ lastError = err as AxiosError;
+
+ if (!isWebhookErrorRetryable(lastError)) {
+ logger.info(
+ { channelId: ctx.channelId, statusCode: lastError.response?.status, error: lastError.message },
+ `Alarm webhook error is not retryable (4xx or non-transient) [channelId=${ctx.channelId}]`
+ );
+ return { success: false, error: lastError.message };
+ }
+
+ logger.info(
+ {
+ channelId: ctx.channelId,
+ attempt,
+ maxRetries,
+ statusCode: lastError.response?.status,
+ error: lastError.message
+ },
+ `Alarm webhook failed, ${attempt < maxRetries ? `retrying in ${delayMs}ms` : "no more retries"} [channelId=${ctx.channelId}]`
+ );
+
+ if (attempt < maxRetries) {
+ // eslint-disable-next-line no-await-in-loop
+ await delay(delayMs);
+ }
+ }
+ }
+
+ return { success: false, error: lastError?.message };
+};
diff --git a/backend/src/services/alarm/channels/alarm-channels.test.ts b/backend/src/services/alarm/channels/alarm-channels.test.ts
new file mode 100644
index 0000000000..83ee164846
--- /dev/null
+++ b/backend/src/services/alarm/channels/alarm-channels.test.ts
@@ -0,0 +1,217 @@
+import { NotificationType } from "@app/services/notification/notification-types";
+
+import { AlarmChannelType, TAlarmPayload } from "../alarm-channel-types";
+import { sendEmailNotification } from "./alarm-channel-email-fns";
+import { sendInAppNotification } from "./alarm-channel-inapp-fns";
+import { buildPagerDutyPayload } from "./alarm-channel-pagerduty-fns";
+import { ALARM_CHANNEL_REGISTRY } from "./alarm-channel-registry";
+import { buildSlackPayload, validateSlackWebhookUrl } from "./alarm-channel-slack-fns";
+import { buildWebhookPayload } from "./alarm-channel-webhook-fns";
+
+const samplePayload = (): TAlarmPayload => ({
+ alarm: {
+ id: "alarm-1",
+ name: "prod-cert-expiry",
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceType: "pki.certificate",
+ condition: "30d",
+ viewUrl: "https://app.infisical.com/inventory"
+ },
+ eventKey: "pki.certificate.expiration",
+ eventLabel: "Expiration",
+ webhookType: "com.infisical.pki.certificate.expiration",
+ resourceKind: "Certificate",
+ severity: "warning",
+ summary: "2 certificates expiring within 30d",
+ notificationType: NotificationType.PKI_ALERT_CHANNEL_FAILED,
+ items: [
+ {
+ id: "cert-a",
+ title: "api.prod.example.com",
+ identifier: "4B:3E:2F:A1",
+ fields: [
+ { label: "Expires", value: "2025-11-12" },
+ { label: "Days Until Expiry", value: "7" }
+ ]
+ },
+ {
+ id: "cert-b",
+ title: "web.example.com",
+ identifier: "8A:7F:1C:E4",
+ fields: [{ label: "Expires", value: "2025-11-10" }]
+ }
+ ]
+});
+
+const baseCtx = () => ({
+ channelId: "chan-1",
+ payload: samplePayload(),
+ deps: {
+ smtpService: { sendMail: async () => undefined },
+ notificationService: { createUserNotifications: async () => undefined }
+ }
+});
+
+describe("alarm channel registry", () => {
+ test("exposes all five channels with correct directed flags", () => {
+ expect(ALARM_CHANNEL_REGISTRY[AlarmChannelType.IN_APP].directed).toBe(true);
+ expect(ALARM_CHANNEL_REGISTRY[AlarmChannelType.EMAIL].directed).toBe(true);
+ expect(ALARM_CHANNEL_REGISTRY[AlarmChannelType.SLACK].directed).toBe(false);
+ expect(ALARM_CHANNEL_REGISTRY[AlarmChannelType.WEBHOOK].directed).toBe(false);
+ expect(ALARM_CHANNEL_REGISTRY[AlarmChannelType.PAGERDUTY].directed).toBe(false);
+ });
+
+ test("each entry is keyed by its own type", () => {
+ Object.entries(ALARM_CHANNEL_REGISTRY).forEach(([key, def]) => {
+ expect(def.type).toBe(key);
+ });
+ });
+});
+
+describe("buildWebhookPayload", () => {
+ test("wraps the payload in a CloudEvents 1.0 envelope", () => {
+ const wh = buildWebhookPayload(samplePayload());
+ expect(wh.specversion).toBe("1.0");
+ expect(wh.type).toBe("com.infisical.pki.certificate.expiration");
+ expect(wh.subject).toBe("pki.certificate.expiration");
+ expect(wh.source).toBe("/projects/proj-1/alarms/alarm-1");
+ expect(wh.data.metadata.totalItems).toBe(2);
+ expect(wh.data.items).toHaveLength(2);
+ expect(wh.data.alarm.condition).toBe("30d");
+ });
+
+ test("uses an org-less source when there is no project", () => {
+ const payload = samplePayload();
+ payload.alarm.projectId = undefined;
+ expect(buildWebhookPayload(payload).source).toBe("/alarms/alarm-1");
+ });
+});
+
+describe("buildSlackPayload", () => {
+ test("builds a header, a colored attachment, and a view button", () => {
+ const slack = buildSlackPayload(samplePayload());
+ expect(slack.blocks[0].type).toBe("header");
+ expect(slack.attachments?.[0].color).toBe("#f0b429"); // warning
+ const hasButton = slack.attachments?.[0].blocks.some((b) => b.type === "actions");
+ expect(hasButton).toBe(true);
+ });
+
+ test("caps displayed items at 2 and adds a +more indicator", () => {
+ const payload = samplePayload();
+ payload.items.push({ id: "cert-c", title: "extra.example.com" });
+ const slack = buildSlackPayload(payload);
+ const contextBlock = slack.attachments?.[0].blocks.find((b) => b.type === "context");
+ expect(contextBlock).toBeDefined();
+ });
+});
+
+describe("buildPagerDutyPayload", () => {
+ test("uses the alarm id as dedup key and carries provider severity", () => {
+ const pd = buildPagerDutyPayload(samplePayload(), "a".repeat(32));
+ expect(pd.dedup_key).toBe("alarm-1");
+ expect(pd.routing_key).toBe("a".repeat(32));
+ expect(pd.payload.severity).toBe("warning");
+ expect(pd.payload.custom_details.total_items).toBe(2);
+ expect(pd.payload.custom_details.items[0].fields.Expires).toBe("2025-11-12");
+ });
+});
+
+describe("validateSlackWebhookUrl", () => {
+ test("rejects a lookalike host", () => {
+ expect(() => validateSlackWebhookUrl("https://hooks.slack.com.evil.com/x")).toThrow();
+ });
+
+ test("rejects non-https", () => {
+ expect(() => validateSlackWebhookUrl("http://hooks.slack.com/x")).toThrow();
+ });
+});
+
+describe("sendEmailNotification (directed)", () => {
+ test("delivers to the per-call recipient's address", async () => {
+ let sentTo: string[] | undefined;
+ const ctx = {
+ ...baseCtx(),
+ config: {},
+ recipient: { userId: "u1", email: "[email protected]" },
+ deps: {
+ ...baseCtx().deps,
+ smtpService: {
+ sendMail: async (opts: { recipients: string[] }) => {
+ sentTo = opts.recipients;
+ }
+ }
+ }
+ };
+ const result = await sendEmailNotification(ctx);
+ expect(result.success).toBe(true);
+ expect(sentTo).toEqual(["[email protected]"]);
+ });
+
+ test("delivers to a raw EMAIL-address recipient (no user id)", async () => {
+ let sentTo: string[] | undefined;
+ const ctx = {
+ ...baseCtx(),
+ config: {},
+ recipient: { email: "[email protected]" },
+ deps: {
+ ...baseCtx().deps,
+ smtpService: {
+ sendMail: async (opts: { recipients: string[] }) => {
+ sentTo = opts.recipients;
+ }
+ }
+ }
+ };
+ const result = await sendEmailNotification(ctx);
+ expect(result.success).toBe(true);
+ expect(sentTo).toEqual(["[email protected]"]);
+ });
+
+ test("fails when there is no recipient", async () => {
+ const result = await sendEmailNotification({ ...baseCtx(), config: {} });
+ expect(result.success).toBe(false);
+ });
+});
+
+describe("sendInAppNotification (directed)", () => {
+ test("creates a notification for the recipient", async () => {
+ let created: unknown[] | undefined;
+ const ctx = {
+ ...baseCtx(),
+ config: {},
+ recipient: { userId: "u1", email: "[email protected]" },
+ deps: {
+ ...baseCtx().deps,
+ notificationService: {
+ createUserNotifications: async (data: unknown[]) => {
+ created = data;
+ }
+ }
+ }
+ };
+ const result = await sendInAppNotification(ctx);
+ expect(result.success).toBe(true);
+ expect(created).toHaveLength(1);
+ });
+
+ test("skips (success no-op) a raw EMAIL-address recipient with no user id", async () => {
+ let created: unknown[] | undefined;
+ const ctx = {
+ ...baseCtx(),
+ config: {},
+ recipient: { email: "[email protected]" },
+ deps: {
+ ...baseCtx().deps,
+ notificationService: {
+ createUserNotifications: async (data: unknown[]) => {
+ created = data;
+ }
+ }
+ }
+ };
+ const result = await sendInAppNotification(ctx);
+ expect(result.success).toBe(true);
+ expect(created).toBeUndefined();
+ });
+});
diff --git a/backend/src/services/alarm/providers/identity-credential-alarm-dal.ts b/backend/src/services/alarm/providers/identity-credential-alarm-dal.ts
new file mode 100644
index 0000000000..131e6592d5
--- /dev/null
+++ b/backend/src/services/alarm/providers/identity-credential-alarm-dal.ts
@@ -0,0 +1,90 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+
+export type TIdentityCredentialAlarmDALFactory = ReturnType<typeof identityCredentialAlarmDALFactory>;
+
+export type TExpiringUaClientSecret = {
+ id: string;
+ description: string;
+ clientSecretPrefix: string;
+ identityId: string;
+ identityName: string;
+ expiresAt: Date;
+};
+
+export const identityCredentialAlarmDALFactory = (db: TDbClient) => {
+ const findExpiringUaClientSecrets = async (
+ {
+ orgId,
+ identityId,
+ alertBeforeInterval
+ }: { orgId: string; identityId?: string | null; alertBeforeInterval: string },
+ tx?: Knex
+ ): Promise<TExpiringUaClientSecret[]> => {
+ try {
+ const expiresAtSql = `${TableName.IdentityUaClientSecret}."createdAt" + (${TableName.IdentityUaClientSecret}."clientSecretTTL" * interval '1 second')`;
+
+ const query = (tx || db.replicaNode())(TableName.IdentityUaClientSecret)
+ .join(
+ TableName.IdentityUniversalAuth,
+ `${TableName.IdentityUaClientSecret}.identityUAId`,
+ `${TableName.IdentityUniversalAuth}.id`
+ )
+ .join(
+ TableName.IdentityOrgMembership,
+ `${TableName.IdentityUniversalAuth}.identityId`,
+ `${TableName.IdentityOrgMembership}.identityId`
+ )
+ .join(TableName.Identity, `${TableName.IdentityUniversalAuth}.identityId`, `${TableName.Identity}.id`)
+ .where(`${TableName.IdentityOrgMembership}.orgId`, orgId)
+ .where(`${TableName.IdentityUaClientSecret}.isClientSecretRevoked`, false)
+ .where(`${TableName.IdentityUaClientSecret}.clientSecretTTL`, ">", 0)
+ .whereRaw(`${expiresAtSql} > NOW()`)
+ .whereRaw(`${expiresAtSql} <= NOW() + ?::interval`, [alertBeforeInterval]);
+
+ if (identityId) {
+ void query.where(`${TableName.IdentityUniversalAuth}.identityId`, identityId);
+ }
+
+ const rows = (await query.select(
+ db.ref("id").withSchema(TableName.IdentityUaClientSecret),
+ db.ref("description").withSchema(TableName.IdentityUaClientSecret),
+ db.ref("clientSecretPrefix").withSchema(TableName.IdentityUaClientSecret),
+ db.ref("identityId").withSchema(TableName.IdentityUniversalAuth),
+ db.ref("name").withSchema(TableName.Identity).as("identityName"),
+ db.raw(`${expiresAtSql} as "expiresAt"`)
+ )) as TExpiringUaClientSecret[];
+
+ return rows;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindExpiringUaClientSecrets" });
+ }
+ };
+
+ const isIdentityInOrg = async (identityId: string, orgId: string, tx?: Knex): Promise<boolean> => {
+ try {
+ const row = (await (tx || db.replicaNode())(TableName.IdentityOrgMembership)
+ .where({ identityId, orgId })
+ .first()) as { id: string } | undefined;
+ return Boolean(row);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "IsIdentityInOrg" });
+ }
+ };
+
+ const isIdentityInProject = async (identityId: string, projectId: string, tx?: Knex): Promise<boolean> => {
+ try {
+ const row = (await (tx || db.replicaNode())(TableName.IdentityProjectMembership)
+ .where({ identityId, projectId })
+ .first()) as { id: string } | undefined;
+ return Boolean(row);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "IsIdentityInProject" });
+ }
+ };
+
+ return { findExpiringUaClientSecrets, isIdentityInOrg, isIdentityInProject };
+};
diff --git a/backend/src/services/alarm/providers/identity-credential-alarm-provider.test.ts b/backend/src/services/alarm/providers/identity-credential-alarm-provider.test.ts
new file mode 100644
index 0000000000..5f511e7914
--- /dev/null
+++ b/backend/src/services/alarm/providers/identity-credential-alarm-provider.test.ts
@@ -0,0 +1,173 @@
+import { createMongoAbility } from "@casl/ability";
+import { vi } from "vitest";
+
+import { AlarmPermissionAction, TAlarmContext } from "../alarm-types";
+import { TExpiringUaClientSecret } from "./identity-credential-alarm-dal";
+import {
+ IDENTITY_CREDENTIAL_EXPIRY_EVENT,
+ IDENTITY_CREDENTIAL_RESOURCE_TYPE,
+ identityCredentialAlarmProviderFactory,
+ TIdentityCredentialAlarmProviderDep
+} from "./identity-credential-alarm-provider";
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ SITE_URL: "https://app.infisical.com" })
+}));
+
+const futureDate = (days: number) => new Date(Date.now() + days * 24 * 60 * 60 * 1000);
+
+const sampleSecret = (overrides: Partial<TExpiringUaClientSecret> = {}): TExpiringUaClientSecret => ({
+ id: "sec-1",
+ description: "ci-secret",
+ clientSecretPrefix: "abc123",
+ identityId: "ident-1",
+ identityName: "ci-runner",
+ expiresAt: futureDate(5),
+ ...overrides
+});
+
+const alarmContext = (overrides: Partial<TAlarmContext> = {}): TAlarmContext => ({
+ id: "alarm-1",
+ name: "ua-expiry",
+ orgId: "org-1",
+ resourceType: IDENTITY_CREDENTIAL_RESOURCE_TYPE,
+ resourceId: null,
+ eventType: IDENTITY_CREDENTIAL_EXPIRY_EVENT,
+ condition: { alertBefore: "30d" },
+ filters: null,
+ ...overrides
+});
+
+const buildProvider = (opts?: {
+ secrets?: TExpiringUaClientSecret[];
+ onFind?: (args: { orgId: string; identityId?: string | null; alertBeforeInterval: string }) => void;
+ abilityRules?: { action: string; subject: string }[];
+ inOrg?: boolean;
+ inProject?: boolean;
+}) => {
+ const dal = {
+ findExpiringUaClientSecrets: async (args: {
+ orgId: string;
+ identityId?: string | null;
+ alertBeforeInterval: string;
+ }) => {
+ opts?.onFind?.(args);
+ return opts?.secrets ?? [];
+ },
+ isIdentityInOrg: async () => opts?.inOrg ?? true,
+ isIdentityInProject: async () => opts?.inProject ?? true
+ };
+ const ability = () => createMongoAbility(opts?.abilityRules ?? [{ action: "read", subject: "identity" }]);
+ const permissionService = {
+ getOrgPermission: async () => ({ permission: ability() }),
+ getProjectPermission: async () => ({ permission: ability() })
+ };
+ return identityCredentialAlarmProviderFactory({
+ identityCredentialAlarmDAL: dal,
+ permissionService
+ } as unknown as TIdentityCredentialAlarmProviderDep);
+};
+
+const actor = { actor: "user", actorId: "u1", actorAuthMethod: null, actorOrgId: "org-1" } as never;
+
+describe("identity credential alarm provider", () => {
+ test("condition schema accepts alertBefore formats and rejects junk", () => {
+ const provider = buildProvider();
+ expect(provider.conditionSchema.safeParse({ alertBefore: "30d" }).success).toBe(true);
+ expect(provider.conditionSchema.safeParse({ alertBefore: "2w" }).success).toBe(true);
+ expect(provider.conditionSchema.safeParse({ alertBefore: "nope" }).success).toBe(false);
+ expect(provider.conditionSchema.safeParse({}).success).toBe(false);
+ });
+
+ test("findDueTargets converts alertBefore to a postgres interval and tags credential type", async () => {
+ let seenArgs: { alertBeforeInterval: string; identityId?: string | null } | undefined;
+ const provider = buildProvider({
+ secrets: [sampleSecret()],
+ onFind: (args) => {
+ seenArgs = args;
+ }
+ });
+
+ const targets = await provider.findDueTargets({
+ orgId: "org-1",
+ resourceId: "ident-1",
+ eventType: IDENTITY_CREDENTIAL_EXPIRY_EVENT,
+ condition: { alertBefore: "30d" },
+ filters: null
+ });
+
+ expect(seenArgs?.alertBeforeInterval).toBe("30 days");
+ expect(seenArgs?.identityId).toBe("ident-1");
+ expect(targets).toHaveLength(1);
+ expect(provider.targetId(targets[0])).toBe("ua-client-secret:sec-1");
+ });
+
+ test("buildPayload produces neutral items, severity, and an in-app notification type", () => {
+ const provider = buildProvider();
+ const target = { credentialType: "ua-client-secret" as const, ...sampleSecret({ expiresAt: futureDate(3) }) };
+ const payload = provider.buildPayload(alarmContext(), [target]);
+
+ expect(payload.eventKey).toBe(IDENTITY_CREDENTIAL_EXPIRY_EVENT);
+ expect(payload.severity).toBe("critical"); // 3 days out
+ expect(payload.notificationType).toBe("identity-credential-expiry");
+ expect(payload.items[0].fields?.some((f) => f.label === "Days Until Expiry")).toBe(true);
+ expect(payload.alarm.viewUrl).toContain("/organizations/org-1/identities");
+ });
+
+ test("buildPayload deep-links to the bound identity when resourceId is set", () => {
+ const provider = buildProvider();
+ const target = { credentialType: "ua-client-secret" as const, ...sampleSecret() };
+ const payload = provider.buildPayload(alarmContext({ resourceId: "ident-1" }), [target]);
+ expect(payload.alarm.viewUrl).toContain("/identities/ident-1");
+ });
+
+ test("dedup window spans the lead time (30d -> 720h) with a 24h floor", () => {
+ const provider = buildProvider();
+ expect(provider.dedupWindowHours?.({ alertBefore: "30d" })).toBe(720);
+ expect(provider.dedupWindowHours?.({ alertBefore: "1d" })).toBe(24);
+ expect(provider.dedupWindowHours?.({ alertBefore: "bad" })).toBe(24);
+ });
+
+ test("assertPermission allows read but denies create when only read is granted (org scope)", async () => {
+ const provider = buildProvider({ abilityRules: [{ action: "read", subject: "identity" }] });
+ await expect(
+ provider.assertPermission({ action: AlarmPermissionAction.Read, orgId: "org-1", actor })
+ ).resolves.toBeUndefined();
+ await expect(
+ provider.assertPermission({ action: AlarmPermissionAction.Create, orgId: "org-1", actor })
+ ).rejects.toThrow();
+ });
+
+ test("assertPermission uses the project identity permission when the alarm is project-scoped", async () => {
+ const provider = buildProvider({ abilityRules: [{ action: "read", subject: "identity" }] });
+ await expect(
+ provider.assertPermission({ action: AlarmPermissionAction.Read, orgId: "org-1", projectId: "proj-1", actor })
+ ).resolves.toBeUndefined();
+ await expect(
+ provider.assertPermission({ action: AlarmPermissionAction.Edit, orgId: "org-1", projectId: "proj-1", actor })
+ ).rejects.toThrow();
+ });
+
+ test("assertResourceInScope no-ops when there is no resource (filter-based alarm)", async () => {
+ const provider = buildProvider({ inOrg: false });
+ // inOrg=false would reject if checked, but with no resourceId it must return without checking.
+ await expect(provider.assertResourceInScope({ orgId: "org-1" })).resolves.toBeUndefined();
+ });
+
+ test("assertResourceInScope passes for an identity in the org", async () => {
+ const provider = buildProvider({ inOrg: true });
+ await expect(provider.assertResourceInScope({ orgId: "org-1", resourceId: "ident-1" })).resolves.toBeUndefined();
+ });
+
+ test("assertResourceInScope rejects an identity not in the org", async () => {
+ const provider = buildProvider({ inOrg: false });
+ await expect(provider.assertResourceInScope({ orgId: "org-1", resourceId: "foreign" })).rejects.toThrow();
+ });
+
+ test("assertResourceInScope rejects an identity not in the project when project-scoped", async () => {
+ const provider = buildProvider({ inOrg: true, inProject: false });
+ await expect(
+ provider.assertResourceInScope({ orgId: "org-1", projectId: "proj-1", resourceId: "ident-1" })
+ ).rejects.toThrow();
+ });
+});
diff --git a/backend/src/services/alarm/providers/identity-credential-alarm-provider.ts b/backend/src/services/alarm/providers/identity-credential-alarm-provider.ts
new file mode 100644
index 0000000000..70456b2e5f
--- /dev/null
+++ b/backend/src/services/alarm/providers/identity-credential-alarm-provider.ts
@@ -0,0 +1,195 @@
+import { ForbiddenError } from "@casl/ability";
+import RE2 from "re2";
+import { z } from "zod";
+
+import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";
+import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
+import { getConfig } from "@app/lib/config/env";
+import { NotFoundError } from "@app/lib/errors";
+import { NotificationType } from "@app/services/notification/notification-types";
+
+import { TAlarmPayload, TAlarmSeverity } from "../alarm-channel-types";
+import {
+ AlarmPermissionAction,
+ DEFAULT_DEDUP_WINDOW_HOURS,
+ IResourceAlarmProvider,
+ TAlarmContext,
+ TAlarmPermissionInput,
+ TFindDueTargetsInput
+} from "../alarm-types";
+import { TExpiringUaClientSecret, TIdentityCredentialAlarmDALFactory } from "./identity-credential-alarm-dal";
+
+export const IDENTITY_CREDENTIAL_RESOURCE_TYPE = "identity.credential";
+export const IDENTITY_CREDENTIAL_EXPIRY_EVENT = "identity.credential.expiry";
+
+const alertBeforeRegex = new RE2("^\\d+[dwmy]$");
+
+const IdentityCredentialConditionSchema = z.object({
+ alertBefore: z.string().refine((v) => alertBeforeRegex.test(v), "Must be in format like '30d', '1w', '3m', '1y'")
+});
+
+type TIdentityCredentialTarget = { credentialType: "ua-client-secret" } & TExpiringUaClientSecret;
+
+const UNIT_TO_INTERVAL_WORD: Record<string, string> = { d: "days", w: "weeks", m: "months", y: "years" };
+const UNIT_TO_DAYS: Record<string, number> = { d: 1, w: 7, m: 30, y: 365 };
+
+const parseAlertBefore = (alertBefore: string) => {
+ const amount = parseInt(alertBefore.slice(0, -1), 10);
+ const unit = alertBefore.slice(-1);
+ return {
+ intervalSql: `${amount} ${UNIT_TO_INTERVAL_WORD[unit]}`,
+ days: amount * (UNIT_TO_DAYS[unit] ?? 1)
+ };
+};
+
+const daysUntil = (date: Date): number => Math.ceil((new Date(date).getTime() - Date.now()) / (1000 * 60 * 60 * 24));
+
+const severityFor = (targets: TIdentityCredentialTarget[]): TAlarmSeverity => {
+ const minDays = Math.min(...targets.map((t) => daysUntil(t.expiresAt)));
+ if (minDays <= 7) return "critical";
+ if (minDays <= 14) return "error";
+ if (minDays <= 30) return "warning";
+ return "info";
+};
+
+const CREDENTIAL_TYPE_LABEL: Record<TIdentityCredentialTarget["credentialType"], string> = {
+ "ua-client-secret": "Universal Auth Client Secret"
+};
+
+export type TIdentityCredentialAlarmProviderDep = {
+ identityCredentialAlarmDAL: TIdentityCredentialAlarmDALFactory;
+ permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;
+};
+
+export const identityCredentialAlarmProviderFactory = ({
+ identityCredentialAlarmDAL,
+ permissionService
+}: TIdentityCredentialAlarmProviderDep): IResourceAlarmProvider<TIdentityCredentialTarget> => {
+ const buildViewUrl = (alarm: TAlarmContext): string => {
+ const appCfg = getConfig();
+ const base = `${appCfg.SITE_URL ?? "https://app.infisical.com"}/organizations/${alarm.orgId}/identities`;
+ return alarm.resourceId ? `${base}/${alarm.resourceId}` : base;
+ };
+
+ const findDueTargets = async (input: TFindDueTargetsInput): Promise<TIdentityCredentialTarget[]> => {
+ const { alertBefore } = IdentityCredentialConditionSchema.parse(input.condition);
+ const { intervalSql } = parseAlertBefore(alertBefore);
+
+ const uaSecrets = await identityCredentialAlarmDAL.findExpiringUaClientSecrets({
+ orgId: input.orgId,
+ identityId: input.resourceId,
+ alertBeforeInterval: intervalSql
+ });
+
+ return uaSecrets.map((secret) => ({ credentialType: "ua-client-secret" as const, ...secret }));
+ };
+
+ const buildPayload = (alarm: TAlarmContext, targets: TIdentityCredentialTarget[]): TAlarmPayload => {
+ const alertBefore = (alarm.condition as { alertBefore?: string } | null)?.alertBefore;
+ const viewUrl = buildViewUrl(alarm);
+
+ return {
+ alarm: {
+ id: alarm.id,
+ name: alarm.name,
+ orgId: alarm.orgId,
+ resourceType: alarm.resourceType,
+ ...(alertBefore ? { condition: alertBefore } : {}),
+ viewUrl
+ },
+ eventKey: IDENTITY_CREDENTIAL_EXPIRY_EVENT,
+ eventLabel: "Expiration",
+ webhookType: "com.infisical.identity.credential.expiration",
+ resourceKind: "Identity Credential",
+ severity: severityFor(targets),
+ summary: alertBefore
+ ? `${targets.length} identity credential(s) expiring within ${alertBefore}`
+ : `${targets.length} identity credential(s) expiring`,
+ notificationType: NotificationType.IDENTITY_CREDENTIAL_EXPIRY,
+ items: targets.map((target) => ({
+ id: `${target.credentialType}:${target.id}`,
+ title: `${CREDENTIAL_TYPE_LABEL[target.credentialType]} — ${target.identityName}`,
+ identifier: target.description || target.clientSecretPrefix,
+ fields: [
+ { label: "Credential Type", value: CREDENTIAL_TYPE_LABEL[target.credentialType] },
+ { label: "Identity", value: target.identityName },
+ { label: "Expires", value: new Date(target.expiresAt).toISOString().split("T")[0] },
+ { label: "Days Until Expiry", value: String(daysUntil(target.expiresAt)) }
+ ]
+ }))
+ };
+ };
+
+ const targetId = (target: TIdentityCredentialTarget): string => `${target.credentialType}:${target.id}`;
+
+ const assertResourceInScope = async (input: {
+ orgId: string;
+ projectId?: string | null;
+ resourceId?: string | null;
+ }): Promise<void> => {
+ if (!input.resourceId) return;
+
+ const inOrg = await identityCredentialAlarmDAL.isIdentityInOrg(input.resourceId, input.orgId);
+ if (!inOrg) {
+ throw new NotFoundError({ message: `Identity '${input.resourceId}' was not found in this organization` });
+ }
+
+ if (input.projectId) {
+ const inProject = await identityCredentialAlarmDAL.isIdentityInProject(input.resourceId, input.projectId);
+ if (!inProject) {
+ throw new NotFoundError({ message: `Identity '${input.resourceId}' is not a member of this project` });
+ }
+ }
+ };
+
+ const assertPermission = async (input: TAlarmPermissionInput): Promise<void> => {
+ const isRead = input.action === AlarmPermissionAction.Read;
+
+ if (input.projectId) {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: input.actor.actor,
+ actorId: input.actor.actorId,
+ projectId: input.projectId,
+ actorAuthMethod: input.actor.actorAuthMethod,
+ actorOrgId: input.actor.actorOrgId,
+ actionProjectType: ActionProjectType.Any
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ isRead ? ProjectPermissionIdentityActions.Read : ProjectPermissionIdentityActions.Edit,
+ ProjectPermissionSub.Identity
+ );
+ return;
+ }
+
+ const { permission } = await permissionService.getOrgPermission({
+ scope: OrganizationActionScope.Any,
+ actor: input.actor.actor,
+ actorId: input.actor.actorId,
+ orgId: input.orgId,
+ actorAuthMethod: input.actor.actorAuthMethod,
+ actorOrgId: input.actor.actorOrgId
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ isRead ? OrgPermissionIdentityActions.Read : OrgPermissionIdentityActions.Edit,
+ OrgPermissionSubjects.Identity
+ );
+ };
+
+ return {
+ resourceType: IDENTITY_CREDENTIAL_RESOURCE_TYPE,
+ eventTypes: [IDENTITY_CREDENTIAL_EXPIRY_EVENT],
+ conditionSchema: IdentityCredentialConditionSchema,
+ findDueTargets,
+ buildPayload,
+ targetId,
+ dedupWindowHours: (condition) => {
+ const parsed = IdentityCredentialConditionSchema.safeParse(condition);
+ if (!parsed.success) return DEFAULT_DEDUP_WINDOW_HOURS;
+ return Math.max(DEFAULT_DEDUP_WINDOW_HOURS, parseAlertBefore(parsed.data.alertBefore).days * 24);
+ },
+ assertPermission,
+ assertResourceInScope
+ };
+};
diff --git a/backend/src/services/notification/notification-types.ts b/backend/src/services/notification/notification-types.ts
index ad347a7231..d7810cd0a3 100644
--- a/backend/src/services/notification/notification-types.ts
+++ b/backend/src/services/notification/notification-types.ts
@@ -22,7 +22,9 @@ export enum NotificationType {
APPROVAL_REQUIRED = "approval-required",
PKI_ALERT_CHANNEL_FAILED = "pki-alert-channel-failed",
CREDENTIAL_ROTATION_FAILED = "credential-rotation-failed",
- AUDIT_LOG_MIGRATION_RECOMMENDED = "audit-log-migration-recommended"
+ AUDIT_LOG_MIGRATION_RECOMMENDED = "audit-log-migration-recommended",
+ ALARM_CHANNEL_FAILED = "alarm-channel-failed",
+ IDENTITY_CREDENTIAL_EXPIRY = "identity-credential-expiry"
}
export interface TCreateUserNotificationDTO {
diff --git a/backend/src/services/smtp/emails/AlarmNotificationTemplate.tsx b/backend/src/services/smtp/emails/AlarmNotificationTemplate.tsx
new file mode 100644
index 0000000000..5ba2beb0e0
--- /dev/null
+++ b/backend/src/services/smtp/emails/AlarmNotificationTemplate.tsx
@@ -0,0 +1,88 @@
+import { Heading, Section, Text } from "@react-email/components";
+
+import { BaseButton } from "./BaseButton";
+import { BaseEmailWrapper, BaseEmailWrapperProps } from "./BaseEmailWrapper";
+
+interface AlarmNotificationTemplateProps extends Omit<BaseEmailWrapperProps, "title" | "preview" | "children"> {
+ alarmName: string;
+ eventLabel: string;
+ resourceKind: string;
+ summary: string;
+ condition?: string;
+ viewUrl: string;
+ items: { title: string; identifier?: string; fields?: { label: string; value: string }[] }[];
+}
+
+export const AlarmNotificationTemplate = ({
+ alarmName,
+ eventLabel,
+ resourceKind,
+ summary,
+ viewUrl,
+ siteUrl,
+ items
+}: AlarmNotificationTemplateProps) => {
+ const title = `${resourceKind} ${eventLabel} Notice`;
+
+ return (
+ <BaseEmailWrapper title={title} preview={summary} siteUrl={siteUrl}>
+ <Heading className="text-black text-[18px] leading-[28px] text-center font-normal p-0 mx-0">
+ <strong>{title}</strong>
+ </Heading>
+
+ <Section className="px-[24px] mb-[28px] mt-[36px] pt-[12px] pb-[8px] border border-solid border-gray-200 rounded-md bg-gray-50">
+ <Text className="text-[14px]">
+ Alarm {alarmName}: {summary}
+ </Text>
+ </Section>
+
+ <Section className="mb-[28px]">
+ {items.map((item) => (
+ <Section
+ key={item.identifier ?? item.title}
+ className="mb-[16px] p-[16px] border border-solid border-gray-200 rounded-md bg-gray-50"
+ >
+ <Text className="text-[14px] font-semibold m-0 mb-[4px]">{item.title}</Text>
+ {item.identifier && <Text className="text-[12px] text-gray-600 m-0 mb-[4px]">{item.identifier}</Text>}
+ {(item.fields ?? []).map((field) => (
+ <Text key={field.label} className="text-[12px] text-gray-600 m-0 mb-[4px]">
+ {field.label}: {field.value}
+ </Text>
+ ))}
+ </Section>
+ ))}
+ </Section>
+
+ <Section className="text-center mt-[32px] mb-[16px]">
+ <BaseButton href={viewUrl}>View in Infisical</BaseButton>
+ </Section>
+ </BaseEmailWrapper>
+ );
+};
+
+export default AlarmNotificationTemplate;
+
+AlarmNotificationTemplate.PreviewProps = {
+ alarmName: "prod-cert-expiry",
+ eventLabel: "Expiration",
+ resourceKind: "Certificate",
+ summary: "2 certificates expiring within 30d",
+ condition: "30d",
+ viewUrl: "https://infisical.com/organizations/org-1/projects/cert-manager/proj-1/inventory",
+ siteUrl: "https://infisical.com",
+ items: [
+ {
+ title: "api.production.company.com",
+ identifier: "Serial: 4B:3E:2F:A1:D6:7C:89:45",
+ fields: [
+ { label: "Expires", value: "November 12, 2025" },
+ { label: "Days Until Expiry", value: "7" }
+ ]
+ },
+ {
+ title: "web.company.com",
+ identifier: "Serial: 8A:7F:1C:E4:92:B5:D3:68",
+ fields: [{ label: "Expires", value: "November 10, 2025" }]
+ }
+ ]
+} as AlarmNotificationTemplateProps;
diff --git a/backend/src/services/smtp/emails/index.ts b/backend/src/services/smtp/emails/index.ts
index 08c62104b2..1c6b453020 100644
--- a/backend/src/services/smtp/emails/index.ts
+++ b/backend/src/services/smtp/emails/index.ts
@@ -3,6 +3,7 @@ export * from "./AccessApprovalRequestUpdatedTemplate";
export * from "./AccessPamRequestBypassedTemplate";
export * from "./AccessPamRequestTemplate";
export * from "./AccountDeletionConfirmationTemplate";
+export * from "./AlarmNotificationTemplate";
export * from "./AuditLogMigrationAlertTemplate";
export * from "./AuditReportTemplate";
export * from "./CredentialRotationFailedTemplate";
diff --git a/backend/src/services/smtp/smtp-service.ts b/backend/src/services/smtp/smtp-service.ts
index 08e806d4de..24433352a1 100644
--- a/backend/src/services/smtp/smtp-service.ts
+++ b/backend/src/services/smtp/smtp-service.ts
@@ -13,6 +13,7 @@ import {
AccessPamRequestBypassedTemplate,
AccessPamRequestTemplate,
AccountDeletionConfirmationTemplate,
+ AlarmNotificationTemplate,
AuditLogMigrationAlertTemplate,
AuditReportTemplate,
CredentialRotationFailedTemplate,
@@ -122,7 +123,8 @@ export enum SmtpTemplates {
CredentialRotationFailed = "credentialRotationFailed",
AuditLogMigrationAlert = "auditLogMigrationAlert",
HoneyTokenTriggered = "honeyTokenTriggered",
- AuditReport = "auditReport"
+ AuditReport = "auditReport",
+ AlarmNotification = "alarmNotification"
}
export enum SmtpHost {
@@ -183,7 +185,8 @@ const EmailTemplateMap: Record<SmtpTemplates, React.FC<any>> = {
[SmtpTemplates.CredentialRotationFailed]: CredentialRotationFailedTemplate,
[SmtpTemplates.AuditLogMigrationAlert]: AuditLogMigrationAlertTemplate,
[SmtpTemplates.HoneyTokenTriggered]: HoneyTokenTriggeredTemplate,
- [SmtpTemplates.AuditReport]: AuditReportTemplate
+ [SmtpTemplates.AuditReport]: AuditReportTemplate,
+ [SmtpTemplates.AlarmNotification]: AlarmNotificationTemplate
};
export const smtpServiceFactory = (cfg: TSmtpConfig) => {