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
add test button for channels
Thiago Araujo da Silva2273705db944
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 8dd5348ce3..7592a70d8f 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -78,6 +78,7 @@ import { RequestMemoizer } from "@app/lib/request-context/request-memoizer";import { TAuthMode } from "@app/server/plugins/auth/inject-identity";import { TAccountRecoveryServiceFactory } from "@app/services/account-recovery/account-recovery-service";import { TAdditionalPrivilegeServiceFactory } from "@app/services/additional-privilege/additional-privilege-service";+import { TAlertChannelTestServiceFactory } from "@app/services/alert/alert-channel-test-service";import { TAlertServiceFactory } from "@app/services/alert/alert-service";import { TAnnouncementServiceFactory } from "@app/services/announcement/announcement-service";import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";@@ -441,6 +442,7 @@ declare module "fastify" {identityAuthTemplate: TIdentityAuthTemplateServiceFactory;notification: TNotificationServiceFactory;alert: TAlertServiceFactory;+ alertChannelTest: TAlertChannelTestServiceFactory;announcement: TAnnouncementServiceFactory;offlineUsageReport: TOfflineUsageReportServiceFactory;orgProductStats: TOrgProductStatsServiceFactory;diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 709e435365..28177eb152 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -86,6 +86,11 @@ export const KeyStorePrefixes = {`sse-connections:${projectId}:${identityId}:${connectionId}` as const,RecentAnnouncements: "announcements:recent" as const,+ AlertChannelTestOrgCooldown: (orgId: string, channelType: string) =>+ `alert-channel-test-cooldown:org:${orgId}:${channelType}` as const,+ AlertChannelTestActorCooldown: (actorId: string, channelType: string) =>+ `alert-channel-test-cooldown:actor:${actorId}:${channelType}` as const,+ProjectPermissionMarker: (projectId: string, actorType: string, actorId: string, actionProjectType: string) =>`project-permission-marker:${projectId}:${actorType}:${actorId}:${actionProjectType}` as const,ProjectPermissionData: (projectId: string, actorType: string, actorId: string, actionProjectType: string) =>@@ -182,6 +187,7 @@ export const KeyStoreTtls = {MfaSessionInSeconds: 300, // 5 minutesRecentMfaAuthInSeconds: 600, // 10 minutesMfaCodeResendCooldownInSeconds: 60, // 1 minute+ AlertChannelTestCooldownInSeconds: 60, // 1 minuteWebAuthnChallengeInSeconds: 300, // 5 minutesUsedTotpCodeInSeconds: 120, // covers the full ±30s acceptance window (window:1 → 90s) with margindiff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex c6f7401fb3..e2030f6a74 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -236,6 +236,7 @@ import { alertChannelDALFactory } from "@app/services/alert/alert-channel-dal";import { alertChannelMembershipDALFactory } from "@app/services/alert/alert-channel-membership-dal";import { alertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";import { alertChannelServiceFactory } from "@app/services/alert/alert-channel-service";+import { alertChannelTestServiceFactory } from "@app/services/alert/alert-channel-test-service";import { alertDALFactory } from "@app/services/alert/alert-dal";import { alertEngineFactory } from "@app/services/alert/alert-engine";import { alertHistoryDALFactory } from "@app/services/alert/alert-history-dal";@@ -1068,6 +1069,14 @@ export const registerRoutes = async (kmsService,alertProviderRegistry});+ const alertChannelTestService = alertChannelTestServiceFactory({+ alertChannelDAL,+ alertRecipientResolver,+ alertProviderRegistry,+ kmsService,+ smtpService,+ keyStore+ });const auditLogStreamService = auditLogStreamServiceFactory({licenseService,@@ -4100,6 +4109,7 @@ export const registerRoutes = async (projectEventsSSE: projectEventsSSEService,notification: notificationService,alert: alertService,+ alertChannelTest: alertChannelTestService,announcement: announcementService,mfaSession: mfaSessionService,membershipUser: membershipUserService,diff --git a/backend/src/server/routes/v1/alert-router.ts b/backend/src/server/routes/v1/alert-router.tsindex 171d9b848d..7fe93bdd33 100644--- a/backend/src/server/routes/v1/alert-router.ts+++ b/backend/src/server/routes/v1/alert-router.ts@@ -107,6 +107,40 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {}});+ server.route({+ method: "POST",+ url: "/channels/test",+ config: { rateLimit: writeLimit },+ schema: {+ operationId: "testAlertChannel",+ body: z.object({+ resourceType: z.string().min(1),+ resourceId: z.string().nullable().optional(),+ projectId: z.string().nullable().optional(),+ channelId: z.string().uuid().optional(),+ channelType: z.nativeEnum(AlertChannelType),+ config: z.record(z.unknown()).default({}),+ recipients: z.array(ChannelRecipientSchema).max(MAX_RECIPIENTS_PER_CHANNEL).optional()+ }),+ response: {+ 200: z.object({+ success: z.boolean(),+ deliveredTo: z.number().optional(),+ error: z.string().optional()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) =>+ server.services.alertChannelTest.testChannel({+ ...req.body,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ })+ });+server.route({method: "GET",url: "/",diff --git a/backend/src/services/alert/alert-channel-config-fns.ts b/backend/src/services/alert/alert-channel-config-fns.tsnew file mode 100644index 0000000000..cb65fbcc79--- /dev/null+++ b/backend/src/services/alert/alert-channel-config-fns.ts@@ -0,0 +1,47 @@+import { z } from "zod";++import { BadRequestError } from "@app/lib/errors";++import { AlertChannelType, TAlertChannelDefinition } from "./alert-channel-types";+import { ALERT_CHANNEL_REGISTRY } from "./channels/alert-channel-registry";++export const getChannelDefinition = (channelType: string): TAlertChannelDefinition => {+ const definition = ALERT_CHANNEL_REGISTRY[channelType as AlertChannelType];+ if (!definition) throw new BadRequestError({ message: `Unknown channel type '${channelType}'` });+ return definition;+};++export const assertChannelConfigValid = (+ definition: Pick<TAlertChannelDefinition, "configSchema">,+ channelType: string,+ config: Record<string, unknown>+) => {+ try {+ definition.configSchema.parse(config);+ } catch (err) {+ const detail = err instanceof z.ZodError ? err.issues.map((i) => i.message).join(", ") : null;+ throw new BadRequestError({+ message: detail ? `Invalid ${channelType} channel config: ${detail}` : `Invalid ${channelType} channel config`+ });+ }+};++export const mergeChannelConfigWithStored = (+ channelType: string,+ incomingConfig: Record<string, unknown>,+ existingConfig: Record<string, unknown>+): Record<string, unknown> => {+ const definition = ALERT_CHANNEL_REGISTRY[channelType as AlertChannelType];+ if (!definition) return incomingConfig;++ const merged: Record<string, unknown> = { ...incomingConfig };+ definition.secretFields.forEach((field) => {+ if (!(field in incomingConfig)) {+ if (existingConfig[field] != null) merged[field] = existingConfig[field];+ return;+ }+ const value = incomingConfig[field];+ if (value === "" || value === null || value === undefined) delete merged[field];+ });+ return merged;+};diff --git a/backend/src/services/alert/alert-channel-service.ts b/backend/src/services/alert/alert-channel-service.tsindex 683353c338..54064c6582 100644--- a/backend/src/services/alert/alert-channel-service.ts+++ b/backend/src/services/alert/alert-channel-service.ts@@ -1,5 +1,4 @@import { Knex } from "knex";-import { z } from "zod";import { TAlertChannels } from "@app/db/schemas";import { TGroupDALFactory } from "@app/ee/services/group/group-dal";@@ -7,6 +6,11 @@ import { BadRequestError } from "@app/lib/errors";import { TOrgDALFactory } from "@app/services/org/org-dal";import { TProjectDALFactory } from "@app/services/project/project-dal";+import {+ assertChannelConfigValid,+ getChannelDefinition,+ mergeChannelConfigWithStored+} from "./alert-channel-config-fns";import {decryptChannelConfig,encryptChannelConfig,@@ -63,12 +67,6 @@ export const alertChannelServiceFactory = ({projectDAL,groupDAL}: TAlertChannelServiceFactoryDep) => {- const $getDefinition = (channelType: string) => {- const definition = ALERT_CHANNEL_REGISTRY[channelType as AlertChannelType];- if (!definition) throw new BadRequestError({ message: `Unknown channel type '${channelType}'` });- return definition;- };-// Confirms every recipient principal (user/group) actually belongs to the channel's scope so an// alert can't be made to notify a foreign principal.const $validateRecipients = async (@@ -118,21 +116,6 @@ export const alertChannelServiceFactory = ({}};- const $assertConfigValid = (- definition: { configSchema: { parse: (value: unknown) => unknown } },- channelType: string,- config: Record<string, unknown>- ) => {- try {- definition.configSchema.parse(config);- } catch (err) {- const detail = err instanceof z.ZodError ? err.issues.map((i) => i.message).join(", ") : null;- throw new BadRequestError({- message: detail ? `Invalid ${channelType} channel config: ${detail}` : `Invalid ${channelType} channel config`- });- }- };-const $redactConfig = (channelType: string, config: Record<string, unknown>): Record<string, unknown> => {const definition = ALERT_CHANNEL_REGISTRY[channelType as AlertChannelType];if (!definition) return {};@@ -146,35 +129,15 @@ export const alertChannelServiceFactory = ({return redacted;};- const $mergeConfigForUpdate = (- channelType: string,- incomingConfig: Record<string, unknown>,- existingConfig: Record<string, unknown>- ): Record<string, unknown> => {- const definition = ALERT_CHANNEL_REGISTRY[channelType as AlertChannelType];- if (!definition) return incomingConfig;-- const merged: Record<string, unknown> = { ...incomingConfig };- definition.secretFields.forEach((field) => {- if (!(field in incomingConfig)) {- if (existingConfig[field] != null) merged[field] = existingConfig[field];- return;- }- const value = incomingConfig[field];- if (value === "" || value === null || value === undefined) delete merged[field];- });- return merged;- };-const createChannelInTx = async (input: TCreateChannelInTxInput,encryptor: TAlertEncryptor,tx: Knex): Promise<TAlertChannels> => {- const definition = $getDefinition(input.channelType);+ const definition = getChannelDefinition(input.channelType);const recipients = input.recipients ?? [];$assertRecipientRules(definition, input.channelType, recipients);- $assertConfigValid(definition, input.channelType, input.config);+ assertChannelConfigValid(definition, input.channelType, input.config);await $validateRecipients(input.orgId, input.projectId, recipients);const created = await alertChannelDAL.create(@@ -206,13 +169,13 @@ export const alertChannelServiceFactory = ({cipher: { encryptor: TAlertEncryptor; decryptor: TAlertDecryptor },tx: Knex): Promise<Record<string, unknown>> => {- const definition = $getDefinition(channel.channelType);+ const definition = getChannelDefinition(channel.channelType);const existingConfig = decryptChannelConfig<Record<string, unknown>>(channel.encryptedConfig, cipher.decryptor);let finalConfig = existingConfig;if (input.config !== undefined) {- const merged = $mergeConfigForUpdate(channel.channelType, input.config, existingConfig);- $assertConfigValid(definition, channel.channelType, merged);+ const merged = mergeChannelConfigWithStored(channel.channelType, input.config, existingConfig);+ assertChannelConfigValid(definition, channel.channelType, merged);finalConfig = merged;}diff --git a/backend/src/services/alert/alert-channel-test-service.test.ts b/backend/src/services/alert/alert-channel-test-service.test.tsnew file mode 100644index 0000000000..d97cb105f9--- /dev/null+++ b/backend/src/services/alert/alert-channel-test-service.test.ts@@ -0,0 +1,340 @@+import { z } from "zod";++import { alertChannelTestServiceFactory, TAlertChannelTestServiceFactoryDep } from "./alert-channel-test-service";+import { TAlertChannelSendContext, TAlertPayload, TChannelResult } from "./alert-channel-types";+import { alertProviderRegistryFactory } from "./alert-provider-registry";+import { IResourceAlertProvider, TAlertPermissionInput } from "./alert-types";+import { ALERT_CHANNEL_REGISTRY } from "./channels/alert-channel-registry";++// logger is `export let logger` assigned by initLogger(), which unit tests don't run, so the+// delivery-failure path (which logs) would otherwise dereference undefined. Mock it per-file.+vi.mock("@app/lib/logger", () => ({+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },+ initLogger: () => {}+}));++const RESOURCE_TYPE = "test.resource";+const ORG_ID = "org-1";+const ACTOR_ID = "actor-1";++const actor = {+ actor: "user",+ actorId: ACTOR_ID,+ actorAuthMethod: undefined,+ actorOrgId: ORG_ID+} as unknown as { actor: never; actorId: string; actorAuthMethod: never; actorOrgId: string };++const buildProvider = (opts?: { assertPermission?: (input: TAlertPermissionInput) => Promise<void> }) => {+ const provider: IResourceAlertProvider = {+ resourceType: RESOURCE_TYPE,+ eventTypes: ["test.resource.expiration"],+ conditionSchema: z.object({}).optional(),+ findDueTargets: async () => [],+ buildViewUrl: async () => "https://app.infisical.com/x",+ buildPayload: (alert, targets, viewUrl) =>+ ({+ alert: { id: alert.id, name: alert.name, orgId: alert.orgId, resourceType: alert.resourceType, viewUrl },+ eventKey: "test.resource.expiration",+ eventLabel: "Expiration",+ webhookType: "com.infisical.test.resource.expiration",+ resourceKind: "Test Resource",+ resourceOwnerKind: "Test Owner",+ severity: "critical",+ summary: "real summary",+ items: (targets as { id: string }[]).map((target) => ({ id: target.id, title: "sample" }))+ }) as TAlertPayload,+ targetId: () => "t",+ buildTestTargets: () => [{ id: "sample-target" }],+ assertPermission: async (input) => {+ if (opts?.assertPermission) await opts.assertPermission(input);+ },+ assertResourceInScope: async () => {}+ };++ const registry = alertProviderRegistryFactory();+ registry.register(provider);+ return registry;+};++const buildKeyStore = () => {+ const keys = new Map<string, number>();+ return {+ acquired: [] as string[],+ setItemWithExpiryNX: async (key: string, expiryInSeconds: number | string) => {+ if (keys.has(key)) return null;+ keys.set(key, Number(expiryInSeconds));+ return "OK" as const;+ },+ ttl: async (key: string) => keys.get(key) ?? -2+ };+};++const buildDeps = (overrides?: {+ registry?: ReturnType<typeof alertProviderRegistryFactory>;+ channel?: Record<string, unknown> | null;+ recipients?: { email: string }[];+ keyStore?: ReturnType<typeof buildKeyStore>;+}) => {+ const keyStore = overrides?.keyStore ?? buildKeyStore();+ return {+ keyStore,+ deps: {+ alertChannelDAL: {+ findById: async () => overrides?.channel ?? null+ },+ alertRecipientResolver: {+ resolveMany: async (rowsByChannel: Map<string, unknown[]>) =>+ new Map([...rowsByChannel.keys()].map((channelId) => [channelId, overrides?.recipients ?? []]))+ },+ alertProviderRegistry: overrides?.registry ?? buildProvider(),+ kmsService: {+ createCipherPairWithDataKey: async () => ({+ encryptor: ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: plainText }),+ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob+ })+ },+ smtpService: { sendMail: async () => {} },+ keyStore+ } as unknown as TAlertChannelTestServiceFactoryDep+ };+};++const stubSend = (channelType: "slack" | "email", impl: (ctx: TAlertChannelSendContext) => Promise<TChannelResult>) => {+ const definition = ALERT_CHANNEL_REGISTRY[channelType];+ const original = definition.send;+ definition.send = impl;+ return () => {+ definition.send = original;+ };+};++describe("alertChannelTestService", () => {+ test("sends a test through an undirected channel with the supplied config", async () => {+ const sent: TAlertChannelSendContext[] = [];+ const restore = stubSend("slack", async (ctx) => {+ sent.push(ctx);+ return { success: true };+ });++ try {+ const { deps } = buildDeps();+ const service = alertChannelTestServiceFactory(deps);++ const result = await service.testChannel({+ ...actor,+ resourceType: RESOURCE_TYPE,+ channelType: "slack" as never,+ config: { webhookUrl: "https://hooks.slack.com/services/T/B/x" }+ });++ expect(result).toEqual({ success: true, deliveredTo: 1 });+ expect(sent).toHaveLength(1);+ expect(sent[0].config).toEqual({ webhookUrl: "https://hooks.slack.com/services/T/B/x" });+ // A test must never page an on-call rotation at the severity a real firing would carry.+ expect(sent[0].payload.severity).toBe("info");+ expect(sent[0].payload.summary).toContain("Test notification");+ } finally {+ restore();+ }+ });++ test("falls back to the stored secret when the config omits it", async () => {+ const sent: TAlertChannelSendContext[] = [];+ const restore = stubSend("slack", async (ctx) => {+ sent.push(ctx);+ return { success: true };+ });++ try {+ const { deps } = buildDeps({+ channel: {+ id: "channel-1",+ orgId: ORG_ID,+ projectId: null,+ channelType: "slack",+ encryptedConfig: Buffer.from(JSON.stringify({ webhookUrl: "https://hooks.slack.com/services/T/B/stored" }))+ }+ });+ const service = alertChannelTestServiceFactory(deps);++ const result = await service.testChannel({+ ...actor,+ resourceType: RESOURCE_TYPE,+ channelId: "channel-1",+ channelType: "slack" as never,+ config: {}+ });++ expect(result.success).toBe(true);+ expect(sent[0].config).toEqual({ webhookUrl: "https://hooks.slack.com/services/T/B/stored" });+ } finally {+ restore();+ }+ });++ test("rejects a saved channel that belongs to another organization", async () => {+ const { deps } = buildDeps({+ channel: {+ id: "channel-1",+ orgId: "other-org",+ projectId: null,+ channelType: "slack",+ encryptedConfig: Buffer.from(JSON.stringify({ webhookUrl: "https://hooks.slack.com/services/T/B/stored" }))+ }+ });+ const service = alertChannelTestServiceFactory(deps);++ await expect(+ service.testChannel({+ ...actor,+ resourceType: RESOURCE_TYPE,+ channelId: "channel-1",+ channelType: "slack" as never,+ config: {}+ })+ ).rejects.toThrow(/not found in this scope/);+ });++ test("rejects an invalid config before any cooldown is spent", async () => {+ const { deps, keyStore } = buildDeps();+ const service = alertChannelTestServiceFactory(deps);++ await expect(+ service.testChannel({+ ...actor,+ resourceType: RESOURCE_TYPE,+ channelType: "slack" as never,+ config: { webhookUrl: "https://example.com/not-slack" }+ })+ ).rejects.toThrow(/Invalid slack channel config/);++ // The window is still free, so a corrected config can be tested immediately.+ await expect(+ keyStore.setItemWithExpiryNX(`alert-channel-test-cooldown:org:${ORG_ID}:slack`, 60, "1")+ ).resolves.toBe("OK");+ });++ test("holds a second test of the same channel type for the cooldown window", async () => {+ const restore = stubSend("slack", async () => ({ success: true }));++ try {+ const { deps } = buildDeps();+ const service = alertChannelTestServiceFactory(deps);+ const dto = {+ ...actor,+ resourceType: RESOURCE_TYPE,+ channelType: "slack" as never,+ config: { webhookUrl: "https://hooks.slack.com/services/T/B/x" }+ };++ await expect(service.testChannel(dto)).resolves.toEqual({ success: true, deliveredTo: 1 });+ await expect(service.testChannel(dto)).rejects.toThrow(/Try again in 60s/);+ } finally {+ restore();+ }+ });++ test("leaves other channel types testable while one is cooling down", async () => {+ const restoreSlack = stubSend("slack", async () => ({ success: true }));+ const restoreEmail = stubSend("email", async () => ({ success: true }));++ try {+ const { deps } = buildDeps({ recipients: [{ email: "[email protected]" }] });+ const service = alertChannelTestServiceFactory(deps);++ await service.testChannel({+ ...actor,+ resourceType: RESOURCE_TYPE,+ channelType: "slack" as never,+ config: { webhookUrl: "https://hooks.slack.com/services/T/B/x" }+ });++ await expect(+ service.testChannel({+ ...actor,+ resourceType: RESOURCE_TYPE,+ channelType: "email" as never,+ config: {},+ recipients: [{ principalType: "user" as never, principalId: "user-1" }]+ })+ ).resolves.toEqual({ success: true, deliveredTo: 1 });+ } finally {+ restoreSlack();+ restoreEmail();+ }+ });++ test("reports a delivery failure instead of throwing", async () => {+ const restore = stubSend("slack", async () => {+ throw new Error("connect ECONNREFUSED");+ });++ try {+ const { deps } = buildDeps();+ const service = alertChannelTestServiceFactory(deps);++ const result = await service.testChannel({+ ...actor,+ resourceType: RESOURCE_TYPE,+ channelType: "slack" as never,+ config: { webhookUrl: "https://hooks.slack.com/services/T/B/x" }+ });++ expect(result).toEqual({ success: false, error: "connect ECONNREFUSED" });+ } finally {+ restore();+ }+ });++ test("reports unresolvable recipients without spending the cooldown", async () => {+ const { deps, keyStore } = buildDeps({ recipients: [] });+ const service = alertChannelTestServiceFactory(deps);++ const result = await service.testChannel({+ ...actor,+ resourceType: RESOURCE_TYPE,+ channelType: "email" as never,+ config: {},+ recipients: [{ principalType: "user" as never, principalId: "outsider" }]+ });++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/recipients could be resolved/);+ await expect(+ keyStore.setItemWithExpiryNX(`alert-channel-test-cooldown:org:${ORG_ID}:email`, 60, "1")+ ).resolves.toBe("OK");+ });++ test("propagates the provider's permission decision", async () => {+ const registry = buildProvider({+ assertPermission: async () => {+ throw new Error("forbidden");+ }+ });+ const { deps } = buildDeps({ registry });+ const service = alertChannelTestServiceFactory(deps);++ await expect(+ service.testChannel({+ ...actor,+ resourceType: RESOURCE_TYPE,+ channelType: "slack" as never,+ config: { webhookUrl: "https://hooks.slack.com/services/T/B/x" }+ })+ ).rejects.toThrow("forbidden");+ });++ test("rejects a resource type with no registered provider", async () => {+ const { deps } = buildDeps();+ const service = alertChannelTestServiceFactory(deps);++ await expect(+ service.testChannel({+ ...actor,+ resourceType: "unknown.resource",+ channelType: "slack" as never,+ config: { webhookUrl: "https://hooks.slack.com/services/T/B/x" }+ })+ ).rejects.toThrow(/No alert provider is registered/);+ });+});diff --git a/backend/src/services/alert/alert-channel-test-service.ts b/backend/src/services/alert/alert-channel-test-service.tsnew file mode 100644index 0000000000..2ecdc6be7d--- /dev/null+++ b/backend/src/services/alert/alert-channel-test-service.ts@@ -0,0 +1,204 @@+import crypto from "node:crypto";++import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";+import { BadRequestError, NotFoundError, RateLimitError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { TSmtpService } from "@app/services/smtp/smtp-service";++import {+ assertChannelConfigValid,+ getChannelDefinition,+ mergeChannelConfigWithStored+} from "./alert-channel-config-fns";+import { decryptChannelConfig, getAlertChannelCipher } from "./alert-channel-crypto-fns";+import { TAlertChannelDALFactory } from "./alert-channel-dal";+import { TAlertChannelDeps, TAlertPayload, TAlertRecipient } from "./alert-channel-types";+import { TAlertProviderRegistry } from "./alert-provider-registry";+import { TAlertRecipientResolver } from "./alert-recipient-resolver";+import { TTestAlertChannelDTO, TTestAlertChannelResponse } from "./alert-service-types";+import { AlertPermissionAction, IResourceAlertProvider, TAlertContext } from "./alert-types";++export type TAlertChannelTestServiceFactoryDep = {+ alertChannelDAL: Pick<TAlertChannelDALFactory, "findById">;+ alertRecipientResolver: Pick<TAlertRecipientResolver, "resolveMany">;+ alertProviderRegistry: TAlertProviderRegistry;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ smtpService: Pick<TSmtpService, "sendMail">;+ keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX" | "ttl">;+};++export type TAlertChannelTestServiceFactory = ReturnType<typeof alertChannelTestServiceFactory>;++const TEST_CHANNEL_ID = "test";+const MAX_TEST_RECIPIENTS = 10;+const MAX_ERROR_LENGTH = 300;++export const alertChannelTestServiceFactory = ({+ alertChannelDAL,+ alertRecipientResolver,+ alertProviderRegistry,+ kmsService,+ smtpService,+ keyStore+}: TAlertChannelTestServiceFactoryDep) => {+ const $assertCooldown = async (orgId: string, actorId: string, channelType: string) => {+ const windows = [+ { key: KeyStorePrefixes.AlertChannelTestOrgCooldown(orgId, channelType), scope: "organization" },+ { key: KeyStorePrefixes.AlertChannelTestActorCooldown(actorId, channelType), scope: "you" }+ ];++ for (const { key, scope } of windows) {+ // eslint-disable-next-line no-await-in-loop -- the org window must settle before the actor's is spent+ const acquired = await keyStore.setItemWithExpiryNX(key, KeyStoreTtls.AlertChannelTestCooldownInSeconds, "1");+ if (!acquired) {+ // eslint-disable-next-line no-await-in-loop+ const remaining = await keyStore.ttl(key);+ const seconds = remaining > 0 ? remaining : KeyStoreTtls.AlertChannelTestCooldownInSeconds;+ throw new RateLimitError({+ message: `A ${channelType} test was already sent by ${scope} in the last minute. Try again in ${seconds}s.`+ });+ }+ }+ };++ const $resolveConfig = async (dto: TTestAlertChannelDTO, projectId: string | null) => {+ const definition = getChannelDefinition(dto.channelType);+ const incoming = dto.config ?? {};++ if (!dto.channelId) {+ assertChannelConfigValid(definition, dto.channelType, incoming);+ return incoming;+ }++ const channel = await alertChannelDAL.findById(dto.channelId);+ if (!channel || channel.orgId !== dto.actorOrgId || (channel.projectId ?? null) !== projectId) {+ throw new NotFoundError({ message: `Channel with ID '${dto.channelId}' was not found in this scope` });+ }+ if (channel.channelType !== dto.channelType) {+ throw new BadRequestError({+ message: `Channel '${dto.channelId}' is a ${channel.channelType} channel, not ${dto.channelType}`+ });+ }++ const { decryptor } = await getAlertChannelCipher(kmsService, {+ orgId: channel.orgId,+ projectId: channel.projectId+ });+ const stored = decryptChannelConfig<Record<string, unknown>>(channel.encryptedConfig, decryptor);++ const merged = mergeChannelConfigWithStored(dto.channelType, incoming, stored);+ assertChannelConfigValid(definition, dto.channelType, merged);+ return merged;+ };++ const $resolveRecipients = async (+ dto: TTestAlertChannelDTO,+ projectId: string | null+ ): Promise<TAlertRecipient[]> => {+ const rows = dto.recipients ?? [];+ if (rows.length === 0) return [];++ const resolved = await alertRecipientResolver.resolveMany(new Map([[TEST_CHANNEL_ID, rows]]), {+ orgId: dto.actorOrgId,+ projectId+ });+ return (resolved.get(TEST_CHANNEL_ID) ?? []).slice(0, MAX_TEST_RECIPIENTS);+ };++ const $buildTestPayload = async (+ provider: IResourceAlertProvider,+ dto: TTestAlertChannelDTO,+ projectId: string | null+ ): Promise<TAlertPayload> => {+ const alertContext: TAlertContext = {+ id: crypto.randomUUID(),+ name: "Test alert",+ orgId: dto.actorOrgId,+ projectId,+ resourceType: provider.resourceType,+ resourceId: dto.resourceId ?? null,+ eventType: provider.eventTypes[0],+ condition: null+ };++ const viewUrl = await provider.buildViewUrl(alertContext);+ const payload = provider.buildPayload(alertContext, provider.buildTestTargets(), viewUrl);++ return {+ ...payload,+ severity: "info",+ summary: `Test notification from Infisical. A real ${payload.resourceKind} ${payload.eventLabel.toLowerCase()} alert would look like this. No action is needed.`+ };+ };++ const $toError = (err: unknown): string => {+ const message = err instanceof Error ? err.message : String(err);+ return message.slice(0, MAX_ERROR_LENGTH);+ };++ const testChannel = async (dto: TTestAlertChannelDTO): Promise<TTestAlertChannelResponse> => {+ const definition = getChannelDefinition(dto.channelType);++ const provider = alertProviderRegistry.get(dto.resourceType);+ if (!provider) {+ throw new BadRequestError({+ message: `No alert provider is registered for resource type '${dto.resourceType}'`+ });+ }++ const projectId = dto.projectId ?? null;++ await provider.assertPermission({+ action: AlertPermissionAction.Create,+ orgId: dto.actorOrgId,+ projectId,+ resourceId: dto.resourceId,+ actor: {+ actor: dto.actor,+ actorId: dto.actorId,+ actorAuthMethod: dto.actorAuthMethod,+ actorOrgId: dto.actorOrgId+ }+ });+ await provider.assertResourceInScope({ orgId: dto.actorOrgId, projectId, resourceId: dto.resourceId });++ const config = await $resolveConfig(dto, projectId);+ const recipients = definition.directed ? await $resolveRecipients(dto, projectId) : [];+ if (definition.directed && recipients.length === 0) {+ return { success: false, error: `No ${dto.channelType} recipients could be resolved in this scope` };+ }++ // Last, so a rejected config or an unresolvable recipient doesn't spend the window.+ await $assertCooldown(dto.actorOrgId, dto.actorId, dto.channelType);++ const deps: TAlertChannelDeps = { smtpService };+ const payload = await $buildTestPayload(provider, dto, projectId);++ try {+ if (!definition.directed) {+ const result = await definition.send({ channelId: TEST_CHANNEL_ID, config, payload, deps });+ if (!result.success) return { success: false, error: result.error ?? "Delivery failed" };+ return { success: true, deliveredTo: 1 };+ }++ const results = await Promise.all(+ recipients.map((recipient) => definition.send({ channelId: TEST_CHANNEL_ID, config, payload, recipient, deps }))+ );+ const delivered = results.filter((result) => result.success);+ if (delivered.length === 0) {+ return { success: false, error: results.find((result) => result.error)?.error ?? "Delivery failed" };+ }+ return { success: true, deliveredTo: delivered.length };+ } catch (err) {+ const error = $toError(err);+ logger.info(+ { channelType: dto.channelType, error },+ `Alert channel test delivery failed [channelType=${dto.channelType}] [orgId=${dto.actorOrgId}]`+ );+ return { success: false, error };+ }+ };++ return { testChannel };+};diff --git a/backend/src/services/alert/alert-service-types.ts b/backend/src/services/alert/alert-service-types.tsindex b9534c2e12..6d6b2cf977 100644--- a/backend/src/services/alert/alert-service-types.ts+++ b/backend/src/services/alert/alert-service-types.ts@@ -1,6 +1,7 @@import { TGenericPermission } from "@app/lib/types";-import { TAlertChannelEmbedded, TAlertChannelInput } from "./alert-channel-service-types";+import { TAlertChannelEmbedded, TAlertChannelInput, TChannelRecipientInput } from "./alert-channel-service-types";+import { AlertChannelType } from "./alert-channel-types";export type TCreateAlertDTO = TGenericPermission & {name: string;@@ -34,6 +35,24 @@ export type TListAlertsDTO = TGenericPermission & {enabled?: boolean;};+// A test runs against a channel the caller is still authoring, so it carries the config inline rather+// than an alert id. `channelId` is optional and only names a saved channel to inherit secrets from.+export type TTestAlertChannelDTO = TGenericPermission & {+ resourceType: string;+ resourceId?: string | null;+ projectId?: string | null;+ channelId?: string;+ channelType: AlertChannelType;+ config?: Record<string, unknown>;+ recipients?: TChannelRecipientInput[];+};++export type TTestAlertChannelResponse = {+ success: boolean;+ deliveredTo?: number;+ error?: string;+};+export type TAlertResponse = {id: string;name: string;diff --git a/backend/src/services/alert/alert-service.test.ts b/backend/src/services/alert/alert-service.test.tsindex 91ff01e42e..af2c9d6a44 100644--- a/backend/src/services/alert/alert-service.test.ts+++ b/backend/src/services/alert/alert-service.test.ts@@ -34,6 +34,7 @@ const buildService = (opts?: {buildViewUrl: async () => "https://app.infisical.com/x",buildPayload: () => ({}) as TAlertPayload,targetId: () => "t",+ buildTestTargets: () => [],assertPermission: async (input) => {permissionCalls.push(input);if (opts?.assertPermission) await opts.assertPermission(input);diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.tsindex 158bf50440..1466da9fcb 100644--- a/backend/src/services/alert/alert-types.ts+++ b/backend/src/services/alert/alert-types.ts@@ -94,6 +94,11 @@ export interface IResourceAlertProvider<TTarget = unknown> {// Stable id per target, used for dedup and history. Must be stable across cron runs.targetId(target: TTarget): string;+ // Representative targets used to render a "send test" delivery, so what a user sees when testing a+ // channel is the same shape a real firing produces. Purely synthetic: never queried, stored, or+ // deduped against history, so the ids need not correspond to real rows.+ buildTestTargets(): TTarget[];+// Optional per-condition dedup window override (hours). Defaults to DEFAULT_DEDUP_WINDOW_HOURS.dedupWindowHours?(condition: unknown): number;diff --git a/backend/src/services/alert/providers/identity-credential-alert-provider.ts b/backend/src/services/alert/providers/identity-credential-alert-provider.tsindex 39a8f21e51..817930c484 100644--- a/backend/src/services/alert/providers/identity-credential-alert-provider.ts+++ b/backend/src/services/alert/providers/identity-credential-alert-provider.ts@@ -83,6 +83,9 @@ const CREDENTIAL_TYPE_LABEL: Record<TIdentityCredentialTarget["credentialType"],"ua-client-secret": "Universal Auth Client Secret"};+const TEST_TARGET_ID = "00000000-0000-0000-0000-000000000000";+const TEST_TARGET_EXPIRES_IN_DAYS = 7;+export type TIdentityCredentialAlertProviderDep = {identityCredentialAlertDAL: TIdentityCredentialAlertDALFactory;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;@@ -178,6 +181,18 @@ export const identityCredentialAlertProviderFactory = ({const targetId = (target: TIdentityCredentialTarget): string => `${target.credentialType}:${target.id}`;+ const buildTestTargets = (): TIdentityCredentialTarget[] => [+ {+ credentialType: "ua-client-secret",+ id: TEST_TARGET_ID,+ identityId: TEST_TARGET_ID,+ identityName: "Sample Machine Identity",+ description: "Sample Client Secret",+ clientSecretPrefix: "abcd",+ expiresAt: new Date(Date.now() + TEST_TARGET_EXPIRES_IN_DAYS * 24 * 60 * 60 * 1000)+ }+ ];+const assertResourceInScope = async (input: {orgId: string;projectId?: string | null;@@ -271,6 +286,7 @@ export const identityCredentialAlertProviderFactory = ({buildViewUrl,buildPayload,targetId,+ buildTestTargets,dedupWindowHours: (condition) => {const parsed = IdentityCredentialConditionSchema.safeParse(condition);if (!parsed.success) return DEFAULT_DEDUP_WINDOW_HOURS;diff --git a/frontend/src/hooks/api/alerts/mutations.ts b/frontend/src/hooks/api/alerts/mutations.tsindex 4176381917..5372d9e40c 100644--- a/frontend/src/hooks/api/alerts/mutations.ts+++ b/frontend/src/hooks/api/alerts/mutations.ts@@ -3,7 +3,13 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";import { alertKeys } from "./queries";-import { TAlert, TCreateAlertDTO, TUpdateAlertDTO } from "./types";+import {+ TAlert,+ TCreateAlertDTO,+ TTestAlertChannelDTO,+ TTestAlertChannelResponse,+ TUpdateAlertDTO+} from "./types";export const useCreateAlert = () => {const queryClient = useQueryClient();@@ -33,6 +39,17 @@ export const useUpdateAlert = () => {});};+export const useTestAlertChannel = () =>+ useMutation<TTestAlertChannelResponse, unknown, TTestAlertChannelDTO>({+ mutationFn: async (dto) => {+ const { data } = await apiRequest.post<TTestAlertChannelResponse>(+ "/api/v1/alerts/channels/test",+ dto+ );+ return data;+ }+ });+export const useDeleteAlert = () => {const queryClient = useQueryClient();diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.tsindex 3b80403be3..74b50ecbbf 100644--- a/frontend/src/hooks/api/alerts/types.ts+++ b/frontend/src/hooks/api/alerts/types.ts@@ -95,6 +95,22 @@ export type TCreateAlertDTO = {channels: TAlertChannelInput[];};+export type TTestAlertChannelDTO = {+ resourceType: string;+ resourceId?: string | null;+ projectId?: string | null;+ channelId?: string;+ channelType: AlertChannelType;+ config?: Record<string, unknown>;+ recipients?: TAlertChannelRecipient[];+};++export type TTestAlertChannelResponse = {+ success: boolean;+ deliveredTo?: number;+ error?: string;+};+export type TUpdateAlertDTO = {alertId: string;name?: string;diff --git a/frontend/src/hooks/api/alerts/utils.ts b/frontend/src/hooks/api/alerts/utils.tsindex c8e46f95b7..9821494905 100644--- a/frontend/src/hooks/api/alerts/utils.ts+++ b/frontend/src/hooks/api/alerts/utils.ts@@ -1,3 +1,36 @@+import { AlertChannelType, TAlertChannelInput, TChannelForm } from "./types";++export const toChannelInput = (channel: TChannelForm): TAlertChannelInput => {+ const base: TAlertChannelInput = {+ ...(channel.id ? { id: channel.id } : {}),+ name: channel.name,+ channelType: channel.channelType,+ enabled: channel.enabled+ };++ switch (channel.channelType) {+ case AlertChannelType.Email:+ return { ...base, config: {}, recipients: channel.recipients };+ case AlertChannelType.Slack:+ return { ...base, config: channel.webhookUrl ? { webhookUrl: channel.webhookUrl } : {} };+ case AlertChannelType.Webhook:+ return {+ ...base,+ config: {+ url: channel.url,+ ...(channel.signingSecret ? { signingSecret: channel.signingSecret } : {})+ }+ };+ case AlertChannelType.PagerDuty:+ return {+ ...base,+ config: channel.integrationKey ? { integrationKey: channel.integrationKey } : {}+ };+ default:+ return { ...base, config: {} };+ }+};+// The backend stores an alert's lead time as a whole number of days, e.g. "30d".const ALERT_BEFORE_PATTERN = /^(\d+)d$/;diff --git a/frontend/src/views/Alerts/AlertForm.tsx b/frontend/src/views/Alerts/AlertForm.tsxindex b213bc9827..79f06c6d3f 100644--- a/frontend/src/views/Alerts/AlertForm.tsx+++ b/frontend/src/views/Alerts/AlertForm.tsx@@ -1,5 +1,5 @@import { ReactNode } from "react";-import { Controller, FormProvider, useForm } from "react-hook-form";+import { Controller, FormProvider, useForm, useWatch } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { CircleHelpIcon, FingerprintIcon, KeyRoundIcon } from "lucide-react";@@ -32,7 +32,6 @@ import { useScopeVariant } from "@app/hooks";import {ALERT_EVENT_TYPE_LABELS,ALERT_RESOURCE_TYPE_LABELS,- AlertChannelType,AlertEventType,alertFormSchema,AlertResourceType,@@ -40,10 +39,10 @@ import {MIN_ALERT_BEFORE_DAYS,parseAlertBeforeDays,TAlert,- TAlertChannelInput,TAlertForm,TChannelForm,toAlertBefore,+ toChannelInput,useCreateAlert,useUpdateAlert} from "@app/hooks/api/alerts";@@ -116,37 +115,6 @@ const buildFormDefaults = (alert?: TAlert): TAlertForm => {};};-const toChannelInput = (channel: TChannelForm): TAlertChannelInput => {- const base: TAlertChannelInput = {- ...(channel.id ? { id: channel.id } : {}),- name: channel.name,- channelType: channel.channelType,- enabled: channel.enabled- };-- switch (channel.channelType) {- case AlertChannelType.Email:- return { ...base, config: {}, recipients: channel.recipients };- case AlertChannelType.Slack:- return { ...base, config: channel.webhookUrl ? { webhookUrl: channel.webhookUrl } : {} };- case AlertChannelType.Webhook:- return {- ...base,- config: {- url: channel.url,- ...(channel.signingSecret ? { signingSecret: channel.signingSecret } : {})- }- };- case AlertChannelType.PagerDuty:- return {- ...base,- config: channel.integrationKey ? { integrationKey: channel.integrationKey } : {}- };- default:- return { ...base, config: {} };- }-};-export const AlertForm = ({projectId,scopeName,@@ -173,6 +141,7 @@ export const AlertForm = ({formState: { errors, isSubmitting }} = formMethods;+ const resourceTypeValue = useWatch({ control, name: "resourceType" });const isProjectScope = Boolean(projectId);const isResourceScope = Boolean(resourceId ?? alert?.resourceId);const resolveScopeIcon = () => {@@ -398,7 +367,11 @@ export const AlertForm = ({<section className="flex flex-col gap-4"><SectionHeader title="Delivery" />- <ChannelsField projectId={projectId} />+ <ChannelsField+ projectId={projectId}+ resourceType={resourceTypeValue}+ resourceId={resourceId ?? alert?.resourceId ?? null}+ /></section></div>diff --git a/frontend/src/views/Alerts/ChannelCard.tsx b/frontend/src/views/Alerts/ChannelCard.tsxindex fa561566a3..a89d1c5af7 100644--- a/frontend/src/views/Alerts/ChannelCard.tsx+++ b/frontend/src/views/Alerts/ChannelCard.tsx@@ -1,7 +1,9 @@import { Controller, useFormContext, useWatch } from "react-hook-form";-import { TrashIcon } from "lucide-react";+import { SendIcon, TrashIcon } from "lucide-react";+import { createNotification } from "@app/components/notifications";import {+ Button,Field,FieldContent,FieldError,@@ -11,7 +13,13 @@ import {Switch} from "@app/components/v3";import { useScopeVariant } from "@app/hooks";-import { ALERT_CHANNEL_TYPE_LABELS, AlertChannelType, TAlertForm } from "@app/hooks/api/alerts";+import {+ ALERT_CHANNEL_TYPE_LABELS,+ AlertChannelType,+ TAlertForm,+ toChannelInput,+ useTestAlertChannel+} from "@app/hooks/api/alerts";import { getChannelIcon } from "./channelIcons";import { ChannelRecipientsField } from "./ChannelRecipientsField";@@ -19,19 +27,31 @@ import { ChannelRecipientsField } from "./ChannelRecipientsField";type Props = {index: number;projectId?: string;+ resourceType: string;+ resourceId?: string | null;onRemove: () => void;canRemove: boolean;};const KEEP_PLACEHOLDER = "•••••••• (leave blank to keep)";-export const ChannelCard = ({ index, projectId, onRemove, canRemove }: Props) => {+export const ChannelCard = ({+ index,+ projectId,+ resourceType,+ resourceId,+ onRemove,+ canRemove+}: Props) => {const scopeVariant = useScopeVariant();const {control,register,+ getValues,+ trigger,formState: { errors }} = useFormContext<TAlertForm>();+ const testChannel = useTestAlertChannel();const channel = useWatch({ control, name: `channels.${index}` });const channelType = channel?.channelType;@@ -39,6 +59,41 @@ export const ChannelCard = ({ index, projectId, onRemove, canRemove }: Props) =>const channelErrors = errors.channels?.[index];const Icon = getChannelIcon(channelType);+ const channelLabel = ALERT_CHANNEL_TYPE_LABELS[channelType];++ const onTest = async () => {+ if (!(await trigger(`channels.${index}`))) return;++ const { config, recipients } = toChannelInput(getValues(`channels.${index}`));+ try {+ const result = await testChannel.mutateAsync({+ resourceType,+ resourceId,+ projectId: projectId ?? null,+ channelId: channel?.id,+ channelType,+ config,+ recipients+ });++ if (result.success) {+ createNotification({+ text: `Test ${channelLabel} notification sent${+ result.deliveredTo && result.deliveredTo > 1 ? ` to ${result.deliveredTo} recipients` : ""+ }`,+ type: "success"+ });+ } else {+ createNotification({+ title: `Test ${channelLabel} notification failed`,+ text: result.error ?? "The channel could not be reached.",+ type: "error"+ });+ }+ } catch {+ // MutationCache reports request errors (including the cooldown) globally.+ }+ };return (<div className="flex flex-col gap-4 rounded-md border border-border p-4">@@ -50,6 +105,17 @@ export const ChannelCard = ({ index, projectId, onRemove, canRemove }: Props) =></span></div><div className="flex items-center gap-3">+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={onTest}+ isPending={testChannel.isPending}+ isDisabled={testChannel.isPending}+ >+ <SendIcon className="size-3.5" />+ Send test+ </Button><Controllercontrol={control}name={`channels.${index}.enabled`}diff --git a/frontend/src/views/Alerts/ChannelsField.tsx b/frontend/src/views/Alerts/ChannelsField.tsxindex a5a6e51ecb..a1bcee8045 100644--- a/frontend/src/views/Alerts/ChannelsField.tsx+++ b/frontend/src/views/Alerts/ChannelsField.tsx@@ -22,6 +22,8 @@ import { getChannelIcon } from "./channelIcons";type Props = {projectId?: string;+ resourceType: string;+ resourceId?: string | null;};const buildNewChannel = (channelType: AlertChannelType): TChannelForm => ({@@ -35,7 +37,7 @@ const buildNewChannel = (channelType: AlertChannelType): TChannelForm => ({integrationKey: ""});-export const ChannelsField = ({ projectId }: Props) => {+export const ChannelsField = ({ projectId, resourceType, resourceId }: Props) => {const {control,formState: { errors }@@ -91,6 +93,8 @@ export const ChannelsField = ({ projectId }: Props) => {key={field.id}index={index}projectId={projectId}+ resourceType={resourceType}+ resourceId={resourceId}canRemove={fields.length > 1}onRemove={() => remove(index)}/>