Skip to content

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

disable channel if no more recipients

Thiago Araujo da Silvaaa7cfae6dea7
diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.ts
index 7a9007b6ac..774c680069 100644
--- a/backend/src/lib/telemetry/metrics.ts
+++ b/backend/src/lib/telemetry/metrics.ts
@@ -620,6 +620,10 @@ export enum AlertDispatchOutcome {
NoDueTargets = "no_due_targets",
// The alert has no enabled channels, so the run is skipped before scanning for targets.
NoChannels = "no_channels",
+ // Every channel in the run was directed (email) with no resolvable recipient — the recipients left
+ // the org, or the recipient group emptied out. Customer config drift, not a delivery fault, so it
+ // is kept out of delivery_failed and must not alarm.
+ NoRecipients = "no_recipients",
// Targets matched, but every one had already been alerted inside the dedup window.
AllDeduped = "all_deduped"
}
diff --git a/backend/src/services/alert/alert-channel-recipient-dal.test.ts b/backend/src/services/alert/alert-channel-recipient-dal.test.ts
index e9a2ca8d8a..832cc2d1eb 100644
--- a/backend/src/services/alert/alert-channel-recipient-dal.test.ts
+++ b/backend/src/services/alert/alert-channel-recipient-dal.test.ts
@@ -1,22 +1,61 @@
import { TableName } from "@app/db/schemas";
import { alertChannelRecipientDALFactory } from "./alert-channel-recipient-dal";
+import { AlertChannelType } from "./alert-channel-types";
import { AlertPrincipalType } from "./alert-types";
+type TChannelQueryLog = {
+ where: unknown[][];
+ whereIn: unknown[][];
+ notExistsSubqueries: number;
+ update?: Record<string, unknown>;
+};
+
// Records query-builder calls so we can assert the scope cleanup filters correctly without a DB.
-const buildDAL = () => {
+const buildDAL = (opts: { deletedChannelIds?: string[] } = {}) => {
+ const deletedChannelIds = opts.deletedChannelIds ?? ["c1", "c2"];
+
const calls = {
- channelWhere: [] as unknown[][],
recipientWhere: [] as unknown[][],
- recipientWhereIn: [] as unknown[][]
+ recipientWhereIn: [] as unknown[][],
+ channelQueries: [] as TChannelQueryLog[]
};
- const channelChain = {
- select: () => channelChain,
- where: (...args: unknown[]) => {
- calls.channelWhere.push(args);
- return channelChain;
- }
+
+ // The AlertChannel table is hit for two unrelated things — the channel-scoping subquery and the
+ // disable-empty-channels update — so each invocation gets its own log, classified by whether it
+ // ended in an update.
+ const channelChain = () => {
+ const log: TChannelQueryLog = { where: [], whereIn: [], notExistsSubqueries: 0 };
+ calls.channelQueries.push(log);
+
+ const subquery = {
+ select: () => subquery,
+ from: () => subquery,
+ whereRaw: () => subquery
+ };
+ const chain = {
+ select: () => chain,
+ where: (...args: unknown[]) => {
+ log.where.push(args);
+ return chain;
+ },
+ whereIn: (...args: unknown[]) => {
+ log.whereIn.push(args);
+ return chain;
+ },
+ whereNotExists: (cb: (qb: typeof subquery) => void) => {
+ log.notExistsSubqueries += 1;
+ cb(subquery);
+ return chain;
+ },
+ update: async (patch: Record<string, unknown>) => {
+ log.update = patch;
+ return 1;
+ }
+ };
+ return chain;
};
+
const recipientChain = {
where: (...args: unknown[]) => {
calls.recipientWhere.push(args);
@@ -26,31 +65,44 @@ const buildDAL = () => {
calls.recipientWhereIn.push(args);
return recipientChain;
},
- del: async () => 2
+ del: () => ({
+ returning: async () => deletedChannelIds.map((channelId) => ({ channelId }))
+ })
};
- const db = ((table: string) => (table === TableName.AlertChannel ? channelChain : recipientChain)) as never;
- return { dal: alertChannelRecipientDALFactory(db), calls };
+ const db = ((table: string) =>
+ table === TableName.AlertChannel ? channelChain() : recipientChain) as unknown as Parameters<
+ typeof alertChannelRecipientDALFactory
+ >[0];
+ (db as unknown as { raw: (value: string) => string }).raw = (value: string) => value;
+
+ const scopeQueries = () => calls.channelQueries.filter((query) => !query.update);
+ const disableQueries = () => calls.channelQueries.filter((query) => query.update);
+
+ return { dal: alertChannelRecipientDALFactory(db), calls, scopeQueries, disableQueries };
};
describe("alert channel recipient dal — scope cleanup", () => {
test("project removal scopes channels by projectId and prunes only USER principals", async () => {
- const { dal, calls } = buildDAL();
+ const { dal, calls, scopeQueries } = buildDAL();
const deleted = await dal.deleteUsersRecipientsByScope({ userIds: ["u1", "u2"], projectId: "proj-1" });
expect(deleted).toBe(2);
- expect(calls.channelWhere).toContainEqual([`${TableName.AlertChannel}.projectId`, "proj-1"]);
+ expect(scopeQueries().flatMap((query) => query.where)).toContainEqual([
+ `${TableName.AlertChannel}.projectId`,
+ "proj-1"
+ ]);
expect(calls.recipientWhere).toContainEqual([`${TableName.AlertChannelRecipient}.principalType`, "user"]);
expect(calls.recipientWhereIn).toContainEqual([`${TableName.AlertChannelRecipient}.principalId`, ["u1", "u2"]]);
});
test("org removal scopes channels by orgId (covers org- and project-scoped channels)", async () => {
- const { dal, calls } = buildDAL();
+ const { dal, scopeQueries } = buildDAL();
await dal.deleteUsersRecipientsByScope({ userIds: ["u1"], orgId: "org-1" });
- expect(calls.channelWhere).toContainEqual([`${TableName.AlertChannel}.orgId`, "org-1"]);
+ expect(scopeQueries().flatMap((query) => query.where)).toContainEqual([`${TableName.AlertChannel}.orgId`, "org-1"]);
});
test("no-op when no users or no scope", async () => {
@@ -58,13 +110,13 @@ describe("alert channel recipient dal — scope cleanup", () => {
expect(await dal.deleteUsersRecipientsByScope({ userIds: [], orgId: "org-1" })).toBe(0);
expect(await dal.deleteUsersRecipientsByScope({ userIds: ["u1"] })).toBe(0);
- expect(calls.channelWhere).toHaveLength(0);
+ expect(calls.channelQueries).toHaveLength(0);
});
});
describe("alert channel recipient dal — deleted principal cleanup", () => {
test("prunes a hard-deleted group's rows everywhere, with no channel scoping", async () => {
- const { dal, calls } = buildDAL();
+ const { dal, calls, scopeQueries } = buildDAL();
const deleted = await dal.deleteByPrincipals({
principalType: AlertPrincipalType.GROUP,
@@ -75,7 +127,7 @@ describe("alert channel recipient dal — deleted principal cleanup", () => {
expect(calls.recipientWhere).toContainEqual([`${TableName.AlertChannelRecipient}.principalType`, "group"]);
expect(calls.recipientWhereIn).toContainEqual([`${TableName.AlertChannelRecipient}.principalId`, ["g1"]]);
// The principal no longer exists anywhere, so its rows are pruned across every org and project.
- expect(calls.channelWhere).toHaveLength(0);
+ expect(scopeQueries()).toHaveLength(0);
});
test("no-op on an empty principal list", async () => {
@@ -83,5 +135,44 @@ describe("alert channel recipient dal — deleted principal cleanup", () => {
expect(await dal.deleteByPrincipals({ principalType: AlertPrincipalType.USER, principalIds: [] })).toBe(0);
expect(calls.recipientWhere).toHaveLength(0);
+ expect(calls.channelQueries).toHaveLength(0);
+ });
+});
+
+describe("alert channel recipient dal — emptied channels", () => {
+ // Rather than deleting a channel (and the alert with it) when its last recipient is pruned, the
+ // channel is disabled so nothing of the user's config is destroyed and the cron stops enqueueing
+ // an alert that would notify nobody.
+ test.each([
+ [
+ "scope cleanup",
+ (dal: ReturnType<typeof buildDAL>["dal"]) => dal.deleteUsersRecipientsByScope({ userIds: ["u1"], orgId: "org-1" })
+ ],
+ [
+ "deleted principal cleanup",
+ (dal: ReturnType<typeof buildDAL>["dal"]) =>
+ dal.deleteByPrincipals({ principalType: AlertPrincipalType.USER, principalIds: ["u1"] })
+ ]
+ ])("disables the directed channels left with no recipients after %s", async (_label, prune) => {
+ const { dal, disableQueries } = buildDAL({ deletedChannelIds: ["c1", "c1", "c2"] });
+
+ await prune(dal);
+
+ const [disable] = disableQueries();
+ expect(disable.update).toEqual({ enabled: false });
+ // Only the channels the prune actually touched, deduplicated.
+ expect(disable.whereIn).toContainEqual([`${TableName.AlertChannel}.id`, ["c1", "c2"]]);
+ // Undirected channels (Slack, webhook, PagerDuty) deliver without recipients, so they are untouched.
+ expect(disable.whereIn).toContainEqual([`${TableName.AlertChannel}.channelType`, [AlertChannelType.EMAIL]]);
+ // Channels that still have other recipients keep running.
+ expect(disable.notExistsSubqueries).toBe(1);
+ });
+
+ test("skips the disable pass when the prune deleted nothing", async () => {
+ const { dal, disableQueries } = buildDAL({ deletedChannelIds: [] });
+
+ await dal.deleteUsersRecipientsByScope({ userIds: ["u1"], orgId: "org-1" });
+
+ expect(disableQueries()).toHaveLength(0);
});
});
diff --git a/backend/src/services/alert/alert-channel-recipient-dal.ts b/backend/src/services/alert/alert-channel-recipient-dal.ts
index 448ef08334..4bfa4bc5f1 100644
--- a/backend/src/services/alert/alert-channel-recipient-dal.ts
+++ b/backend/src/services/alert/alert-channel-recipient-dal.ts
@@ -5,6 +5,7 @@ import { TableName, TAlertChannelRecipients } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex";
+import { DIRECTED_ALERT_CHANNEL_TYPES } from "./alert-channel-types";
import { AlertPrincipalType } from "./alert-types";
export type TAlertChannelRecipientDALFactory = ReturnType<typeof alertChannelRecipientDALFactory>;
@@ -12,6 +13,22 @@ export type TAlertChannelRecipientDALFactory = ReturnType<typeof alertChannelRec
export const alertChannelRecipientDALFactory = (db: TDbClient) => {
const alertChannelRecipientOrm = ormify(db, TableName.AlertChannelRecipient);
+ const $disableChannelsWithoutRecipients = async (channelIds: string[], tx?: Knex): Promise<number> => {
+ if (!channelIds.length) return 0;
+
+ return (tx || db)(TableName.AlertChannel)
+ .whereIn(`${TableName.AlertChannel}.id`, channelIds)
+ .whereIn(`${TableName.AlertChannel}.channelType`, DIRECTED_ALERT_CHANNEL_TYPES)
+ .where(`${TableName.AlertChannel}.enabled`, true)
+ .whereNotExists((qb) => {
+ void qb
+ .select(db.raw("1"))
+ .from(TableName.AlertChannelRecipient)
+ .whereRaw(`"${TableName.AlertChannelRecipient}"."channelId" = "${TableName.AlertChannel}"."id"`);
+ })
+ .update({ enabled: false });
+ };
+
const findByChannelIds = async (channelIds: string[], tx?: Knex): Promise<TAlertChannelRecipients[]> => {
try {
if (!channelIds.length) return [];
@@ -44,10 +61,15 @@ export const alertChannelRecipientDALFactory = (db: TDbClient) => {
try {
if (!principalIds.length) return 0;
- return await (tx || db)(TableName.AlertChannelRecipient)
+ const deleted = (await (tx || db)(TableName.AlertChannelRecipient)
.where(`${TableName.AlertChannelRecipient}.principalType`, principalType)
.whereIn(`${TableName.AlertChannelRecipient}.principalId`, principalIds)
- .del();
+ .del()
+ .returning("channelId")) as { channelId: string }[];
+
+ await $disableChannelsWithoutRecipients([...new Set(deleted.map((row) => row.channelId))], tx);
+
+ return deleted.length;
} catch (error) {
throw new DatabaseError({ error, name: "DeleteByPrincipals" });
}
@@ -64,11 +86,16 @@ export const alertChannelRecipientDALFactory = (db: TDbClient) => {
if (projectId) void channelIds.where(`${TableName.AlertChannel}.projectId`, projectId);
else void channelIds.where(`${TableName.AlertChannel}.orgId`, orgId as string);
- return await (tx || db)(TableName.AlertChannelRecipient)
+ const deleted = (await (tx || db)(TableName.AlertChannelRecipient)
.where(`${TableName.AlertChannelRecipient}.principalType`, AlertPrincipalType.USER)
.whereIn(`${TableName.AlertChannelRecipient}.principalId`, userIds)
.whereIn(`${TableName.AlertChannelRecipient}.channelId`, channelIds)
- .del();
+ .del()
+ .returning("channelId")) as { channelId: string }[];
+
+ await $disableChannelsWithoutRecipients([...new Set(deleted.map((row) => row.channelId))], tx);
+
+ return deleted.length;
} catch (error) {
throw new DatabaseError({ error, name: "DeleteUsersRecipientsByScope" });
}
diff --git a/backend/src/services/alert/alert-channel-types.ts b/backend/src/services/alert/alert-channel-types.ts
index 7b1f35f595..094dcedb44 100644
--- a/backend/src/services/alert/alert-channel-types.ts
+++ b/backend/src/services/alert/alert-channel-types.ts
@@ -10,6 +10,11 @@ export enum AlertChannelType {
PAGERDUTY = "pagerduty"
}
+// Channel types that address individual principals and therefore cannot deliver without recipients.
+// Kept here rather than read off ALERT_CHANNEL_REGISTRY so the DALs don't have to pull in the send
+// implementations; alert-channels.test.ts asserts the two stay in agreement.
+export const DIRECTED_ALERT_CHANNEL_TYPES: AlertChannelType[] = [AlertChannelType.EMAIL];
+
export type TAlertSeverity = "critical" | "error" | "warning" | "info";
export type TAlertItem = {
diff --git a/backend/src/services/alert/alert-engine.test.ts b/backend/src/services/alert/alert-engine.test.ts
index 4d660f3673..7fb99166c0 100644
--- a/backend/src/services/alert/alert-engine.test.ts
+++ b/backend/src/services/alert/alert-engine.test.ts
@@ -330,7 +330,7 @@ describe("alert engine", () => {
]);
});
- test("fails a directed channel with no resolved recipients instead of dispatching to undefined", async () => {
+ test("skips a directed channel with no resolved recipients rather than dispatching to undefined or failing the run", async () => {
const { engine, sentMail, historyWrites } = buildEngine({
targets: [{ id: "t1" }],
channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }],
@@ -339,13 +339,36 @@ describe("alert engine", () => {
const outcome = await engine.runAlert(makeAlert());
- expect(outcome).toBe(AlertDispatchOutcome.DeliveryFailed);
+ // Nobody to notify is customer config drift, not a delivery fault: it must stay out of
+ // delivery_failed (which we alarm on) and leave no failed history row to re-read as an incident.
+ expect(outcome).toBe(AlertDispatchOutcome.NoRecipients);
// No send is attempted with an undefined recipient.
expect(sentMail).toHaveLength(0);
+ expect(historyWrites).toHaveLength(0);
+ });
+
+ test("dispatches the reachable channels when only some are directed-but-empty", async () => {
+ const { engine, historyWrites } = buildEngine({
+ targets: [{ id: "t1" }],
+ channels: [
+ { id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true },
+ {
+ id: "c-slack",
+ channelType: "slack",
+ encryptedConfig: encConfig({ webhookUrl: "https://hooks.slack.com/services/x" }),
+ enabled: true
+ }
+ ],
+ recipients: []
+ });
+
+ const outcome = await engine.runAlert(makeAlert());
+
+ // The empty email channel neither fails the run nor records a delivery it never attempted.
+ expect(outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
expect(historyWrites).toHaveLength(1);
- expect(historyWrites[0].status).toBe(AlertRunStatus.FAILED);
expect(historyWrites[0].deliveries).toEqual([
- { targetId: "t1", channelId: "c-email", channelType: "email", status: AlertRunStatus.FAILED }
+ { targetId: "t1", channelId: "c-slack", channelType: "slack", status: AlertRunStatus.SUCCESS }
]);
});
diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.ts
index d0215c0176..ef3d9c288a 100644
--- a/backend/src/services/alert/alert-engine.ts
+++ b/backend/src/services/alert/alert-engine.ts
@@ -25,6 +25,7 @@ type TChannelDispatchResult = {
success: boolean;
error?: string;
targetResults?: TChannelTargetResult[];
+ skipped?: boolean;
};
export type TAlertEngineDep = {
@@ -158,7 +159,10 @@ export const alertEngineFactory = ({
if (definition.directed) {
const recipients = recipientsByChannel.get(channel.id) ?? [];
if (recipients.length === 0) {
- return { ...base, success: false, error: "No recipients could be resolved for this channel" };
+ logger.warn(
+ `Alert ${channel.channelType} channel has no resolvable recipients; skipping it this run [alertId=${alert.id}] [channelId=${channel.id}]`
+ );
+ return { ...base, success: false, skipped: true };
}
const results = await Promise.all(
recipients.map((recipient) =>
@@ -189,7 +193,10 @@ export const alertEngineFactory = ({
})
);
- const deliveries = channelResults.flatMap((result) => {
+ const dispatched = channelResults.filter((result) => !result.skipped);
+ if (dispatched.length === 0) return AlertDispatchOutcome.NoRecipients;
+
+ const deliveries = dispatched.flatMap((result) => {
const perTarget = new Map<string, boolean>((result.targetResults ?? []).map((t) => [t.targetId, t.success]));
return result.targetIds.map((targetId) => ({
targetId,
@@ -199,10 +206,10 @@ export const alertEngineFactory = ({
}));
});
- const errors = channelResults
+ const errors = dispatched
.filter((result) => !result.success && result.error)
.map((result) => `${result.channelType}: ${result.error}`);
- const anyDelivered = channelResults.some((result) => result.success);
+ const anyDelivered = dispatched.some((result) => result.success);
let status = AlertRunStatus.SUCCESS;
if (errors.length > 0) status = anyDelivered ? AlertRunStatus.PARTIAL : AlertRunStatus.FAILED;
const errorText = errors.length > 0 ? errors.join("\n") : undefined;
diff --git a/backend/src/services/alert/channels/alert-channels.test.ts b/backend/src/services/alert/channels/alert-channels.test.ts
index afb708b549..bd95aae73b 100644
--- a/backend/src/services/alert/channels/alert-channels.test.ts
+++ b/backend/src/services/alert/channels/alert-channels.test.ts
@@ -1,4 +1,9 @@
-import { AlertChannelType, SlackChannelConfigSchema, TAlertPayload } from "../alert-channel-types";
+import {
+ AlertChannelType,
+ DIRECTED_ALERT_CHANNEL_TYPES,
+ SlackChannelConfigSchema,
+ TAlertPayload
+} from "../alert-channel-types";
import { sendEmailNotification } from "./alert-channel-email-fns";
import { buildPagerDutyEvent } from "./alert-channel-pagerduty-fns";
import { ALERT_CHANNEL_REGISTRY } from "./alert-channel-registry";
@@ -69,6 +74,16 @@ describe("alert channel registry", () => {
expect(def.type).toBe(key);
});
});
+
+ // The DALs read the constant instead of the registry (which would drag the send implementations
+ // into the data layer), so it has to track the registry's directed flags.
+ test("DIRECTED_ALERT_CHANNEL_TYPES matches the registry's directed flags", () => {
+ const fromRegistry = Object.values(ALERT_CHANNEL_REGISTRY)
+ .filter((def) => def.directed)
+ .map((def) => def.type);
+
+ expect([...DIRECTED_ALERT_CHANNEL_TYPES].sort()).toEqual(fromRegistry.sort());
+ });
});
describe("buildWebhookPayload", () => {
diff --git a/frontend/src/views/Alerts/ChannelCard.tsx b/frontend/src/views/Alerts/ChannelCard.tsx
index fa561566a3..b41ed7672d 100644
--- a/frontend/src/views/Alerts/ChannelCard.tsx
+++ b/frontend/src/views/Alerts/ChannelCard.tsx
@@ -4,6 +4,7 @@ import { TrashIcon } from "lucide-react";
import {
Field,
FieldContent,
+ FieldDescription,
FieldError,
FieldLabel,
IconButton,
@@ -40,6 +41,14 @@ export const ChannelCard = ({ index, projectId, onRemove, canRemove }: Props) =>
const Icon = getChannelIcon(channelType);
+ // A saved email channel can only reach zero recipients by having them pruned when they left the
+ // org or project, which also disables the channel. Say so, since the empty field is otherwise
+ // indistinguishable from one the user just cleared.
+ const hasLostRecipients =
+ isExisting &&
+ channelType === AlertChannelType.Email &&
+ (channel?.recipients?.length ?? 0) === 0;
+
return (
<div className="flex flex-col gap-4 rounded-md border border-border p-4">
<div className="flex items-center justify-between">
@@ -106,6 +115,12 @@ export const ChannelCard = ({ index, projectId, onRemove, canRemove }: Props) =>
)}
/>
<FieldError errors={[channelErrors?.recipients as { message?: string } | undefined]} />
+ {hasLostRecipients && (
+ <FieldDescription className="text-warning">
+ Every recipient of this channel lost access, so the channel was disabled. Add a
+ recipient and enable it to resume notifications.
+ </FieldDescription>
+ )}
</FieldContent>
</Field>
)}