Skip to content

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

fix update alarm

Thiago Araujo da Silvaf0994e1a17e6
diff --git a/backend/src/db/migrations/20260714120000_add-alarms.ts b/backend/src/db/migrations/20260714120000_add-alarms.ts
index 3538ac4d3e..b18d88e4ab 100644
--- a/backend/src/db/migrations/20260714120000_add-alarms.ts
+++ b/backend/src/db/migrations/20260714120000_add-alarms.ts
@@ -69,8 +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");
- // Composite covers the FK plus the dedup lookup (by alarm, ordered/filtered by time).
- t.index(["alarmId", "triggeredAt"]);
+ // 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"]);
});
}
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 2f1d75de6b..9f984806bb 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1044,7 +1044,6 @@ export const registerRoutes = async (
alarmDAL,
alarmChannelDAL,
alarmRecipientDAL,
- alarmHistoryDAL,
alarmProviderRegistry,
kmsService,
orgDAL,
diff --git a/backend/src/server/routes/v1/alarm-router.ts b/backend/src/server/routes/v1/alarm-router.ts
index dc5e3cd391..5ff1a42820 100644
--- a/backend/src/server/routes/v1/alarm-router.ts
+++ b/backend/src/server/routes/v1/alarm-router.ts
@@ -3,7 +3,7 @@ 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 { AlarmPrincipalType } from "@app/services/alarm/alarm-types";
import { AuthMode } from "@app/services/auth/auth-type";
const RecipientInputSchema = z.object({
@@ -12,6 +12,7 @@ const RecipientInputSchema = z.object({
});
const ChannelInputSchema = z.object({
+ id: z.string().uuid().optional(),
channelType: z.nativeEnum(AlarmChannelType),
config: z.record(z.unknown()).default({}),
enabled: z.boolean().optional()
@@ -40,9 +41,6 @@ const AlarmResponseSchema = z.object({
updatedAt: z.date()
})
),
- lastRun: z
- .object({ timestamp: z.date(), status: z.nativeEnum(AlarmRunStatus), error: z.string().nullable() })
- .nullable(),
createdAt: z.date(),
updatedAt: z.date()
});
@@ -92,7 +90,10 @@ export const registerAlarmRouter = async (server: FastifyZodProvider) => {
resourceType: z.string().min(1),
resourceId: z.string().optional(),
projectId: z.string().optional(),
- enabled: z.coerce.boolean().optional()
+ enabled: z
+ .enum(["true", "false"])
+ .transform((value) => value === "true")
+ .optional()
}),
response: { 200: z.object({ alarms: AlarmResponseSchema.array() }) }
},
diff --git a/backend/src/services/alarm/alarm-channel-types.ts b/backend/src/services/alarm/alarm-channel-types.ts
index e141506753..74e272f822 100644
--- a/backend/src/services/alarm/alarm-channel-types.ts
+++ b/backend/src/services/alarm/alarm-channel-types.ts
@@ -61,6 +61,7 @@ export type TAlarmChannelSendContext = {
export type TAlarmChannelDefinition = {
type: AlarmChannelType;
directed: boolean;
+ secretFields: string[];
configSchema: z.ZodTypeAny;
send: (ctx: TAlarmChannelSendContext) => Promise<TChannelResult>;
};
diff --git a/backend/src/services/alarm/alarm-history-dal.test.ts b/backend/src/services/alarm/alarm-history-dal.test.ts
new file mode 100644
index 0000000000..ec9b215525
--- /dev/null
+++ b/backend/src/services/alarm/alarm-history-dal.test.ts
@@ -0,0 +1,42 @@
+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).
+const buildDAL = () => {
+ const whereCalls: unknown[][] = [];
+ const chain = {
+ join: () => chain,
+ where: (...args: unknown[]) => {
+ whereCalls.push(args);
+ return chain;
+ },
+ whereIn: () => chain,
+ distinct: () => chain,
+ select: async () => [] as Array<{ targetId: string }>
+ };
+ const queryBuilder = () => chain;
+ const db = { replicaNode: () => queryBuilder } as never;
+
+ return { dal: alarmHistoryDALFactory(db), whereCalls };
+};
+
+describe("alarm history dal", () => {
+ test("findRecentlyAlarmedTargets only counts successful runs", async () => {
+ const { dal, whereCalls } = buildDAL();
+
+ await dal.findRecentlyAlarmedTargets("alarm-1", ["t1", "t2"], 24);
+
+ expect(whereCalls).toContainEqual(["hist.status", AlarmRunStatus.SUCCESS]);
+ expect(whereCalls).toContainEqual(["hist.alarmId", "alarm-1"]);
+ });
+
+ test("findRecentlyAlarmedTargets short-circuits on empty target list without querying", async () => {
+ const { dal, whereCalls } = buildDAL();
+
+ const result = await dal.findRecentlyAlarmedTargets("alarm-1", [], 24);
+
+ expect(result).toEqual([]);
+ expect(whereCalls).toHaveLength(0);
+ });
+});
diff --git a/backend/src/services/alarm/alarm-history-dal.ts b/backend/src/services/alarm/alarm-history-dal.ts
index 461760e23d..851d427cd0 100644
--- a/backend/src/services/alarm/alarm-history-dal.ts
+++ b/backend/src/services/alarm/alarm-history-dal.ts
@@ -5,6 +5,8 @@ import { TableName, TAlarmHistory } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex";
+import { AlarmRunStatus } from "./alarm-types";
+
export type TAlarmHistoryDALFactory = ReturnType<typeof alarmHistoryDALFactory>;
export const alarmHistoryDALFactory = (db: TDbClient) => {
@@ -51,6 +53,7 @@ export const alarmHistoryDALFactory = (db: TDbClient) => {
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)
.whereIn("tgt.targetId", targetIds)
.distinct("tgt.targetId")
@@ -62,22 +65,9 @@ export const alarmHistoryDALFactory = (db: TDbClient) => {
}
};
- 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
+ findRecentlyAlarmedTargets
};
};
diff --git a/backend/src/services/alarm/alarm-service-types.ts b/backend/src/services/alarm/alarm-service-types.ts
index 4b7b42f39c..4dda6543ea 100644
--- a/backend/src/services/alarm/alarm-service-types.ts
+++ b/backend/src/services/alarm/alarm-service-types.ts
@@ -1,7 +1,7 @@
import { TGenericPermission } from "@app/lib/types";
import { AlarmChannelType } from "./alarm-channel-types";
-import { AlarmPrincipalType, AlarmRunStatus } from "./alarm-types";
+import { AlarmPrincipalType } from "./alarm-types";
export type TAlarmRecipientInput = {
principalType: AlarmPrincipalType;
@@ -9,6 +9,7 @@ export type TAlarmRecipientInput = {
};
export type TAlarmChannelInput = {
+ id?: string;
channelType: AlarmChannelType;
config: unknown;
enabled?: boolean;
@@ -50,7 +51,6 @@ export type TListAlarmsDTO = TGenericPermission & {
enabled?: boolean;
};
-// Channel config in responses has endpoint secrets redacted (webhook signing secret -> a boolean).
export type TAlarmChannelResponse = {
id: string;
channelType: string;
@@ -79,7 +79,6 @@ export type TAlarmResponse = {
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
index 30c4303c7a..87a38ff6a0 100644
--- a/backend/src/services/alarm/alarm-service.test.ts
+++ b/backend/src/services/alarm/alarm-service.test.ts
@@ -44,6 +44,7 @@ const buildService = (opts?: {
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 findFilters: Array<Record<string, unknown>> = [];
const service = alarmServiceFactory({
alarmDAL: {
@@ -61,7 +62,15 @@ const buildService = (opts?: {
return row;
},
findById: async (id: string) => alarms.get(id),
- find: async () => [...alarms.values()],
+ find: async (filter: Record<string, unknown>) => {
+ findFilters.push(filter);
+ return [...alarms.values()].filter((row) =>
+ Object.entries(filter).every(([key, value]) => {
+ if (value === undefined) return true;
+ return row[key] === value;
+ })
+ );
+ },
updateById: async (id: string, data: Record<string, unknown>) => {
alarms.set(id, { ...alarms.get(id), ...data });
return alarms.get(id);
@@ -91,7 +100,6 @@ const buildService = (opts?: {
return 0;
}
},
- alarmHistoryDAL: { findLatestByAlarmId: async () => undefined },
alarmProviderRegistry: registry,
kmsService: kmsServiceMock,
orgDAL: {
@@ -116,7 +124,7 @@ const buildService = (opts?: {
}
} as unknown as TAlarmServiceFactoryDep);
- return { service, permissionCalls, alarms, channels };
+ return { service, permissionCalls, alarms, channels, findFilters };
};
const actor = {
@@ -237,6 +245,160 @@ describe("alarm service", () => {
expect(alarm.channels[0].config).not.toHaveProperty("signingSecret");
});
+ test("redacts the Slack webhook URL and PagerDuty integration key on read", async () => {
+ const { service, alarms, channels } = buildService();
+ alarms.set("alarm-1", {
+ id: "alarm-1",
+ name: "creds",
+ 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.SLACK,
+ encryptedConfig: encConfig({ webhookUrl: "https://hooks.slack.com/services/T/B/xxx" }),
+ enabled: true,
+ createdAt: new Date(),
+ updatedAt: new Date()
+ },
+ {
+ id: "c1",
+ channelType: AlarmChannelType.PAGERDUTY,
+ encryptedConfig: encConfig({ integrationKey: "a".repeat(32) }),
+ enabled: true,
+ createdAt: new Date(),
+ updatedAt: new Date()
+ }
+ ]);
+
+ const alarm = await service.getAlarmById({ alarmId: "alarm-1", ...actor });
+
+ expect(alarm.channels[0].config).toEqual({ hasWebhookUrl: true });
+ expect(alarm.channels[0].config).not.toHaveProperty("webhookUrl");
+ expect(alarm.channels[1].config).toEqual({ hasIntegrationKey: true });
+ expect(alarm.channels[1].config).not.toHaveProperty("integrationKey");
+ });
+
+ const listBase = {
+ resourceType: RESOURCE_TYPE,
+ resourceId: null,
+ eventType: "test.resource.expiration",
+ condition: null,
+ filters: null,
+ enabled: true,
+ orgId: "org-1",
+ createdAt: new Date(),
+ updatedAt: new Date()
+ };
+
+ test("org-scoped list returns only org-level alarms, never other projects'", async () => {
+ const { service, alarms, findFilters } = buildService();
+ alarms.set("org-alarm", { id: "org-alarm", name: "org", projectId: null, ...listBase });
+ alarms.set("proj-alarm", { id: "proj-alarm", name: "proj", projectId: "proj-x", ...listBase });
+
+ const result = await service.listAlarms({ resourceType: RESOURCE_TYPE, ...actor });
+
+ expect(result.map((a) => a.id)).toEqual(["org-alarm"]);
+ expect(findFilters[0]).toMatchObject({ projectId: null });
+ });
+
+ test("project-scoped list filters to the requested project", async () => {
+ const { service, alarms, findFilters } = buildService();
+ alarms.set("org-alarm", { id: "org-alarm", name: "org", projectId: null, ...listBase });
+ alarms.set("proj-alarm", { id: "proj-alarm", name: "proj", projectId: "proj-x", ...listBase });
+
+ const result = await service.listAlarms({ resourceType: RESOURCE_TYPE, projectId: "proj-x", ...actor });
+
+ expect(result.map((a) => a.id)).toEqual(["proj-alarm"]);
+ expect(findFilters[0]).toMatchObject({ projectId: "proj-x" });
+ });
+
+ const seedAlarmWithChannel = (
+ channelType: AlarmChannelType,
+ config: unknown,
+ channelId = "c0"
+ ): ReturnType<typeof buildService> => {
+ const built = buildService();
+ built.alarms.set("alarm-1", {
+ id: "alarm-1",
+ name: "a",
+ 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()
+ });
+ built.channels.set("alarm-1", [
+ {
+ id: channelId,
+ channelType,
+ encryptedConfig: encConfig(config),
+ enabled: true,
+ createdAt: new Date(),
+ updatedAt: new Date()
+ }
+ ]);
+ return built;
+ };
+
+ test("preserves an unresent webhook signing secret when a channel is edited by id", async () => {
+ const { service } = seedAlarmWithChannel(AlarmChannelType.WEBHOOK, {
+ url: "https://example.com/hook",
+ signingSecret: "s3cr3t"
+ });
+
+ const updated = await service.updateAlarm({
+ alarmId: "alarm-1",
+ channels: [{ id: "c0", channelType: AlarmChannelType.WEBHOOK, config: { url: "https://example.com/hook" } }],
+ ...actor
+ });
+
+ expect(updated.channels[0].config).toEqual({ url: "https://example.com/hook", hasSigningSecret: true });
+ });
+
+ test("preserves an unresent Slack webhook URL when a channel is edited by id", async () => {
+ const { service } = seedAlarmWithChannel(AlarmChannelType.SLACK, {
+ webhookUrl: "https://hooks.slack.com/services/T/B/xxx"
+ });
+
+ const updated = await service.updateAlarm({
+ alarmId: "alarm-1",
+ channels: [{ id: "c0", channelType: AlarmChannelType.SLACK, config: {} }],
+ ...actor
+ });
+
+ expect(updated.channels[0].config).toEqual({ hasWebhookUrl: true });
+ });
+
+ 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",
+ signingSecret: "s3cr3t"
+ });
+
+ const updated = await service.updateAlarm({
+ alarmId: "alarm-1",
+ channels: [{ channelType: AlarmChannelType.WEBHOOK, config: { url: "https://new.example.com/hook" } }],
+ ...actor
+ });
+
+ expect(updated.channels[0].config).toEqual({ url: "https://new.example.com/hook", hasSigningSecret: false });
+ });
+
test("deletes an alarm after checking Delete permission", async () => {
const { service, permissionCalls } = buildService();
await service.createAlarm(validCreate);
diff --git a/backend/src/services/alarm/alarm-service.ts b/backend/src/services/alarm/alarm-service.ts
index d3460376ea..ffd9917824 100644
--- a/backend/src/services/alarm/alarm-service.ts
+++ b/backend/src/services/alarm/alarm-service.ts
@@ -8,9 +8,8 @@ import { TProjectDALFactory } from "@app/services/project/project-dal";
import { decryptChannelConfig, encryptChannelConfig, getAlarmChannelCipher } from "./alarm-channel-crypto-fns";
import { TAlarmChannelDALFactory } from "./alarm-channel-dal";
-import { AlarmChannelType, TWebhookChannelConfig } from "./alarm-channel-types";
+import { AlarmChannelType } 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 {
@@ -23,7 +22,7 @@ import {
TListAlarmsDTO,
TUpdateAlarmDTO
} from "./alarm-service-types";
-import { AlarmPermissionAction, AlarmPrincipalType, AlarmRunStatus, IResourceAlarmProvider } from "./alarm-types";
+import { AlarmPermissionAction, AlarmPrincipalType, IResourceAlarmProvider } from "./alarm-types";
import { ALARM_CHANNEL_REGISTRY } from "./channels/alarm-channel-registry";
import { validateSlackWebhookUrl } from "./channels/alarm-channel-slack-fns";
@@ -31,7 +30,6 @@ 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">;
orgDAL: Pick<TOrgDALFactory, "findMembership">;
@@ -44,11 +42,44 @@ export type TAlarmServiceFactory = ReturnType<typeof alarmServiceFactory>;
const isValidPrincipalType = (value: string): value is AlarmPrincipalType =>
Object.values(AlarmPrincipalType).includes(value as AlarmPrincipalType);
+const capitalize = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1);
+
+const $redactChannelConfig = (channelType: string, config: Record<string, unknown>): Record<string, unknown> => {
+ const definition = ALARM_CHANNEL_REGISTRY[channelType as AlarmChannelType];
+ if (!definition) return {};
+
+ const redacted: Record<string, unknown> = {};
+ Object.entries(config).forEach(([key, value]) => {
+ if (!definition.secretFields.includes(key)) redacted[key] = value;
+ });
+ definition.secretFields.forEach((field) => {
+ redacted[`has${capitalize(field)}`] = Boolean(config[field]);
+ });
+ return redacted;
+};
+
+const $preserveChannelSecrets = (
+ channelType: string,
+ incomingConfig: Record<string, unknown>,
+ existingConfig: Record<string, unknown>
+): Record<string, unknown> => {
+ const definition = ALARM_CHANNEL_REGISTRY[channelType as AlarmChannelType];
+ if (!definition) return incomingConfig;
+
+ const merged = { ...incomingConfig };
+ definition.secretFields.forEach((field) => {
+ const incoming = merged[field];
+ if ((incoming === undefined || incoming === null || incoming === "") && existingConfig[field] != null) {
+ merged[field] = existingConfig[field];
+ }
+ });
+ return merged;
+};
+
export const alarmServiceFactory = ({
alarmDAL,
alarmChannelDAL,
alarmRecipientDAL,
- alarmHistoryDAL,
alarmProviderRegistry,
kmsService,
orgDAL,
@@ -195,10 +226,9 @@ export const alarmServiceFactory = ({
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([
+ const [channels, recipients] = await Promise.all([
alarmChannelDAL.findByAlarmId(alarmId),
- alarmRecipientDAL.findByAlarmId(alarmId),
- alarmHistoryDAL.findLatestByAlarmId(alarmId)
+ alarmRecipientDAL.findByAlarmId(alarmId)
]);
const { decryptor } = await getAlarmChannelCipher(kmsService, {
@@ -208,18 +238,11 @@ export const alarmServiceFactory = ({
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,
+ config: $redactChannelConfig(channel.channelType, config),
enabled: channel.enabled,
createdAt: channel.createdAt,
updatedAt: channel.updatedAt
@@ -243,13 +266,6 @@ export const alarmServiceFactory = ({
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
};
@@ -368,7 +384,7 @@ export const alarmServiceFactory = ({
orgId: dto.actorOrgId,
resourceType: dto.resourceType,
...(dto.resourceId !== undefined ? { resourceId: dto.resourceId } : {}),
- ...(dto.projectId !== undefined ? { projectId: dto.projectId } : {}),
+ projectId: dto.projectId ?? null,
...(dto.enabled !== undefined ? { enabled: dto.enabled } : {})
});
@@ -380,11 +396,6 @@ export const alarmServiceFactory = ({
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,
@@ -399,13 +410,39 @@ export const alarmServiceFactory = ({
}
});
- if (dto.recipients) await $validateRecipients(alarm.orgId, alarm.projectId, dto.recipients);
-
- const { encryptor } = await getAlarmChannelCipher(kmsService, {
+ const { encryptor, decryptor } = await getAlarmChannelCipher(kmsService, {
orgId: alarm.orgId,
projectId: alarm.projectId
});
+ let resolvedChannels: TAlarmChannelInput[] | undefined;
+ if (dto.channels) {
+ const existingById = new Map(
+ (await alarmChannelDAL.findByAlarmId(alarm.id)).map((channel) => [channel.id, channel])
+ );
+ resolvedChannels = dto.channels.map((channel) => {
+ const existing = channel.id ? existingById.get(channel.id) : undefined;
+ if (!existing || existing.channelType !== channel.channelType) return channel;
+ const existingConfig = decryptChannelConfig<Record<string, unknown>>(existing.encryptedConfig, decryptor);
+ return {
+ ...channel,
+ config: $preserveChannelSecrets(
+ channel.channelType,
+ channel.config as Record<string, unknown>,
+ existingConfig
+ )
+ };
+ });
+ }
+
+ $validate(provider, {
+ condition: dto.condition,
+ channels: resolvedChannels,
+ recipients: dto.recipients ?? (resolvedChannels ? [] : undefined)
+ });
+
+ if (dto.recipients) await $validateRecipients(alarm.orgId, alarm.projectId, dto.recipients);
+
await alarmDAL.transaction(async (tx) => {
await alarmDAL.updateById(
alarm.id,
@@ -421,10 +458,10 @@ export const alarmServiceFactory = ({
tx
);
- if (dto.channels) {
+ if (resolvedChannels) {
await alarmChannelDAL.deleteByAlarmId(alarm.id, tx);
await alarmChannelDAL.insertMany(
- dto.channels.map((channel) => ({
+ resolvedChannels.map((channel) => ({
alarmId: alarm.id,
channelType: channel.channelType,
encryptedConfig: encryptChannelConfig(channel.config, encryptor),
diff --git a/backend/src/services/alarm/channels/alarm-channel-registry.ts b/backend/src/services/alarm/channels/alarm-channel-registry.ts
index 37bb861fd8..203ac22e12 100644
--- a/backend/src/services/alarm/channels/alarm-channel-registry.ts
+++ b/backend/src/services/alarm/channels/alarm-channel-registry.ts
@@ -15,24 +15,28 @@ export const ALARM_CHANNEL_REGISTRY: Record<AlarmChannelType, TAlarmChannelDefin
[AlarmChannelType.EMAIL]: {
type: AlarmChannelType.EMAIL,
directed: true,
+ secretFields: [],
configSchema: EmailChannelConfigSchema,
send: sendEmailNotification
},
[AlarmChannelType.SLACK]: {
type: AlarmChannelType.SLACK,
directed: false,
+ secretFields: ["webhookUrl"],
configSchema: SlackChannelConfigSchema,
send: sendSlackNotification
},
[AlarmChannelType.WEBHOOK]: {
type: AlarmChannelType.WEBHOOK,
directed: false,
+ secretFields: ["signingSecret"],
configSchema: WebhookChannelConfigSchema,
send: sendWebhookNotification
},
[AlarmChannelType.PAGERDUTY]: {
type: AlarmChannelType.PAGERDUTY,
directed: false,
+ secretFields: ["integrationKey"],
configSchema: PagerDutyChannelConfigSchema,
send: sendPagerDutyNotification
}
diff --git a/frontend/src/hooks/api/alarms/types.ts b/frontend/src/hooks/api/alarms/types.ts
index 48188b9669..2c7a11fc0f 100644
--- a/frontend/src/hooks/api/alarms/types.ts
+++ b/frontend/src/hooks/api/alarms/types.ts
@@ -24,11 +24,6 @@ export enum AlarmPrincipalType {
Email = "email"
}
-export enum AlarmRunStatus {
- Success = "success",
- Failed = "failed"
-}
-
export enum AlarmTimeUnit {
Days = "d",
Weeks = "w",
@@ -79,12 +74,6 @@ export type TAlarmChannel = {
updatedAt: string;
};
-export type TAlarmLastRun = {
- timestamp: string;
- status: AlarmRunStatus;
- error: string | null;
-};
-
export type TAlarm = {
id: string;
name: string;
@@ -99,7 +88,6 @@ export type TAlarm = {
projectId: string | null;
recipients: TAlarmRecipient[];
channels: TAlarmChannel[];
- lastRun: TAlarmLastRun | null;
createdAt: string;
updatedAt: string;
};
@@ -112,6 +100,8 @@ export type TListAlarmsDTO = {
};
export type TAlarmChannelInput = {
+ // Present when editing an existing channel; lets the server preserve secret fields left blank.
+ id?: string;
channelType: AlarmChannelType;
config: Record<string, unknown>;
enabled?: boolean;
@@ -184,15 +174,16 @@ const emailChannelConfigSchema = z.object({
const slackChannelConfigSchema = z.object({
webhookUrl: z
.string()
- .url("Must be a valid URL")
- .refine((url) => url.startsWith("https://"), "Slack webhook URL must use HTTPS")
+ .optional()
.refine((url) => {
+ if (!url) return true;
try {
- return new URL(url).hostname === "hooks.slack.com";
+ const parsed = new URL(url);
+ return parsed.protocol === "https:" && parsed.hostname === "hooks.slack.com";
} catch {
return false;
}
- }, "Slack webhook URL must be from hooks.slack.com")
+ }, "Must be a valid https://hooks.slack.com/... URL")
});
const webhookChannelConfigSchema = z.object({
@@ -206,54 +197,86 @@ const webhookChannelConfigSchema = z.object({
const pagerdutyChannelConfigSchema = z.object({
integrationKey: z
.string()
+ .optional()
.refine(
- (val) => /^[a-f0-9]{32}$/i.test(val),
+ (val) => !val || /^[a-f0-9]{32}$/i.test(val),
"Integration key must be a 32-character hex string"
)
});
export const alarmChannelFormSchema = z.discriminatedUnion("channelType", [
z.object({
+ id: z.string().optional(),
channelType: z.literal(AlarmChannelType.Email),
config: emailChannelConfigSchema,
enabled: z.boolean().default(true)
}),
z.object({
+ id: z.string().optional(),
channelType: z.literal(AlarmChannelType.Slack),
config: slackChannelConfigSchema,
enabled: z.boolean().default(true)
}),
z.object({
+ id: z.string().optional(),
channelType: z.literal(AlarmChannelType.Webhook),
config: webhookChannelConfigSchema,
enabled: z.boolean().default(true)
}),
z.object({
+ id: z.string().optional(),
channelType: z.literal(AlarmChannelType.PagerDuty),
config: pagerdutyChannelConfigSchema,
enabled: z.boolean().default(true)
})
]);
-export const alarmFormSchema = z.object({
- name: z.string().min(1, "Name is required").max(255),
- description: z.string().max(1000).optional(),
- resourceType: z.nativeEnum(AlarmResourceType),
- eventType: z.nativeEnum(AlarmEventType),
- alertBeforeValue: z
- .number({ invalid_type_error: "Enter a number" })
- .int("Must be a whole number")
- .min(1, "Must be at least 1")
- .max(3650, "Too large"),
- alertBeforeUnit: z.nativeEnum(AlarmTimeUnit),
- enabled: z.boolean().default(true),
- channels: z
- .array(alarmChannelFormSchema)
- .min(1, "At least one notification channel is required")
- .refine(
- (channels) => channels.some((channel) => channel.enabled),
- "At least one notification channel must be enabled"
- )
-});
+export const alarmFormSchema = z
+ .object({
+ name: z.string().min(1, "Name is required").max(255),
+ description: z.string().max(1000).optional(),
+ resourceType: z.nativeEnum(AlarmResourceType),
+ eventType: z.nativeEnum(AlarmEventType),
+ alertBeforeValue: z
+ .number({ invalid_type_error: "Enter a number" })
+ .int("Must be a whole number")
+ .min(1, "Must be at least 1")
+ .max(3650, "Too large"),
+ alertBeforeUnit: z.nativeEnum(AlarmTimeUnit),
+ enabled: z.boolean().default(true),
+ channels: z
+ .array(alarmChannelFormSchema)
+ .min(1, "At least one notification channel is required")
+ .refine(
+ (channels) => channels.some((channel) => channel.enabled),
+ "At least one notification channel must be enabled"
+ )
+ })
+ .superRefine((data, ctx) => {
+ data.channels.forEach((channel, index) => {
+ if (
+ channel.channelType === AlarmChannelType.Slack &&
+ !channel.id &&
+ !channel.config.webhookUrl
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["channels", index, "config", "webhookUrl"],
+ message: "Slack webhook URL is required"
+ });
+ }
+ if (
+ channel.channelType === AlarmChannelType.PagerDuty &&
+ !channel.id &&
+ !channel.config.integrationKey
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["channels", index, "config", "integrationKey"],
+ message: "Integration key is required"
+ });
+ }
+ });
+ });
export type TAlarmForm = z.infer<typeof alarmFormSchema>;
diff --git a/frontend/src/views/AlarmsPage/components/AlarmChannelsField.tsx b/frontend/src/views/AlarmsPage/components/AlarmChannelsField.tsx
index f4f43d1636..c44be380dd 100644
--- a/frontend/src/views/AlarmsPage/components/AlarmChannelsField.tsx
+++ b/frontend/src/views/AlarmsPage/components/AlarmChannelsField.tsx
@@ -183,7 +183,8 @@ export const AlarmChannelsField = () => {
onBlur={urlField.onBlur}
/>
<FieldDescription>
- Create an Incoming Webhook in your Slack workspace settings.
+ Create an Incoming Webhook in your Slack workspace settings. Existing
+ URLs are hidden; leave blank to keep the current one.
</FieldDescription>
<FieldError errors={[error]} />
</FieldContent>
@@ -259,6 +260,7 @@ export const AlarmChannelsField = () => {
/>
<FieldDescription>
Find this in PagerDuty under Services → Integrations → Events API v2.
+ Existing keys are hidden; leave blank to keep the current one.
</FieldDescription>
<FieldError errors={[error]} />
</FieldContent>
diff --git a/frontend/src/views/AlarmsPage/components/AlarmForm.tsx b/frontend/src/views/AlarmsPage/components/AlarmForm.tsx
index 6eb970208b..26a7b0b59e 100644
--- a/frontend/src/views/AlarmsPage/components/AlarmForm.tsx
+++ b/frontend/src/views/AlarmsPage/components/AlarmForm.tsx
@@ -69,27 +69,32 @@ const parseAlertBefore = (alertBefore?: string): { value: number; unit: AlarmTim
const buildChannelsPayload = (channels: TAlarmForm["channels"]): TAlarmChannelInput[] =>
channels.map((channel) => {
+ const id = channel.id ? { id: channel.id } : {};
switch (channel.channelType) {
case AlarmChannelType.Slack:
return {
+ ...id,
channelType: AlarmChannelType.Slack,
- config: { webhookUrl: channel.config.webhookUrl },
+ config: channel.config.webhookUrl ? { webhookUrl: channel.config.webhookUrl } : {},
enabled: channel.enabled
};
case AlarmChannelType.Webhook: {
const config: Record<string, unknown> = { url: channel.config.url };
if (channel.config.signingSecret) config.signingSecret = channel.config.signingSecret;
- return { channelType: AlarmChannelType.Webhook, config, enabled: channel.enabled };
+ return { ...id, channelType: AlarmChannelType.Webhook, config, enabled: channel.enabled };
}
case AlarmChannelType.PagerDuty:
return {
+ ...id,
channelType: AlarmChannelType.PagerDuty,
- config: { integrationKey: channel.config.integrationKey },
+ config: channel.config.integrationKey
+ ? { integrationKey: channel.config.integrationKey }
+ : {},
enabled: channel.enabled
};
case AlarmChannelType.Email:
default:
- return { channelType: AlarmChannelType.Email, config: {}, enabled: channel.enabled };
+ return { ...id, channelType: AlarmChannelType.Email, config: {}, enabled: channel.enabled };
}
});
@@ -135,27 +140,30 @@ const buildFormDefaults = (alarm?: TAlarm): TAlarmForm => {
switch (channel.channelType) {
case AlarmChannelType.Email:
return {
+ id: channel.id,
channelType: AlarmChannelType.Email,
config: { recipients: emailRecipients },
enabled: channel.enabled
};
case AlarmChannelType.Slack:
return {
+ id: channel.id,
channelType: AlarmChannelType.Slack,
- config: { webhookUrl: (channel.config.webhookUrl as string) ?? "" },
+ config: { webhookUrl: "" },
enabled: channel.enabled
};
case AlarmChannelType.Webhook:
return {
+ id: channel.id,
channelType: AlarmChannelType.Webhook,
- // The signing secret is never returned by the API; leave blank on edit.
config: { url: (channel.config.url as string) ?? "", signingSecret: "" },
enabled: channel.enabled
};
case AlarmChannelType.PagerDuty:
return {
+ id: channel.id,
channelType: AlarmChannelType.PagerDuty,
- config: { integrationKey: (channel.config.integrationKey as string) ?? "" },
+ config: { integrationKey: "" },
enabled: channel.enabled
};
default: