Skip to content

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

fix inconsistencies

Thiago Araujo da Silvaf4bcbf28d295
diff --git a/backend/src/services/alarm/alarm-channel-dal.ts b/backend/src/services/alarm/alarm-channel-dal.ts
index 1568afd8ea..2b655c31f3 100644
--- a/backend/src/services/alarm/alarm-channel-dal.ts
+++ b/backend/src/services/alarm/alarm-channel-dal.ts
@@ -47,19 +47,10 @@ export const alarmChannelDALFactory = (db: TDbClient) => {
}
};
- 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,
- findByAlarmIds,
- deleteByAlarmId
+ findByAlarmIds
};
};
diff --git a/backend/src/services/alarm/alarm-channel-types.ts b/backend/src/services/alarm/alarm-channel-types.ts
index 74e272f822..029f569557 100644
--- a/backend/src/services/alarm/alarm-channel-types.ts
+++ b/backend/src/services/alarm/alarm-channel-types.ts
@@ -63,6 +63,7 @@ export type TAlarmChannelDefinition = {
directed: boolean;
secretFields: string[];
configSchema: z.ZodTypeAny;
+ maxTargetsPerRun?: number;
send: (ctx: TAlarmChannelSendContext) => Promise<TChannelResult>;
};
diff --git a/backend/src/services/alarm/alarm-engine.test.ts b/backend/src/services/alarm/alarm-engine.test.ts
index f8a40832a4..312d5df4ae 100644
--- a/backend/src/services/alarm/alarm-engine.test.ts
+++ b/backend/src/services/alarm/alarm-engine.test.ts
@@ -12,6 +12,12 @@ vi.mock("@app/lib/logger", () => ({
initLogger: () => {}
}));
+// Stub outbound HTTP so PagerDuty/Slack/webhook sends resolve without a real network call.
+vi.mock("@app/lib/validator", async (importActual) => ({
+ ...(await importActual<typeof import("@app/lib/validator")>()),
+ safeRequest: { post: async () => ({ data: {} }) }
+}));
+
type TTarget = { id: string };
const RESOURCE_TYPE = "test.resource";
@@ -77,6 +83,7 @@ const buildEngine = (opts: {
recentlyAlarmed?: Array<{ channelId: string; targetId: string }>;
recipients?: Array<{ userId: string; email: string; firstName?: string | null }>;
failEmail?: boolean;
+ failEmailFor?: string;
}) => {
const registry = alarmProviderRegistryFactory();
registry.register(makeProvider(opts.targets) as IResourceAlarmProvider);
@@ -120,6 +127,7 @@ const buildEngine = (opts: {
smtpService: {
sendMail: async (opt: { recipients: string[] }) => {
if (opts.failEmail) throw new Error("smtp down");
+ if (opts.failEmailFor && opt.recipients.includes(opts.failEmailFor)) throw new Error("mailbox unavailable");
sentMail.push({ recipients: opt.recipients });
}
}
@@ -198,6 +206,91 @@ describe("alarm engine", () => {
]);
});
+ test("marks a directed channel SUCCESS when at least one recipient delivers, so healthy recipients are not re-spammed", async () => {
+ const { engine, sentMail, historyWrites } = buildEngine({
+ targets: [{ id: "t1" }],
+ channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }],
+ recipients: [
+ { userId: "u1", email: "[email protected]" },
+ { userId: "u2", email: "[email protected]" }
+ ],
+ failEmailFor: "[email protected]"
+ });
+
+ await engine.runAlarm(makeAlarm());
+
+ // The healthy recipient still got the mail.
+ expect(sentMail.flatMap((m) => m.recipients)).toEqual(["[email protected]"]);
+ // The target is recorded SUCCESS despite the one bounce, so it won't re-fire (and re-spam the
+ // healthy recipient) on the next run.
+ expect(historyWrites).toHaveLength(1);
+ expect(historyWrites[0].deliveries).toEqual([
+ { targetId: "t1", channelId: "c-email", channelType: "email", status: AlarmRunStatus.SUCCESS }
+ ]);
+ });
+
+ test("fails a directed channel with no resolved recipients instead of dispatching to undefined", async () => {
+ const { engine, sentMail, historyWrites } = buildEngine({
+ targets: [{ id: "t1" }],
+ channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }],
+ recipients: [] // group emptied / user deleted at runtime
+ });
+
+ await engine.runAlarm(makeAlarm());
+
+ // No send is attempted with an undefined recipient.
+ 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("caps a per-target channel (PagerDuty) at maxTargetsPerRun and defers the rest instead of marking them delivered", async () => {
+ const { engine, historyWrites } = buildEngine({
+ targets: Array.from({ length: 15 }, (_, i) => ({ id: `t${i}` })),
+ channels: [
+ {
+ id: "c-pd",
+ channelType: "pagerduty",
+ encryptedConfig: encConfig({ integrationKey: "a".repeat(32) }),
+ enabled: true
+ }
+ ]
+ });
+
+ await engine.runAlarm(makeAlarm());
+
+ expect(historyWrites).toHaveLength(1);
+ // Only the first 10 targets are dispatched and recorded; the other 5 get no history row, so they
+ // are re-evaluated and paged on the next run rather than being silently marked delivered.
+ expect(historyWrites[0].deliveries).toHaveLength(10);
+ expect(historyWrites[0].deliveries.map((d) => d.targetId)).toEqual(Array.from({ length: 10 }, (_, i) => `t${i}`));
+ expect(historyWrites[0].deliveries.every((d) => d.status === AlarmRunStatus.SUCCESS)).toBe(true);
+ });
+
+ test("pages the deferred targets on a later run once the first batch is deduped", async () => {
+ const { engine, historyWrites } = buildEngine({
+ targets: Array.from({ length: 15 }, (_, i) => ({ id: `t${i}` })),
+ channels: [
+ {
+ id: "c-pd",
+ channelType: "pagerduty",
+ encryptedConfig: encConfig({ integrationKey: "a".repeat(32) }),
+ enabled: true
+ }
+ ],
+ // First 10 already delivered on the previous run.
+ recentlyAlarmed: Array.from({ length: 10 }, (_, i) => ({ channelId: "c-pd", targetId: `t${i}` }))
+ });
+
+ await engine.runAlarm(makeAlarm());
+
+ expect(historyWrites).toHaveLength(1);
+ expect(historyWrites[0].deliveries.map((d) => d.targetId)).toEqual(["t10", "t11", "t12", "t13", "t14"]);
+ });
+
test("skips entirely when every channel already delivered every target", async () => {
const { engine, historyWrites, sentMail } = buildEngine({
targets: [{ id: "t1" }],
diff --git a/backend/src/services/alarm/alarm-engine.ts b/backend/src/services/alarm/alarm-engine.ts
index 2759defde0..2afe128e3b 100644
--- a/backend/src/services/alarm/alarm-engine.ts
+++ b/backend/src/services/alarm/alarm-engine.ts
@@ -96,10 +96,18 @@ export const alarmEngineFactory = ({
const alarmedSet = new Set(recentlyAlarmed.map((row) => `${row.channelId}:${row.targetId}`));
const channelWork = channels
- .map((channel) => ({
- channel,
- dueTargets: targets.filter((target) => !alarmedSet.has(`${channel.id}:${provider.targetId(target)}`))
- }))
+ .map((channel) => {
+ const definition = ALARM_CHANNEL_REGISTRY[channel.channelType as AlarmChannelType];
+ const dueTargets = targets.filter((target) => !alarmedSet.has(`${channel.id}:${provider.targetId(target)}`));
+ const cap = definition?.maxTargetsPerRun;
+ if (cap && dueTargets.length > cap) {
+ logger.info(
+ `Alarm ${channel.channelType} channel capped at ${cap} targets this run; ${dueTargets.length - cap} deferred to the next run [alarmId=${alarm.id}] [channelId=${channel.id}]`
+ );
+ return { channel, dueTargets: dueTargets.slice(0, cap) };
+ }
+ return { channel, dueTargets };
+ })
.filter((work) => work.dueTargets.length > 0);
if (channelWork.length === 0) return;
@@ -114,8 +122,9 @@ export const alarmEngineFactory = ({
condition: alarm.condition,
filters: alarm.filters
};
- // viewUrl is target-independent; build one reference payload to source it for the failure notice.
- const { viewUrl } = provider.buildPayload(alarmContext, targets).alarm;
+ // viewUrl is target-independent; pass no targets so we don't build the full item list (which is
+ // discarded here) just to read the link used in the failure notice.
+ const { viewUrl } = provider.buildPayload(alarmContext, []).alarm;
const { decryptor } = await getAlarmChannelCipher(kmsService, {
orgId: alarm.orgId,
@@ -151,16 +160,25 @@ export const alarmEngineFactory = ({
try {
if (definition.directed) {
- const deliveries = recipients.length > 0 ? recipients : [undefined];
+ if (recipients.length === 0) {
+ return { ...base, success: false, error: "No recipients could be resolved for this channel" };
+ }
const results = await Promise.all(
- deliveries.map((recipient) =>
+ recipients.map((recipient) =>
definition.send({ channelId: channel.id, config, payload, recipient, deps })
)
);
const failures = results.filter((result) => !result.success);
- if (failures.length > 0) {
+ if (failures.length === results.length) {
return { ...base, success: false, error: failures.map((f) => f.error).join("; ") };
}
+ if (failures.length > 0) {
+ logger.warn(
+ `Alarm ${channel.channelType} channel had partial delivery failures [alarmId=${alarm.id}] [channelId=${channel.id}]: ${failures
+ .map((f) => f.error)
+ .join("; ")}`
+ );
+ }
return { ...base, success: true };
}
diff --git a/backend/src/services/alarm/alarm-queue.ts b/backend/src/services/alarm/alarm-queue.ts
index 04495846d9..0397a82369 100644
--- a/backend/src/services/alarm/alarm-queue.ts
+++ b/backend/src/services/alarm/alarm-queue.ts
@@ -42,7 +42,7 @@ export const alarmQueueServiceFactory = ({
{
jobId: `alarm-dispatch-${alarm.id}`,
removeOnComplete: true,
- removeOnFail: { count: 5 },
+ removeOnFail: true,
attempts: 1
}
)
diff --git a/backend/src/services/alarm/alarm-service.test.ts b/backend/src/services/alarm/alarm-service.test.ts
index d0679c6e8e..668030ee04 100644
--- a/backend/src/services/alarm/alarm-service.test.ts
+++ b/backend/src/services/alarm/alarm-service.test.ts
@@ -85,9 +85,26 @@ const buildService = (opts?: {
},
findByAlarmId: async (alarmId: string) => channels.get(alarmId) ?? [],
findByAlarmIds: async (alarmIds: string[]) => alarmIds.flatMap((alarmId) => channels.get(alarmId) ?? []),
- deleteByAlarmId: async (alarmId: string) => {
- channels.delete(alarmId);
- return 0;
+ updateById: async (id: string, data: Record<string, unknown>) => {
+ for (const [alarmId, rows] of channels) {
+ const idx = rows.findIndex((c) => c.id === id);
+ if (idx >= 0) {
+ rows[idx] = { ...rows[idx], ...data, updatedAt: new Date() };
+ channels.set(alarmId, rows);
+ return rows[idx];
+ }
+ }
+ return undefined;
+ },
+ delete: async (filter: { $in?: { id?: string[] } }) => {
+ const ids = new Set(filter.$in?.id ?? []);
+ for (const [alarmId, rows] of channels) {
+ channels.set(
+ alarmId,
+ rows.filter((c) => !ids.has(c.id as string))
+ );
+ }
+ return [];
}
},
alarmRecipientDAL: {
@@ -394,6 +411,26 @@ describe("alarm service", () => {
expect(updated.channels[0].config).toEqual({ hasWebhookUrl: true });
});
+ test("preserves the channel id when an existing channel is edited so dedup history stays intact", async () => {
+ const { service, channels } = seedAlarmWithChannel(AlarmChannelType.WEBHOOK, {
+ url: "https://example.com/hook"
+ });
+
+ const updated = await service.updateAlarm({
+ alarmId: "alarm-1",
+ channels: [
+ { id: "c0", channelType: AlarmChannelType.WEBHOOK, config: { url: "https://example.com/hook" }, enabled: false }
+ ],
+ ...actor
+ });
+
+ // The channel must keep its original id (not be deleted + recreated with a fresh UUID), otherwise
+ // alarm_history_target.channelId would no longer match and per-channel dedup would reset.
+ expect(updated.channels[0].id).toBe("c0");
+ expect(updated.channels[0].enabled).toBe(false);
+ expect((channels.get("alarm-1") ?? []).map((c) => c.id)).toEqual(["c0"]);
+ });
+
test("does not fabricate a secret for a newly added channel (no id)", async () => {
const { service } = seedAlarmWithChannel(AlarmChannelType.WEBHOOK, {
url: "https://old.example.com/hook",
diff --git a/backend/src/services/alarm/alarm-service.ts b/backend/src/services/alarm/alarm-service.ts
index 4216a4dbd9..c7c9f5da9d 100644
--- a/backend/src/services/alarm/alarm-service.ts
+++ b/backend/src/services/alarm/alarm-service.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-import { TAlarmChannels, TAlarmRecipients, TAlarms } from "@app/db/schemas";
+import { TAlarmChannels, TAlarmChannelsInsert, TAlarmRecipients, TAlarms } from "@app/db/schemas";
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -33,7 +33,10 @@ import { ALARM_CHANNEL_REGISTRY } from "./channels/alarm-channel-registry";
export type TAlarmServiceFactoryDep = {
alarmDAL: TAlarmDALFactory;
- alarmChannelDAL: Pick<TAlarmChannelDALFactory, "insertMany" | "findByAlarmId" | "findByAlarmIds" | "deleteByAlarmId">;
+ alarmChannelDAL: Pick<
+ TAlarmChannelDALFactory,
+ "insertMany" | "findByAlarmId" | "findByAlarmIds" | "updateById" | "delete"
+ >;
alarmRecipientDAL: Pick<
TAlarmRecipientDALFactory,
"insertMany" | "findByAlarmId" | "findByAlarmIds" | "deleteByAlarmId"
@@ -138,9 +141,12 @@ export const alarmServiceFactory = ({
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 email channels" });
+ const directedChannels = input.channels.filter(
+ (channel) => ALARM_CHANNEL_REGISTRY[channel.channelType]?.directed
+ );
+ if (directedChannels.length > 0 && (input.recipients ?? []).length === 0) {
+ const directedTypes = [...new Set(directedChannels.map((channel) => channel.channelType))].join(", ");
+ throw new BadRequestError({ message: `At least one recipient is required for ${directedTypes} channels` });
}
for (const channel of input.channels) {
@@ -505,16 +511,32 @@ export const alarmServiceFactory = ({
);
if (resolvedChannels) {
- await alarmChannelDAL.deleteByAlarmId(alarm.id, tx);
- await alarmChannelDAL.insertMany(
- resolvedChannels.map((channel) => ({
- alarmId: alarm.id,
- channelType: channel.channelType,
- encryptedConfig: encryptChannelConfig(channel.config, encryptor),
- enabled: channel.enabled ?? true
- })),
- tx
- );
+ const existingChannels = await alarmChannelDAL.findByAlarmId(alarm.id, tx);
+ const existingChannelById = new Map(existingChannels.map((channel) => [channel.id, channel]));
+
+ const keptIds = new Set<string>();
+ const toInsert: TAlarmChannelsInsert[] = [];
+
+ for (const channel of resolvedChannels) {
+ const existing = channel.id ? existingChannelById.get(channel.id) : undefined;
+ const encryptedConfig = encryptChannelConfig(channel.config, encryptor);
+ if (existing && existing.channelType === channel.channelType) {
+ keptIds.add(existing.id);
+ // eslint-disable-next-line no-await-in-loop
+ await alarmChannelDAL.updateById(existing.id, { encryptedConfig, enabled: channel.enabled ?? true }, tx);
+ } else {
+ toInsert.push({
+ alarmId: alarm.id,
+ channelType: channel.channelType,
+ encryptedConfig,
+ enabled: channel.enabled ?? true
+ });
+ }
+ }
+
+ const idsToDelete = existingChannels.filter((channel) => !keptIds.has(channel.id)).map((channel) => channel.id);
+ if (idsToDelete.length) await alarmChannelDAL.delete({ $in: { id: idsToDelete } }, tx);
+ if (toInsert.length) await alarmChannelDAL.insertMany(toInsert, tx);
}
if (dto.recipients) {
diff --git a/backend/src/services/alarm/channels/alarm-channel-pagerduty-fns.ts b/backend/src/services/alarm/channels/alarm-channel-pagerduty-fns.ts
index 26845a10ab..a3b2d14bf7 100644
--- a/backend/src/services/alarm/channels/alarm-channel-pagerduty-fns.ts
+++ b/backend/src/services/alarm/channels/alarm-channel-pagerduty-fns.ts
@@ -1,6 +1,5 @@
import { AxiosError } from "axios";
-import { logger } from "@app/lib/logger";
import { safeRequest } from "@app/lib/validator";
import { RETRYABLE_NETWORK_ERRORS } from "../alarm-channel-constants";
@@ -16,7 +15,7 @@ import { retryWithBackoff } from "./alarm-channel-retry-fns";
const PAGERDUTY_EVENTS_URL = "https://events.pagerduty.com/v2/enqueue";
const PAGERDUTY_TIMEOUT = 7 * 1000;
-const MAX_INCIDENTS_PER_RUN = 10;
+export const PAGERDUTY_MAX_INCIDENTS_PER_RUN = 10;
const PAGERDUTY_SUMMARY_MAX_LENGTH = 1024;
type TPagerDutyPayload = {
@@ -97,16 +96,8 @@ export const sendPagerDutyNotification = async (ctx: TAlarmChannelSendContext):
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) =>
+ ctx.payload.items.map((item) =>
retryWithBackoff(
() => triggerPagerDutyEvent(buildPagerDutyEvent(ctx.payload, item, config.integrationKey)),
isPagerDutyErrorRetryable,
diff --git a/backend/src/services/alarm/channels/alarm-channel-registry.ts b/backend/src/services/alarm/channels/alarm-channel-registry.ts
index 140dc55150..3398d562e3 100644
--- a/backend/src/services/alarm/channels/alarm-channel-registry.ts
+++ b/backend/src/services/alarm/channels/alarm-channel-registry.ts
@@ -7,7 +7,7 @@ import {
WebhookChannelConfigSchema
} from "../alarm-channel-types";
import { sendEmailNotification } from "./alarm-channel-email-fns";
-import { sendPagerDutyNotification } from "./alarm-channel-pagerduty-fns";
+import { PAGERDUTY_MAX_INCIDENTS_PER_RUN, sendPagerDutyNotification } from "./alarm-channel-pagerduty-fns";
import { sendSlackNotification } from "./alarm-channel-slack-fns";
import { sendWebhookNotification } from "./alarm-channel-webhook-fns";
@@ -38,6 +38,7 @@ export const ALARM_CHANNEL_REGISTRY: Record<AlarmChannelType, TAlarmChannelDefin
directed: false,
secretFields: ["integrationKey"],
configSchema: PagerDutyChannelConfigSchema,
+ maxTargetsPerRun: PAGERDUTY_MAX_INCIDENTS_PER_RUN,
send: sendPagerDutyNotification
}
};
diff --git a/backend/src/services/alarm/channels/alarm-channel-retry-fns.ts b/backend/src/services/alarm/channels/alarm-channel-retry-fns.ts
index 73ed33741f..7e8c2bf4cd 100644
--- a/backend/src/services/alarm/channels/alarm-channel-retry-fns.ts
+++ b/backend/src/services/alarm/channels/alarm-channel-retry-fns.ts
@@ -49,6 +49,7 @@ export const retryWithBackoff = async (
export const isAxiosErrorRetryable = (err: unknown): boolean => {
const axiosErr = err as AxiosError;
const status = axiosErr.response?.status;
+ if (status === 429) return true;
if (status && status >= 500) return true;
if (axiosErr.code && RETRYABLE_NETWORK_ERRORS.includes(axiosErr.code)) return true;
if (axiosErr.message?.toLowerCase().includes("timeout")) return true;
diff --git a/backend/src/services/alarm/channels/alarm-channel-slack-fns.ts b/backend/src/services/alarm/channels/alarm-channel-slack-fns.ts
index 10147310ac..b6e1bac483 100644
--- a/backend/src/services/alarm/channels/alarm-channel-slack-fns.ts
+++ b/backend/src/services/alarm/channels/alarm-channel-slack-fns.ts
@@ -1,4 +1,3 @@
-import { BadRequestError } from "@app/lib/errors";
import { safeRequest } from "@app/lib/validator";
import {
@@ -42,18 +41,6 @@ const SEVERITY_COLOR: Record<TAlarmSeverity, string> = {
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);
@@ -126,7 +113,6 @@ const triggerSlackWebhook = async (url: string, payload: TSlackPayload): Promise
export const sendSlackNotification = async (ctx: TAlarmChannelSendContext): Promise<TChannelResult> => {
const config = SlackChannelConfigSchema.parse(ctx.config);
- validateSlackWebhookUrl(config.webhookUrl);
const payload = buildSlackPayload(ctx.payload);
return retryWithBackoff(() => triggerSlackWebhook(config.webhookUrl, payload), isAxiosErrorRetryable, {
diff --git a/backend/src/services/alarm/channels/alarm-channels.test.ts b/backend/src/services/alarm/channels/alarm-channels.test.ts
index 64219cc2b8..0bc001d012 100644
--- a/backend/src/services/alarm/channels/alarm-channels.test.ts
+++ b/backend/src/services/alarm/channels/alarm-channels.test.ts
@@ -1,8 +1,9 @@
-import { AlarmChannelType, TAlarmPayload } from "../alarm-channel-types";
+import { AlarmChannelType, SlackChannelConfigSchema, TAlarmPayload } from "../alarm-channel-types";
import { sendEmailNotification } from "./alarm-channel-email-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 { isAxiosErrorRetryable } from "./alarm-channel-retry-fns";
+import { buildSlackPayload } from "./alarm-channel-slack-fns";
import { buildWebhookPayload } from "./alarm-channel-webhook-fns";
const samplePayload = (): TAlarmPayload => ({
@@ -123,13 +124,21 @@ describe("buildPagerDutyEvent", () => {
});
});
-describe("validateSlackWebhookUrl", () => {
+describe("SlackChannelConfigSchema webhook allowlist", () => {
test("rejects a lookalike host", () => {
- expect(() => validateSlackWebhookUrl("https://hooks.slack.com.evil.com/x")).toThrow();
+ expect(SlackChannelConfigSchema.safeParse({ webhookUrl: "https://hooks.slack.com.evil.com/x" }).success).toBe(
+ false
+ );
});
test("rejects non-https", () => {
- expect(() => validateSlackWebhookUrl("http://hooks.slack.com/x")).toThrow();
+ expect(SlackChannelConfigSchema.safeParse({ webhookUrl: "http://hooks.slack.com/x" }).success).toBe(false);
+ });
+
+ test("accepts a valid hooks.slack.com https URL", () => {
+ expect(SlackChannelConfigSchema.safeParse({ webhookUrl: "https://hooks.slack.com/services/T/B/x" }).success).toBe(
+ true
+ );
});
});
@@ -179,3 +188,20 @@ describe("sendEmailNotification (directed)", () => {
expect(result.success).toBe(false);
});
});
+
+describe("isAxiosErrorRetryable", () => {
+ test("retries on 429 (rate limit) so a short backoff can recover", () => {
+ expect(isAxiosErrorRetryable({ response: { status: 429 } })).toBe(true);
+ });
+
+ test("retries on 5xx and network/timeout errors", () => {
+ expect(isAxiosErrorRetryable({ response: { status: 503 } })).toBe(true);
+ expect(isAxiosErrorRetryable({ code: "ECONNRESET" })).toBe(true);
+ expect(isAxiosErrorRetryable({ message: "socket hang up timeout" })).toBe(true);
+ });
+
+ test("does not retry on other 4xx client errors", () => {
+ expect(isAxiosErrorRetryable({ response: { status: 400 } })).toBe(false);
+ expect(isAxiosErrorRetryable({ response: { status: 404 } })).toBe(false);
+ });
+});
diff --git a/backend/src/services/alarm/providers/identity-credential-alarm-dal.ts b/backend/src/services/alarm/providers/identity-credential-alarm-dal.ts
index 131e6592d5..255cb20660 100644
--- a/backend/src/services/alarm/providers/identity-credential-alarm-dal.ts
+++ b/backend/src/services/alarm/providers/identity-credential-alarm-dal.ts
@@ -19,9 +19,10 @@ export const identityCredentialAlarmDALFactory = (db: TDbClient) => {
const findExpiringUaClientSecrets = async (
{
orgId,
+ projectId,
identityId,
alertBeforeInterval
- }: { orgId: string; identityId?: string | null; alertBeforeInterval: string },
+ }: { orgId: string; projectId?: string | null; identityId?: string | null; alertBeforeInterval: string },
tx?: Knex
): Promise<TExpiringUaClientSecret[]> => {
try {
@@ -45,6 +46,16 @@ export const identityCredentialAlarmDALFactory = (db: TDbClient) => {
.whereRaw(`${expiresAtSql} > NOW()`)
.whereRaw(`${expiresAtSql} <= NOW() + ?::interval`, [alertBeforeInterval]);
+ if (projectId) {
+ void query
+ .join(
+ TableName.IdentityProjectMembership,
+ `${TableName.IdentityUniversalAuth}.identityId`,
+ `${TableName.IdentityProjectMembership}.identityId`
+ )
+ .where(`${TableName.IdentityProjectMembership}.projectId`, projectId);
+ }
+
if (identityId) {
void query.where(`${TableName.IdentityUniversalAuth}.identityId`, identityId);
}
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
index 26d10e0275..90d77e3de0 100644
--- a/backend/src/services/alarm/providers/identity-credential-alarm-provider.test.ts
+++ b/backend/src/services/alarm/providers/identity-credential-alarm-provider.test.ts
@@ -40,7 +40,12 @@ const alarmContext = (overrides: Partial<TAlarmContext> = {}): TAlarmContext =>
const buildProvider = (opts?: {
secrets?: TExpiringUaClientSecret[];
- onFind?: (args: { orgId: string; identityId?: string | null; alertBeforeInterval: string }) => void;
+ onFind?: (args: {
+ orgId: string;
+ projectId?: string | null;
+ identityId?: string | null;
+ alertBeforeInterval: string;
+ }) => void;
abilityRules?: { action: string; subject: string }[];
inOrg?: boolean;
inProject?: boolean;
@@ -48,6 +53,7 @@ const buildProvider = (opts?: {
const dal = {
findExpiringUaClientSecrets: async (args: {
orgId: string;
+ projectId?: string | null;
identityId?: string | null;
alertBeforeInterval: string;
}) => {
@@ -80,7 +86,7 @@ describe("identity credential alarm provider", () => {
});
test("findDueTargets converts alertBefore to a postgres interval and tags credential type", async () => {
- let seenArgs: { alertBeforeInterval: string; identityId?: string | null } | undefined;
+ let seenArgs: { alertBeforeInterval: string; projectId?: string | null; identityId?: string | null } | undefined;
const provider = buildProvider({
secrets: [sampleSecret()],
onFind: (args) => {
@@ -102,6 +108,26 @@ describe("identity credential alarm provider", () => {
expect(provider.targetId(targets[0])).toBe("ua-client-secret:sec-1");
});
+ test("findDueTargets scopes the query to the alarm's project so it cannot leak org-wide credentials", async () => {
+ let seenArgs: { projectId?: string | null } | undefined;
+ const provider = buildProvider({
+ onFind: (args) => {
+ seenArgs = args;
+ }
+ });
+
+ await provider.findDueTargets({
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: null,
+ eventType: IDENTITY_CREDENTIAL_EXPIRY_EVENT,
+ condition: { alertBefore: "30d" },
+ filters: null
+ });
+
+ expect(seenArgs?.projectId).toBe("proj-1");
+ });
+
test("buildPayload produces neutral items and severity", () => {
const provider = buildProvider();
const target = { credentialType: "ua-client-secret" as const, ...sampleSecret({ expiresAt: futureDate(3) }) };
diff --git a/backend/src/services/alarm/providers/identity-credential-alarm-provider.ts b/backend/src/services/alarm/providers/identity-credential-alarm-provider.ts
index 824e2cf2a1..70c5903bbd 100644
--- a/backend/src/services/alarm/providers/identity-credential-alarm-provider.ts
+++ b/backend/src/services/alarm/providers/identity-credential-alarm-provider.ts
@@ -78,6 +78,7 @@ export const identityCredentialAlarmProviderFactory = ({
const uaSecrets = await identityCredentialAlarmDAL.findExpiringUaClientSecrets({
orgId: input.orgId,
+ projectId: input.projectId,
identityId: input.resourceId,
alertBeforeInterval: intervalSql
});