Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
dedup by channel
Thiago Araujo da Silva625969ad8bc8
diff --git a/backend/src/db/migrations/20260714120000_add-alarms.ts b/backend/src/db/migrations/20260714120000_add-alarms.tsindex b18d88e4ab..cc902d2638 100644--- a/backend/src/db/migrations/20260714120000_add-alarms.ts+++ b/backend/src/db/migrations/20260714120000_add-alarms.ts@@ -69,10 +69,10 @@ export async function up(knex: Knex): Promise<void> {t.timestamps(true, true, true);t.foreign("alarmId").references("id").inTable(TableName.Alarm).onDelete("CASCADE");- // Covers the FK plus the dedup lookup: recently *successfully* alarmed targets for an alarm.- // Column order is equality (alarmId), equality (status), then range (triggeredAt) so the whole- // WHERE clause is served by the index.- t.index(["alarmId", "status", "triggeredAt"]);+ // Covers the FK plus the dedup lookup: recent runs for an alarm within the window. The run-level+ // status column (success | partial | failed) is audit-only; per-(channel, target) success+ // filtering happens on alarm_history_target, so status is not part of this index.+ t.index(["alarmId", "triggeredAt"]);});}@@ -81,10 +81,19 @@ export async function up(knex: Knex): Promise<void> {t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());t.uuid("alarmHistoryId").notNullable();t.string("targetId").notNullable();+ // Dedup is scoped per (channel, target): a broken channel re-fires only its own targets while+ // channels that already delivered are never re-notified. channelId is nullable (SET NULL) so a+ // delivery record survives channel deletion; channelType is retained for display when it does.+ t.uuid("channelId").nullable();+ t.string("channelType").notNullable();+ t.string("status").notNullable();t.timestamps(true, true, true);t.foreign("alarmHistoryId").references("id").inTable(TableName.AlarmHistory).onDelete("CASCADE");+ t.foreign("channelId").references("id").inTable(TableName.AlarmChannel).onDelete("SET NULL");+ // Serves the dedup lookup: join on alarmHistoryId, filter status=success + targetId IN (...).t.index(["alarmHistoryId", "targetId"]);+ t.index("channelId");});}}diff --git a/backend/src/db/schemas/alarm-history-target.ts b/backend/src/db/schemas/alarm-history-target.tsindex 7fb206c801..6bf94f42fa 100644--- a/backend/src/db/schemas/alarm-history-target.ts+++ b/backend/src/db/schemas/alarm-history-target.ts@@ -11,6 +11,9 @@ export const AlarmHistoryTargetSchema = z.object({id: z.string().uuid(),alarmHistoryId: z.string().uuid(),targetId: z.string(),+ channelId: z.string().uuid().nullable().optional(),+ channelType: z.string(),+ status: z.string(),createdAt: z.date(),updatedAt: z.date()});diff --git a/backend/src/services/alarm/alarm-engine.test.ts b/backend/src/services/alarm/alarm-engine.test.tsindex 588b8b66de..f8a40832a4 100644--- a/backend/src/services/alarm/alarm-engine.test.ts+++ b/backend/src/services/alarm/alarm-engine.test.ts@@ -5,6 +5,13 @@ import { alarmEngineFactory, TAlarmEngineDep } from "./alarm-engine";import { alarmProviderRegistryFactory } from "./alarm-provider-registry";import { AlarmPrincipalType, AlarmRunStatus, IResourceAlarmProvider, TAlarmContext } from "./alarm-types";+// logger is `export let logger` assigned by initLogger(), which unit tests don't run, so any+// channel-failure path (which logs) would otherwise dereference undefined. Mock it per-file.+vi.mock("@app/lib/logger", () => ({+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },+ initLogger: () => {}+}));+type TTarget = { id: string };const RESOURCE_TYPE = "test.resource";@@ -62,18 +69,21 @@ const kmsServiceMock = {const encConfig = (config: unknown) => Buffer.from(JSON.stringify(config));+type TDelivery = { targetId: string; channelId: string; channelType: string; status: string };+const buildEngine = (opts: {targets: TTarget[];channels: Array<{ id: string; channelType: string; encryptedConfig: Buffer; enabled: boolean }>;- recentlyAlarmed?: string[];+ recentlyAlarmed?: Array<{ channelId: string; targetId: string }>;recipients?: Array<{ userId: string; email: string; firstName?: string | null }>;+ failEmail?: boolean;}) => {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 historyWrites: Array<{ deliveries: TDelivery[]; status: string }> = [];const engine = alarmEngineFactory({alarmChannelDAL: { findByAlarmId: async () => opts.channels },@@ -91,8 +101,8 @@ const buildEngine = (opts: {},alarmHistoryDAL: {findRecentlyAlarmedTargets: async () => opts.recentlyAlarmed ?? [],- createWithTargets: async (_alarmId: string, targetIds: string[], options: { status: string }) => {- historyWrites.push({ targetIds, status: options.status });+ createWithTargets: async (_alarmId: string, options: { status: string }, deliveries: TDelivery[]) => {+ historyWrites.push({ deliveries, status: options.status });return {} as never;}},@@ -109,6 +119,7 @@ const buildEngine = (opts: {},smtpService: {sendMail: async (opt: { recipients: string[] }) => {+ if (opts.failEmail) throw new Error("smtp down");sentMail.push({ recipients: opt.recipients });}}@@ -118,7 +129,7 @@ const buildEngine = (opts: {};describe("alarm engine", () => {- test("dispatches email to resolved recipients and records history", async () => {+ test("dispatches email to resolved recipients and records a delivery per (target, channel)", async () => {const { engine, sentMail, createdNotifications, historyWrites } = buildEngine({targets: [{ id: "t1" }, { id: "t2" }],channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }]@@ -130,28 +141,68 @@ describe("alarm engine", () => {expect(sentMail[0].recipients).toEqual(["[email protected]"]);expect(createdNotifications).toHaveLength(0); // no failure fallback on successexpect(historyWrites).toHaveLength(1);- expect(historyWrites[0].targetIds).toEqual(["t1", "t2"]);expect(historyWrites[0].status).toBe(AlarmRunStatus.SUCCESS);+ expect(historyWrites[0].deliveries).toEqual([+ { targetId: "t1", channelId: "c-email", channelType: "email", status: AlarmRunStatus.SUCCESS },+ { targetId: "t2", channelId: "c-email", channelType: "email", status: AlarmRunStatus.SUCCESS }+ ]);});- test("dedups targets already alarmed within the window", async () => {+ test("dedups a target already delivered on the same channel 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"]+ recentlyAlarmed: [{ channelId: "c-email", targetId: "t1" }]});await engine.runAlarm(makeAlarm());expect(historyWrites).toHaveLength(1);- expect(historyWrites[0].targetIds).toEqual(["t2"]);+ expect(historyWrites[0].deliveries.map((d) => d.targetId)).toEqual(["t2"]);+ });++ test("re-fires a target on a channel that has not delivered it, even if another channel has", async () => {+ const { engine, sentMail, historyWrites } = buildEngine({+ targets: [{ id: "t1" }],+ channels: [+ { id: "c-email-1", channelType: "email", encryptedConfig: encConfig({}), enabled: true },+ { id: "c-email-2", channelType: "email", encryptedConfig: encConfig({}), enabled: true }+ ],+ // t1 was delivered on channel 1 but never on channel 2 → only channel 2 should fire.+ recentlyAlarmed: [{ channelId: "c-email-1", targetId: "t1" }]+ });++ await engine.runAlarm(makeAlarm());++ expect(sentMail).toHaveLength(1);+ expect(historyWrites).toHaveLength(1);+ expect(historyWrites[0].deliveries).toEqual([+ { targetId: "t1", channelId: "c-email-2", channelType: "email", status: AlarmRunStatus.SUCCESS }+ ]);+ });++ test("records FAILED deliveries when a channel fails so they are re-tried next run", async () => {+ const { engine, sentMail, historyWrites } = buildEngine({+ targets: [{ id: "t1" }],+ channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }],+ failEmail: true+ });++ await engine.runAlarm(makeAlarm());++ expect(sentMail).toHaveLength(0);+ expect(historyWrites).toHaveLength(1);+ expect(historyWrites[0].status).toBe(AlarmRunStatus.FAILED);+ expect(historyWrites[0].deliveries).toEqual([+ { targetId: "t1", channelId: "c-email", channelType: "email", status: AlarmRunStatus.FAILED }+ ]);});- test("skips entirely when all targets were recently alarmed", async () => {+ test("skips entirely when every channel already delivered every target", async () => {const { engine, historyWrites, sentMail } = buildEngine({targets: [{ id: "t1" }],channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }],- recentlyAlarmed: ["t1"]+ recentlyAlarmed: [{ channelId: "c-email", targetId: "t1" }]});await engine.runAlarm(makeAlarm());diff --git a/backend/src/services/alarm/alarm-engine.ts b/backend/src/services/alarm/alarm-engine.tsindex 6261c8f5f4..2759defde0 100644--- a/backend/src/services/alarm/alarm-engine.ts+++ b/backend/src/services/alarm/alarm-engine.ts@@ -87,14 +87,21 @@ export const alarmEngineFactory = ({});if (targets.length === 0) return;+ const channels = (await alarmChannelDAL.findByAlarmId(alarm.id)).filter((channel) => channel.enabled);+ if (channels.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 recentlyAlarmed = await alarmHistoryDAL.findRecentlyAlarmedTargets(alarm.id, candidateIds, window);+ const alarmedSet = new Set(recentlyAlarmed.map((row) => `${row.channelId}:${row.targetId}`));- const channels = (await alarmChannelDAL.findByAlarmId(alarm.id)).filter((channel) => channel.enabled);- if (channels.length === 0) return;+ const channelWork = channels+ .map((channel) => ({+ channel,+ dueTargets: targets.filter((target) => !alarmedSet.has(`${channel.id}:${provider.targetId(target)}`))+ }))+ .filter((work) => work.dueTargets.length > 0);+ if (channelWork.length === 0) return;const alarmContext: TAlarmContext = {id: alarm.id,@@ -107,15 +114,16 @@ export const alarmEngineFactory = ({condition: alarm.condition,filters: alarm.filters};- const payload = provider.buildPayload(alarmContext, dueTargets);+ // viewUrl is target-independent; build one reference payload to source it for the failure notice.+ const { viewUrl } = provider.buildPayload(alarmContext, targets).alarm;const { decryptor } = await getAlarmChannelCipher(kmsService, {orgId: alarm.orgId,projectId: alarm.projectId});- const hasDirectedChannel = channels.some(- (channel) => ALARM_CHANNEL_REGISTRY[channel.channelType as AlarmChannelType]?.directed+ const hasDirectedChannel = channelWork.some(+ (work) => ALARM_CHANNEL_REGISTRY[work.channel.channelType as AlarmChannelType]?.directed);let recipients: TAlarmRecipient[] = [];if (hasDirectedChannel) {@@ -125,18 +133,22 @@ export const alarmEngineFactory = ({const deps: TAlarmChannelDeps = { smtpService };const channelResults = await Promise.all(- channels.map(async (channel) => {+ channelWork.map(async ({ channel, dueTargets }) => {+ const targetIds = dueTargets.map((target) => provider.targetId(target));+ const base = { channelId: channel.id, channelType: channel.channelType, targetIds };const definition = ALARM_CHANNEL_REGISTRY[channel.channelType as AlarmChannelType];- if (!definition) return { channelType: channel.channelType, success: false, error: "Unknown channel type" };+ if (!definition) return { ...base, 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" };+ return { ...base, success: false, error: "Failed to decrypt channel config" };}+ const payload = provider.buildPayload(alarmContext, dueTargets);+try {if (definition.directed) {const deliveries = recipients.length > 0 ? recipients : [undefined];@@ -147,40 +159,43 @@ export const alarmEngineFactory = ({);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 { ...base, success: false, error: failures.map((f) => f.error).join("; ") };}- return { channelType: channel.channelType, success: true };+ return { ...base, success: true };}const result = await definition.send({ channelId: channel.id, config, payload, deps });- return { channelType: channel.channelType, ...result };+ return { ...base, ...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 };+ return { ...base, success: false, error };}}));+ const deliveries = channelResults.flatMap((result) =>+ result.targetIds.map((targetId) => ({+ targetId,+ channelId: result.channelId,+ channelType: result.channelType,+ status: result.success ? AlarmRunStatus.SUCCESS : AlarmRunStatus.FAILED+ }))+ );+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 anyDelivered = channelResults.some((result) => result.success);+ let status = AlarmRunStatus.SUCCESS;+ if (errors.length > 0) status = anyDelivered ? AlarmRunStatus.PARTIAL : AlarmRunStatus.FAILED;const errorText = errors.length > 0 ? errors.join("\n") : undefined;if (errorText) {- await notifyAdminsOfFailure(alarm, payload.alarm.viewUrl, errorText);+ await notifyAdminsOfFailure(alarm, viewUrl, errorText);}- await alarmHistoryDAL.createWithTargets(- alarm.id,- dueTargets.map((target) => provider.targetId(target)),- { status, error: errorText }- );+ await alarmHistoryDAL.createWithTargets(alarm.id, { status, error: errorText }, deliveries);};return { runAlarm };diff --git a/backend/src/services/alarm/alarm-history-dal.test.ts b/backend/src/services/alarm/alarm-history-dal.test.tsindex ec9b215525..deb4a9a48f 100644--- a/backend/src/services/alarm/alarm-history-dal.test.ts+++ b/backend/src/services/alarm/alarm-history-dal.test.ts@@ -1,8 +1,9 @@import { alarmHistoryDALFactory } from "./alarm-history-dal";import { AlarmRunStatus } from "./alarm-types";-// Records the .where() predicates the dedup query applies, so we can assert it filters on-// status=success (regression for: a transiently FAILED run must not suppress re-delivery).+// Records the .where() predicates the dedup query applies, so we can assert it filters on the+// per-(channel, target) delivery status (regression for: a transiently FAILED delivery must not+// suppress re-delivery, and a success on one channel must not suppress delivery on another).const buildDAL = () => {const whereCalls: unknown[][] = [];const chain = {@@ -12,8 +13,9 @@ const buildDAL = () => {return chain;},whereIn: () => chain,+ whereNotNull: () => chain,distinct: () => chain,- select: async () => [] as Array<{ targetId: string }>+ select: async () => [] as Array<{ channelId: string; targetId: string }>};const queryBuilder = () => chain;const db = { replicaNode: () => queryBuilder } as never;@@ -22,12 +24,12 @@ const buildDAL = () => {};describe("alarm history dal", () => {- test("findRecentlyAlarmedTargets only counts successful runs", async () => {+ test("findRecentlyAlarmedTargets only counts successful deliveries", async () => {const { dal, whereCalls } = buildDAL();await dal.findRecentlyAlarmedTargets("alarm-1", ["t1", "t2"], 24);- expect(whereCalls).toContainEqual(["hist.status", AlarmRunStatus.SUCCESS]);+ expect(whereCalls).toContainEqual(["tgt.status", AlarmRunStatus.SUCCESS]);expect(whereCalls).toContainEqual(["hist.alarmId", "alarm-1"]);});diff --git a/backend/src/services/alarm/alarm-history-dal.ts b/backend/src/services/alarm/alarm-history-dal.tsindex 851d427cd0..58a575d4dd 100644--- a/backend/src/services/alarm/alarm-history-dal.ts+++ b/backend/src/services/alarm/alarm-history-dal.ts@@ -9,13 +9,22 @@ import { AlarmRunStatus } from "./alarm-types";export type TAlarmHistoryDALFactory = ReturnType<typeof alarmHistoryDALFactory>;+export type TAlarmTargetDelivery = {+ targetId: string;+ channelId: string;+ channelType: string;+ status: string;+};++export type TRecentlyAlarmedTarget = { channelId: string; targetId: string };+export const alarmHistoryDALFactory = (db: TDbClient) => {const alarmHistoryOrm = ormify(db, TableName.AlarmHistory);const createWithTargets = async (alarmId: string,- targetIds: string[],- options: { status: string; error?: string }+ options: { status: string; error?: string },+ deliveries: TAlarmTargetDelivery[]): Promise<TAlarmHistory> => {try {return await db.transaction(async (tx) => {@@ -23,9 +32,15 @@ export const alarmHistoryDALFactory = (db: TDbClient) => {.insert({ alarmId, status: options.status, error: options.error }).returning("*");- if (targetIds.length > 0) {+ if (deliveries.length > 0) {await tx(TableName.AlarmHistoryTarget).insert(- targetIds.map((targetId) => ({ alarmHistoryId: history.id, targetId }))+ deliveries.map((delivery) => ({+ alarmHistoryId: history.id,+ targetId: delivery.targetId,+ channelId: delivery.channelId,+ channelType: delivery.channelType,+ status: delivery.status+ })));}@@ -41,25 +56,26 @@ export const alarmHistoryDALFactory = (db: TDbClient) => {targetIds: string[],withinHours: number,tx?: Knex- ): Promise<string[]> => {+ ): Promise<TRecentlyAlarmedTarget[]> => {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);+ 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.status", AlarmRunStatus.SUCCESS).where("hist.triggeredAt", ">=", cutoffDate)+ .where("tgt.status", AlarmRunStatus.SUCCESS)+ .whereNotNull("tgt.channelId").whereIn("tgt.targetId", targetIds)- .distinct("tgt.targetId")- .select("tgt.targetId")) as Array<{ targetId: string }>;+ .distinct("tgt.channelId", "tgt.targetId")+ .select("tgt.channelId", "tgt.targetId")) as TRecentlyAlarmedTarget[];- return rows.map((row) => row.targetId);+ return rows;} catch (error) {throw new DatabaseError({ error, name: "FindRecentlyAlarmedTargets" });}diff --git a/backend/src/services/alarm/alarm-queue.ts b/backend/src/services/alarm/alarm-queue.tsindex 1cdada191d..04495846d9 100644--- a/backend/src/services/alarm/alarm-queue.ts+++ b/backend/src/services/alarm/alarm-queue.ts@@ -43,8 +43,7 @@ export const alarmQueueServiceFactory = ({jobId: `alarm-dispatch-${alarm.id}`,removeOnComplete: true,removeOnFail: { count: 5 },- attempts: 3,- backoff: { type: "exponential", delay: 5000 }+ attempts: 1}))diff --git a/backend/src/services/alarm/alarm-types.ts b/backend/src/services/alarm/alarm-types.tsindex 0acaa5ce8b..bbfff5d69c 100644--- a/backend/src/services/alarm/alarm-types.ts+++ b/backend/src/services/alarm/alarm-types.ts@@ -13,6 +13,7 @@ export enum AlarmPrincipalType {export enum AlarmRunStatus {SUCCESS = "success",+ PARTIAL = "partial",FAILED = "failed"}diff --git a/backend/src/services/alarm/channels/alarm-channel-pagerduty-fns.ts b/backend/src/services/alarm/channels/alarm-channel-pagerduty-fns.tsindex 5978b7d180..7eae6d5f16 100644--- a/backend/src/services/alarm/channels/alarm-channel-pagerduty-fns.ts+++ b/backend/src/services/alarm/channels/alarm-channel-pagerduty-fns.ts@@ -9,13 +9,15 @@ import {PagerDutyChannelConfigSchema,pagerDutyIntegrationKeyRegex,TAlarmChannelSendContext,+ TAlarmItem,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;+const MAX_INCIDENTS_PER_RUN = 10;+const PAGERDUTY_SUMMARY_MAX_LENGTH = 1024;type TPagerDutyPayload = {routing_key: string;@@ -32,44 +34,42 @@ type TPagerDutyPayload = {custom_details: {alarm_name: string;condition?: string;- total_items: number;- items: Array<{ title: string; identifier?: string; fields: Record<string, string> }>;+ 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" }]- };-};+export const buildPagerDutyEvent = (+ payload: TAlarmPayload,+ item: TAlarmItem,+ integrationKey: string+): TPagerDutyPayload => ({+ routing_key: integrationKey,+ event_action: "trigger",+ dedup_key: `${payload.alarm.id}:${item.id}`,+ payload: {+ summary: `${payload.summary} — ${item.title}`.slice(0, PAGERDUTY_SUMMARY_MAX_LENGTH),+ 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 } : {}),+ 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;@@ -89,14 +89,10 @@ const triggerPagerDutyEvent = async (payload: TPagerDutyPayload): Promise<void>});};-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 triggerPagerDutyEventWithRetry = async (+ payload: TPagerDutyPayload,+ channelId: string+): Promise<TChannelResult> => {const { maxRetries, delayMs } = ALARM_CHANNEL_RETRY_CONFIG;let lastError: AxiosError | undefined;@@ -110,21 +106,15 @@ export const sendPagerDutyNotification = async (ctx: TAlarmChannelSendContext):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}]`+ { channelId, statusCode: lastError.response?.status, error: lastError.message },+ `Alarm PagerDuty error is not retryable (4xx or non-transient) [channelId=${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}]`+ { channelId, attempt, maxRetries, statusCode: lastError.response?.status, error: lastError.message },+ `Alarm PagerDuty failed, ${attempt < maxRetries ? `retrying in ${delayMs}ms` : "no more retries"} [channelId=${channelId}]`);if (attempt < maxRetries) {@@ -136,3 +126,31 @@ export const sendPagerDutyNotification = async (ctx: TAlarmChannelSendContext):return { success: false, error: lastError?.message };};++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 items = ctx.payload.items.slice(0, MAX_INCIDENTS_PER_RUN);+ if (ctx.payload.items.length > MAX_INCIDENTS_PER_RUN) {+ logger.warn(+ { channelId: ctx.channelId, total: ctx.payload.items.length, cap: MAX_INCIDENTS_PER_RUN },+ `Alarm PagerDuty target count exceeds cap; only the first ${MAX_INCIDENTS_PER_RUN} incidents are triggered this run [channelId=${ctx.channelId}]`+ );+ }++ const results = await Promise.all(+ items.map((item) =>+ triggerPagerDutyEventWithRetry(buildPagerDutyEvent(ctx.payload, item, config.integrationKey), ctx.channelId)+ )+ );++ const errors = results.filter((result) => !result.success && result.error).map((result) => result.error);+ if (errors.length > 0) {+ return { success: false, error: errors.join("; ") };+ }+ return { success: true };+};diff --git a/backend/src/services/alarm/channels/alarm-channels.test.ts b/backend/src/services/alarm/channels/alarm-channels.test.tsindex 36497efe0d..64219cc2b8 100644--- a/backend/src/services/alarm/channels/alarm-channels.test.ts+++ b/backend/src/services/alarm/channels/alarm-channels.test.ts@@ -1,6 +1,6 @@import { AlarmChannelType, TAlarmPayload } from "../alarm-channel-types";import { sendEmailNotification } from "./alarm-channel-email-fns";-import { buildPagerDutyPayload } from "./alarm-channel-pagerduty-fns";+import { buildPagerDutyEvent } 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";@@ -100,14 +100,26 @@ describe("buildSlackPayload", () => {});});-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");+describe("buildPagerDutyEvent", () => {+ test("uses a per-target dedup key so each target is its own incident", () => {+ const payload = samplePayload();+ const first = buildPagerDutyEvent(payload, payload.items[0], "a".repeat(32));+ const second = buildPagerDutyEvent(payload, payload.items[1], "a".repeat(32));++ expect(first.dedup_key).toBe("alarm-1:cert-a");+ expect(second.dedup_key).toBe("alarm-1:cert-b");+ expect(first.dedup_key).not.toBe(second.dedup_key);+ });++ test("carries provider severity and the target's own fields", () => {+ const payload = samplePayload();+ const pd = buildPagerDutyEvent(payload, payload.items[0], "a".repeat(32));+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");+ expect(pd.payload.custom_details.title).toBe("api.prod.example.com");+ expect(pd.payload.custom_details.identifier).toBe("4B:3E:2F:A1");+ expect(pd.payload.custom_details.fields.Expires).toBe("2025-11-12");});});