Skip to content

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

feat(pki): add webhooks to alerts (#5327)

Saif Ur Rahmana27c6a2329a0
diff --git a/backend/src/db/migrations/20260129181800_add-encrypted-config-to-pki-alert-channels.ts b/backend/src/db/migrations/20260129181800_add-encrypted-config-to-pki-alert-channels.ts
new file mode 100644
index 0000000000..ff3d80101c
--- /dev/null
+++ b/backend/src/db/migrations/20260129181800_add-encrypted-config-to-pki-alert-channels.ts
@@ -0,0 +1,37 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.PkiAlertChannels)) {
+ const hasEncryptedConfig = await knex.schema.hasColumn(TableName.PkiAlertChannels, "encryptedConfig");
+ if (!hasEncryptedConfig) {
+ await knex.schema.alterTable(TableName.PkiAlertChannels, (t) => {
+ t.binary("encryptedConfig").nullable();
+ });
+ }
+
+ await knex.schema.alterTable(TableName.PkiAlertChannels, (t) => {
+ t.jsonb("config").nullable().alter();
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.PkiAlertChannels)) {
+ const hasEncryptedConfig = await knex.schema.hasColumn(TableName.PkiAlertChannels, "encryptedConfig");
+ if (hasEncryptedConfig) {
+ await knex.schema.alterTable(TableName.PkiAlertChannels, (t) => {
+ t.dropColumn("encryptedConfig");
+ });
+ }
+
+ // Ensure all rows have config populated before making NOT NULL
+ // (encrypted-only channels would have config=null)
+ await knex(TableName.PkiAlertChannels).whereNull("config").update({ config: {} });
+
+ await knex.schema.alterTable(TableName.PkiAlertChannels, (t) => {
+ t.jsonb("config").notNullable().alter();
+ });
+ }
+}
diff --git a/backend/src/db/migrations/20260202042111_add-pki-alert-history-composite-index.ts b/backend/src/db/migrations/20260202042111_add-pki-alert-history-composite-index.ts
new file mode 100644
index 0000000000..84285597f1
--- /dev/null
+++ b/backend/src/db/migrations/20260202042111_add-pki-alert-history-composite-index.ts
@@ -0,0 +1,34 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+const INDEX_NAME = "pki_alert_history_alert_id_triggered_at_idx";
+
+export async function up(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.PkiAlertHistory)) {
+ const hasAlertId = await knex.schema.hasColumn(TableName.PkiAlertHistory, "alertId");
+ const hasTriggeredAt = await knex.schema.hasColumn(TableName.PkiAlertHistory, "triggeredAt");
+
+ if (hasAlertId && hasTriggeredAt) {
+ const indexExists = await knex.raw(`SELECT 1 FROM pg_indexes WHERE indexname = ?`, [INDEX_NAME]);
+
+ if (indexExists.rows.length === 0) {
+ await knex.schema.alterTable(TableName.PkiAlertHistory, (t) => {
+ t.index(["alertId", "triggeredAt"], INDEX_NAME);
+ });
+ }
+ }
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.PkiAlertHistory)) {
+ const indexExists = await knex.raw(`SELECT 1 FROM pg_indexes WHERE indexname = ?`, [INDEX_NAME]);
+
+ if (indexExists.rows.length > 0) {
+ await knex.schema.alterTable(TableName.PkiAlertHistory, (t) => {
+ t.dropIndex(["alertId", "triggeredAt"], INDEX_NAME);
+ });
+ }
+ }
+}
diff --git a/backend/src/db/schemas/pki-alert-channels.ts b/backend/src/db/schemas/pki-alert-channels.ts
index 1101a96071..1a0d9510e1 100644
--- a/backend/src/db/schemas/pki-alert-channels.ts
+++ b/backend/src/db/schemas/pki-alert-channels.ts
@@ -5,16 +5,19 @@
import { z } from "zod";
+import { zodBuffer } from "@app/lib/zod";
+
import { TImmutableDBKeys } from "./models";
export const PkiAlertChannelsSchema = z.object({
id: z.string().uuid(),
alertId: z.string().uuid(),
channelType: z.string(),
- config: z.unknown(),
+ config: z.unknown().nullable().optional(),
enabled: z.boolean().default(true).nullable().optional(),
createdAt: z.date(),
- updatedAt: z.date()
+ updatedAt: z.date(),
+ encryptedConfig: zodBuffer.nullable().optional()
});
export type TPkiAlertChannels = z.infer<typeof PkiAlertChannelsSchema>;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 54bd53aa35..66b66e10ae 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1942,7 +1942,11 @@ export const registerRoutes = async (
pkiAlertChannelDAL,
pkiAlertHistoryDAL,
permissionService,
- smtpService
+ smtpService,
+ kmsService,
+ notificationService,
+ projectMembershipDAL,
+ projectDAL
});
const pkiAlertV2Queue = pkiAlertV2QueueServiceFactory({
diff --git a/backend/src/server/routes/v1/pki-alert-router.ts b/backend/src/server/routes/v1/pki-alert-router.ts
index 05b6f69542..4e5f5b0dde 100644
--- a/backend/src/server/routes/v1/pki-alert-router.ts
+++ b/backend/src/server/routes/v1/pki-alert-router.ts
@@ -10,6 +10,7 @@ import {
createSecureAlertBeforeValidator,
PkiAlertChannelType,
PkiAlertEventType,
+ PkiAlertRunStatus,
PkiFilterRuleSchema,
UpdatePkiAlertV2Schema
} from "@app/services/pki-alert-v2/pki-alert-v2-types";
@@ -125,6 +126,13 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
updatedAt: z.date()
})
),
+ lastRun: z
+ .object({
+ timestamp: z.date(),
+ status: z.nativeEnum(PkiAlertRunStatus),
+ error: z.string().nullable()
+ })
+ .nullable(),
createdAt: z.date(),
updatedAt: z.date()
})
diff --git a/backend/src/server/routes/v2/pki-alert-router.ts b/backend/src/server/routes/v2/pki-alert-router.ts
index e5b730698c..786496e57f 100644
--- a/backend/src/server/routes/v2/pki-alert-router.ts
+++ b/backend/src/server/routes/v2/pki-alert-router.ts
@@ -10,6 +10,7 @@ import {
createSecureAlertBeforeValidator,
PkiAlertChannelType,
PkiAlertEventType,
+ PkiAlertRunStatus,
PkiFilterRuleSchema,
UpdatePkiAlertV2Schema
} from "@app/services/pki-alert-v2/pki-alert-v2-types";
@@ -123,6 +124,13 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
updatedAt: z.date()
})
),
+ lastRun: z
+ .object({
+ timestamp: z.date(),
+ status: z.nativeEnum(PkiAlertRunStatus),
+ error: z.string().nullable()
+ })
+ .nullable(),
createdAt: z.date(),
updatedAt: z.date()
})
@@ -447,4 +455,46 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
return result;
}
});
+
+ server.route({
+ method: "POST",
+ url: "/test-webhook",
+ config: {
+ rateLimit: writeLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ operationId: "testPkiAlertWebhook",
+ description: "Test a webhook configuration by sending a test payload",
+ tags: [ApiDocsTags.PkiAlerting],
+ body: z.object({
+ projectId: z.string().uuid().describe("Project ID for permission check"),
+ url: z
+ .string()
+ .url()
+ .refine((url) => url.startsWith("https://"), "Webhook URL must use HTTPS")
+ .describe("Webhook URL to test"),
+ signingSecret: z.string().max(256).optional().describe("Optional signing secret for HMAC signature")
+ }),
+ response: {
+ 200: z.object({
+ success: z.boolean(),
+ error: z.string().optional()
+ })
+ }
+ },
+ handler: async (req) => {
+ const result = await server.services.pkiAlertV2.testWebhookConfig({
+ projectId: req.body.projectId,
+ url: req.body.url,
+ signingSecret: req.body.signingSecret,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ return result;
+ }
+ });
};
diff --git a/backend/src/services/notification/notification-types.ts b/backend/src/services/notification/notification-types.ts
index 56045174a5..a788c68712 100644
--- a/backend/src/services/notification/notification-types.ts
+++ b/backend/src/services/notification/notification-types.ts
@@ -18,7 +18,8 @@ export enum NotificationType {
SECRET_SYNC_FAILED = "secret-sync-failed",
GATEWAY_HEALTH_ALERT = "gateway-health-alert",
RELAY_HEALTH_ALERT = "relay-health-alert",
- APPROVAL_REQUIRED = "approval-required"
+ APPROVAL_REQUIRED = "approval-required",
+ PKI_ALERT_CHANNEL_FAILED = "pki-alert-channel-failed"
}
export interface TCreateUserNotificationDTO {
diff --git a/backend/src/services/pki-alert-v2/pki-alert-channel-dal.ts b/backend/src/services/pki-alert-v2/pki-alert-channel-dal.ts
index b16432a346..fce2902cfe 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-channel-dal.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-channel-dal.ts
@@ -14,12 +14,7 @@ export const pkiAlertChannelDALFactory = (db: TDbClient) => {
try {
if (!data.length) return [];
- const serializedData = data.map((item) => ({
- ...item,
- config: item.config ? JSON.stringify(item.config) : null
- }));
-
- const res = await (tx || db)(TableName.PkiAlertChannels).insert(serializedData).returning("*");
+ const res = await (tx || db)(TableName.PkiAlertChannels).insert(data).returning("*");
return res as TPkiAlertChannels[];
} catch (error) {
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-channel-email-fns.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-channel-email-fns.ts
new file mode 100644
index 0000000000..81f8e69432
--- /dev/null
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-channel-email-fns.ts
@@ -0,0 +1,83 @@
+import { delay } from "@app/lib/delay";
+import { logger } from "@app/lib/logger";
+import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
+
+import { PKI_ALERT_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "./pki-alert-v2-constants";
+import { TCertificatePreview, TChannelResult, TEmailChannelConfig } from "./pki-alert-v2-types";
+
+const isEmailErrorRetryable = (err: Error): boolean => {
+ const msg = err.message.toLowerCase();
+ if (RETRYABLE_NETWORK_ERRORS.some((code) => msg.includes(code.toLowerCase()))) return true;
+ if (msg.includes("timeout") || msg.includes("connection")) return true;
+ if (["421", "450", "451", "452"].some((code) => msg.includes(code))) return true;
+ return false;
+};
+
+export const sendEmailNotification = async (
+ smtpService: Pick<TSmtpService, "sendMail">,
+ config: TEmailChannelConfig,
+ alertName: string,
+ alertBeforeDays: number,
+ projectId: string,
+ matchingCertificates: TCertificatePreview[]
+): Promise<void> => {
+ await smtpService.sendMail({
+ recipients: config.recipients,
+ subjectLine: `Infisical Certificate Alert - ${alertName}`,
+ substitutions: {
+ alertName,
+ alertBeforeDays,
+ projectId,
+ items: matchingCertificates.map((cert) => ({
+ type: "Certificate",
+ friendlyName: cert.commonName,
+ serialNumber: cert.serialNumber,
+ expiryDate: cert.notAfter.toLocaleDateString()
+ }))
+ },
+ template: SmtpTemplates.PkiExpirationAlert
+ });
+};
+
+export const sendEmailNotificationWithRetry = async (
+ smtpService: Pick<TSmtpService, "sendMail">,
+ config: TEmailChannelConfig,
+ alertName: string,
+ alertBeforeDays: number,
+ projectId: string,
+ matchingCertificates: TCertificatePreview[],
+ alertId: string
+): Promise<TChannelResult> => {
+ const { maxRetries, delayMs } = PKI_ALERT_RETRY_CONFIG;
+ let lastError: Error | undefined;
+
+ for (let attempt = 1; attempt <= maxRetries; attempt += 1) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ await sendEmailNotification(smtpService, config, alertName, alertBeforeDays, projectId, matchingCertificates);
+ return { success: true };
+ } catch (err) {
+ lastError = err instanceof Error ? err : new Error(String(err));
+
+ if (!isEmailErrorRetryable(lastError)) {
+ logger.info(
+ { alertId, recipients: config.recipients, error: lastError.message },
+ "PKI email error is not retryable (permanent SMTP error)"
+ );
+ return { success: false, error: lastError.message };
+ }
+
+ logger.info(
+ { alertId, recipients: config.recipients, attempt, maxRetries, error: lastError.message },
+ `PKI email failed, ${attempt < maxRetries ? `retrying in ${delayMs}ms` : "no more retries"}`
+ );
+
+ if (attempt < maxRetries) {
+ // eslint-disable-next-line no-await-in-loop
+ await delay(delayMs);
+ }
+ }
+ }
+
+ return { success: false, error: lastError?.message };
+};
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-channel-webhook-fns.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-channel-webhook-fns.ts
new file mode 100644
index 0000000000..52198a5d00
--- /dev/null
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-channel-webhook-fns.ts
@@ -0,0 +1,242 @@
+import crypto from "node:crypto";
+
+import { AxiosError } from "axios";
+
+import { getConfig } from "@app/lib/config/env";
+import { request } from "@app/lib/config/request";
+import { delay } from "@app/lib/delay";
+import { logger } from "@app/lib/logger";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator/validate-url";
+
+import { PKI_ALERT_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "./pki-alert-v2-constants";
+import {
+ PkiWebhookEventType,
+ TAlertInfo,
+ TCertificateData,
+ TCertificatePreview,
+ TChannelResult,
+ TPkiWebhookPayload,
+ TWebhookChannelConfig
+} from "./pki-alert-v2-types";
+
+const PKI_WEBHOOK_TIMEOUT = 7 * 1000;
+
+const isWebhookErrorRetryable = (err: AxiosError): boolean => {
+ const status = err.response?.status;
+ if (status && status >= 500) return true;
+ if (err.code && RETRYABLE_NETWORK_ERRORS.includes(err.code)) return true;
+ if (err.message?.toLowerCase().includes("timeout")) return true;
+ return false;
+};
+
+// Base CloudEvents envelope fields
+type TPkiWebhookBase = Pick<TPkiWebhookPayload, "specversion" | "type" | "source" | "id" | "time" | "datacontenttype">;
+
+// Event-specific payload structure (reuses TPkiWebhookPayload fields for type safety)
+type TBaseEventPayload = Pick<TPkiWebhookPayload, "subject" | "data">;
+
+type TBuildWebhookPayloadParams = {
+ alert: TAlertInfo;
+ certificates: TCertificatePreview[];
+ eventType: PkiWebhookEventType;
+ appUrl?: string;
+};
+
+// Builds CloudEvents envelope (shared across all events)
+const buildBasePayload = (params: {
+ eventType: PkiWebhookEventType;
+ projectId: string;
+ alertId: string;
+}): TPkiWebhookBase => ({
+ specversion: "1.0" as const,
+ type: params.eventType,
+ source: `/projects/${params.projectId}/alerts/${params.alertId}`,
+ id: crypto.randomUUID(),
+ time: new Date().toISOString(),
+ datacontenttype: "application/json" as const
+});
+
+// Transforms certificate previews to webhook payload format
+const transformCertificates = (certificates: TCertificatePreview[]): TCertificateData[] => {
+ const now = new Date();
+
+ return certificates.map((cert) => {
+ const notAfter = new Date(cert.notAfter);
+ const daysUntilExpiry = Math.ceil((notAfter.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
+
+ return {
+ id: cert.id,
+ serialNumber: cert.serialNumber,
+ commonName: cert.commonName,
+ san: cert.san,
+ profileName: cert.profileName,
+ notBefore: cert.notBefore.toISOString(),
+ notAfter: cert.notAfter.toISOString(),
+ status: cert.status,
+ daysUntilExpiry
+ };
+ });
+};
+
+// Event-specific data builders
+const buildCertificateExpirationEventData = (params: {
+ alert: TAlertInfo;
+ certificates: TCertificatePreview[];
+ appUrl: string;
+}): TBaseEventPayload => ({
+ subject: "certificate-expiration-alert",
+ data: {
+ alert: {
+ id: params.alert.id,
+ name: params.alert.name,
+ alertBefore: params.alert.alertBefore,
+ projectId: params.alert.projectId
+ },
+ certificates: transformCertificates(params.certificates),
+ metadata: {
+ totalCertificates: params.certificates.length,
+ viewUrl: `${params.appUrl}/projects/cert-manager/${params.alert.projectId}/policies`
+ }
+ }
+});
+
+const buildCertificateTestEventData = (params: {
+ alert: TAlertInfo;
+ certificates: TCertificatePreview[];
+ appUrl: string;
+}): TBaseEventPayload => ({
+ subject: "certificate-test",
+ data: {
+ alert: {
+ id: params.alert.id,
+ name: params.alert.name,
+ alertBefore: params.alert.alertBefore,
+ projectId: params.alert.projectId
+ },
+ certificates: transformCertificates(params.certificates),
+ metadata: {
+ totalCertificates: params.certificates.length,
+ viewUrl: `${params.appUrl}/projects/cert-manager/${params.alert.projectId}/policies`
+ }
+ }
+});
+
+export const buildWebhookPayload = ({
+ alert,
+ certificates,
+ eventType,
+ appUrl = "https://app.infisical.com"
+}: TBuildWebhookPayloadParams): TPkiWebhookPayload => {
+ const base = buildBasePayload({
+ eventType,
+ projectId: alert.projectId,
+ alertId: alert.id
+ });
+
+ const eventParams = { alert, certificates, appUrl };
+
+ const eventData = (() => {
+ switch (eventType) {
+ case PkiWebhookEventType.CERTIFICATE_EXPIRATION:
+ return buildCertificateExpirationEventData(eventParams);
+ case PkiWebhookEventType.CERTIFICATE_TEST:
+ return buildCertificateTestEventData(eventParams);
+ default:
+ throw new Error(`Unknown PKI webhook event type: ${eventType as string}`);
+ }
+ })();
+
+ return { ...base, ...eventData };
+};
+
+const generateHmacSignature = (payload: string, secret: string): string => {
+ return crypto.createHmac("sha256", secret).update(payload).digest("hex");
+};
+
+const triggerPkiWebhook = async (params: {
+ url: string;
+ payload: TPkiWebhookPayload;
+ signingSecret?: string;
+}): Promise<void> => {
+ const { url, payload, signingSecret } = params;
+ const headers: Record<string, string> = {
+ "Content-Type": "application/json"
+ };
+
+ const payloadString = JSON.stringify(payload);
+ const timestamp = Date.now();
+
+ if (signingSecret) {
+ const signaturePayload = `${timestamp}.${payloadString}`;
+ const signature = generateHmacSignature(signaturePayload, signingSecret);
+ headers["x-infisical-signature"] = `t=${timestamp},v1=${signature}`;
+ }
+
+ await request.post(url, payload, {
+ headers,
+ timeout: PKI_WEBHOOK_TIMEOUT,
+ signal: AbortSignal.timeout(PKI_WEBHOOK_TIMEOUT)
+ });
+};
+
+const triggerPkiWebhookWithRetry = async (params: {
+ url: string;
+ payload: TPkiWebhookPayload;
+ signingSecret?: string;
+}): Promise<TChannelResult> => {
+ const { maxRetries, delayMs } = PKI_ALERT_RETRY_CONFIG;
+ let lastError: AxiosError | undefined;
+
+ for (let attempt = 1; attempt <= maxRetries; attempt += 1) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ await triggerPkiWebhook(params);
+ return { success: true };
+ } catch (err) {
+ lastError = err as AxiosError;
+
+ if (!isWebhookErrorRetryable(lastError)) {
+ logger.info(
+ { url: params.url, statusCode: lastError.response?.status, error: lastError.message },
+ "PKI webhook error is not retryable (4xx or non-transient error)"
+ );
+ return { success: false, error: lastError.message };
+ }
+
+ logger.info(
+ { url: params.url, attempt, maxRetries, statusCode: lastError.response?.status, error: lastError.message },
+ `PKI webhook failed, ${attempt < maxRetries ? `retrying in ${delayMs}ms` : "no more retries"}`
+ );
+
+ if (attempt < maxRetries) {
+ // eslint-disable-next-line no-await-in-loop
+ await delay(delayMs);
+ }
+ }
+ }
+
+ return { success: false, error: lastError?.message };
+};
+
+export const sendWebhookNotification = async (
+ config: TWebhookChannelConfig,
+ alertData: TAlertInfo,
+ matchingCertificates: TCertificatePreview[],
+ eventType: PkiWebhookEventType
+): Promise<TChannelResult> => {
+ await blockLocalAndPrivateIpAddresses(config.url);
+
+ const appCfg = getConfig();
+ const payload = buildWebhookPayload({
+ alert: alertData,
+ certificates: matchingCertificates,
+ eventType,
+ appUrl: appCfg.SITE_URL
+ });
+
+ return triggerPkiWebhookWithRetry({
+ url: config.url,
+ payload,
+ signingSecret: config.signingSecret ?? undefined
+ });
+};
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-constants.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-constants.ts
new file mode 100644
index 0000000000..c20f7bf29d
--- /dev/null
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-constants.ts
@@ -0,0 +1,11 @@
+export const PKI_ALERT_RETRY_CONFIG = { maxRetries: 3, delayMs: 3000 };
+
+export const RETRYABLE_NETWORK_ERRORS = [
+ "ECONNREFUSED",
+ "ENOTFOUND",
+ "ETIMEDOUT",
+ "ECONNRESET",
+ "ECONNABORTED",
+ "ENETUNREACH",
+ "EHOSTUNREACH"
+];
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-dal.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-dal.ts
index b93159ed01..73266f619e 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-v2-dal.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-dal.ts
@@ -16,6 +16,28 @@ import { CertificateOrigin, TCertificatePreview, TPkiFilterRule } from "./pki-al
export type TPkiAlertV2DALFactory = ReturnType<typeof pkiAlertV2DALFactory>;
+export type TChannelResult = {
+ id: string;
+ alertId: string;
+ channelType: string;
+ config: unknown;
+ encryptedConfig?: Buffer | null;
+ enabled: boolean;
+ createdAt: Date;
+ updatedAt: Date;
+};
+
+export type TLastRunData = {
+ triggeredAt: Date;
+ hasNotificationSent: boolean;
+ notificationError: string | null;
+};
+
+export type TAlertWithChannels = TPkiAlertsV2 & {
+ channels: TChannelResult[];
+ lastRunData: TLastRunData | null;
+};
+
export const pkiAlertV2DALFactory = (db: TDbClient) => {
const pkiAlertV2Orm = ormify(db, TableName.PkiAlertsV2);
@@ -65,20 +87,6 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
}
};
- type TChannelResult = {
- id: string;
- alertId: string;
- channelType: string;
- config: unknown;
- enabled: boolean;
- createdAt: Date;
- updatedAt: Date;
- };
-
- type TAlertWithChannels = TPkiAlertsV2 & {
- channels: TChannelResult[];
- };
-
const findByIdWithChannels = async (alertId: string, tx?: Knex): Promise<TAlertWithChannels | null> => {
try {
const [alert] = (await (tx || db.replicaNode())
@@ -93,9 +101,36 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
.from(TableName.PkiAlertChannels)
.where(`${TableName.PkiAlertChannels}.alertId`, alertId)) as TChannelResult[];
+ // Fetch last run status
+ type THistoryRecord = {
+ triggeredAt: Date;
+ hasNotificationSent: boolean | null;
+ notificationError: string | null;
+ };
+ const lastHistoryRecords = (await (tx || db.replicaNode())
+ .select(
+ `${TableName.PkiAlertHistory}.triggeredAt`,
+ `${TableName.PkiAlertHistory}.hasNotificationSent`,
+ `${TableName.PkiAlertHistory}.notificationError`
+ )
+ .from(TableName.PkiAlertHistory)
+ .where(`${TableName.PkiAlertHistory}.alertId`, alertId)
+ .orderBy(`${TableName.PkiAlertHistory}.triggeredAt`, "desc")
+ .limit(1)) as THistoryRecord[];
+
+ const lastHistory = lastHistoryRecords[0];
+ const lastRunData: TLastRunData | null = lastHistory
+ ? {
+ triggeredAt: lastHistory.triggeredAt,
+ hasNotificationSent: lastHistory.hasNotificationSent ?? false,
+ notificationError: lastHistory.notificationError ?? null
+ }
+ : null;
+
return {
...alert,
- channels: channels || []
+ channels: channels || [],
+ lastRunData
} as TAlertWithChannels;
} catch (error) {
throw new DatabaseError({ error, name: "FindByIdWithChannels" });
@@ -179,9 +214,48 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
{} as Record<string, TChannelResult[]>
);
+ // Fetch last run status for all alerts in a single query
+ type THistoryWithAlertId = {
+ alertId: string;
+ triggeredAt: Date;
+ hasNotificationSent: boolean | null;
+ notificationError: string | null;
+ };
+
+ const lastHistoryRecords =
+ alertIds.length > 0
+ ? ((await (tx || db.replicaNode())
+ .select(
+ `${TableName.PkiAlertHistory}.alertId`,
+ `${TableName.PkiAlertHistory}.triggeredAt`,
+ `${TableName.PkiAlertHistory}.hasNotificationSent`,
+ `${TableName.PkiAlertHistory}.notificationError`
+ )
+ .from(TableName.PkiAlertHistory)
+ .whereIn(`${TableName.PkiAlertHistory}.alertId`, alertIds)
+ .distinctOn(`${TableName.PkiAlertHistory}.alertId`)
+ .orderBy([
+ { column: `${TableName.PkiAlertHistory}.alertId` },
+ { column: `${TableName.PkiAlertHistory}.triggeredAt`, order: "desc" }
+ ])) as THistoryWithAlertId[])
+ : [];
+
+ const lastHistoryByAlertId = lastHistoryRecords.reduce(
+ (acc, record) => {
+ acc[record.alertId] = {
+ triggeredAt: record.triggeredAt,
+ hasNotificationSent: record.hasNotificationSent ?? false,
+ notificationError: record.notificationError ?? null
+ };
+ return acc;
+ },
+ {} as Record<string, TLastRunData>
+ );
+
const alertsWithChannels: TAlertWithChannels[] = (alerts as TPkiAlertsV2[]).map((alert) => ({
...alert,
- channels: channelsByAlertId[alert.id] || []
+ channels: channelsByAlertId[alert.id] || [],
+ lastRunData: lastHistoryByAlertId[alert.id] || null
}));
return { alerts: alertsWithChannels, total };
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-service.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-service.ts
index 2deb18c62f..02baa30ccf 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-v2-service.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-service.ts
@@ -1,22 +1,35 @@
import { ForbiddenError } from "@casl/ability";
-import { ActionProjectType } from "@app/db/schemas";
+import { ActionProjectType, ProjectMembershipRole } from "@app/db/schemas";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
-import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator/validate-url";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
+import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
+import { NotificationType } from "@app/services/notification/notification-types";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { TProjectMembershipDALFactory } from "@app/services/project-membership/project-membership-dal";
+import { TSmtpService } from "@app/services/smtp/smtp-service";
import { TPkiAlertChannelDALFactory } from "./pki-alert-channel-dal";
import { TPkiAlertHistoryDALFactory } from "./pki-alert-history-dal";
-import { TPkiAlertV2DALFactory } from "./pki-alert-v2-dal";
+import { sendEmailNotificationWithRetry } from "./pki-alert-v2-channel-email-fns";
+import { sendWebhookNotification } from "./pki-alert-v2-channel-webhook-fns";
+import { TAlertWithChannels, TPkiAlertV2DALFactory } from "./pki-alert-v2-dal";
import { parseTimeToDays, parseTimeToPostgresInterval } from "./pki-alert-v2-filter-utils";
import {
CertificateOrigin,
PkiAlertChannelType,
PkiAlertEventType,
+ PkiAlertRunStatus,
+ PkiWebhookEventType,
TAlertV2Response,
+ TCertificatePreview,
TChannelConfig,
+ TChannelConfigResponse,
TCreateAlertV2DTO,
TDeleteAlertV2DTO,
TEmailChannelConfig,
@@ -27,7 +40,9 @@ import {
TListMatchingCertificatesDTO,
TListMatchingCertificatesResponse,
TPkiFilterRule,
- TUpdateAlertV2DTO
+ TTestWebhookConfigDTO,
+ TUpdateAlertV2DTO,
+ TWebhookChannelConfig
} from "./pki-alert-v2-types";
type TPkiAlertV2ServiceFactoryDep = {
@@ -48,6 +63,10 @@ type TPkiAlertV2ServiceFactoryDep = {
pkiAlertHistoryDAL: Pick<TPkiAlertHistoryDALFactory, "createWithCertificates" | "findByAlertId">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
smtpService: Pick<TSmtpService, "sendMail">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
+ projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findAllProjectMembers">;
+ projectDAL: Pick<TProjectDALFactory, "findById">;
};
export type TPkiAlertV2ServiceFactory = ReturnType<typeof pkiAlertV2ServiceFactory>;
@@ -57,47 +76,81 @@ export const pkiAlertV2ServiceFactory = ({
pkiAlertChannelDAL,
pkiAlertHistoryDAL,
permissionService,
- smtpService
+ smtpService,
+ kmsService,
+ notificationService,
+ projectMembershipDAL,
+ projectDAL
}: TPkiAlertV2ServiceFactoryDep) => {
- type TAlertWithChannels = {
- id: string;
- name: string;
- description: string;
- eventType: string;
- alertBefore: string;
- filters: TPkiFilterRule[];
- enabled: boolean;
- projectId: string;
- createdAt: Date;
- updatedAt: Date;
- channels?: Array<{
- id: string;
- channelType: string;
- config: unknown;
- enabled: boolean;
- createdAt: Date;
- updatedAt: Date;
- }>;
+ // Helper to encrypt channel config before storing in DB
+ const encryptChannelConfig = (
+ config: TChannelConfig,
+ encryptor: (data: { plainText: Buffer }) => { cipherTextBlob: Buffer }
+ ): Buffer => {
+ return encryptor({ plainText: Buffer.from(JSON.stringify(config)) }).cipherTextBlob;
};
- const formatAlertResponse = (alert: TAlertWithChannels): TAlertV2Response => {
+ // Helper to decrypt channel config from DB
+ const decryptChannelConfig = <T extends TChannelConfig>(
+ channel: { config?: unknown; encryptedConfig?: Buffer | null },
+ decryptor: (data: { cipherTextBlob: Buffer }) => Buffer
+ ): T => {
+ if (channel.encryptedConfig) {
+ const decrypted = decryptor({ cipherTextBlob: channel.encryptedConfig });
+ return JSON.parse(decrypted.toString()) as T;
+ }
+ // Fallback for old unencrypted data
+ return channel.config as T;
+ };
+
+ const formatAlertResponse = (
+ alert: TAlertWithChannels,
+ decryptor: (data: { cipherTextBlob: Buffer }) => Buffer
+ ): TAlertV2Response => {
return {
id: alert.id,
name: alert.name,
- description: alert.description,
+ description: alert.description ?? null,
eventType: alert.eventType as PkiAlertEventType,
- alertBefore: alert.alertBefore,
- filters: alert.filters,
- enabled: alert.enabled,
+ alertBefore: alert.alertBefore ?? "",
+ filters: (alert.filters ?? []) as TPkiFilterRule[],
+ enabled: alert.enabled ?? true,
projectId: alert.projectId,
- channels: (alert.channels || []).map((channel) => ({
- id: channel.id,
- channelType: channel.channelType as PkiAlertChannelType,
- config: channel.config as TChannelConfig,
- enabled: channel.enabled,
- createdAt: channel.createdAt,
- updatedAt: channel.updatedAt
- })),
+ channels: (alert.channels || []).map((channel) => {
+ const config = decryptChannelConfig<TChannelConfig>(channel, decryptor);
+
+ // For webhook channels, replace signingSecret with hasSigningSecret
+ let responseConfig: TChannelConfigResponse;
+ if (channel.channelType === PkiAlertChannelType.WEBHOOK) {
+ const webhookConfig = config as TWebhookChannelConfig;
+ responseConfig = {
+ url: webhookConfig.url,
+ hasSigningSecret: Boolean(webhookConfig.signingSecret)
+ };
+ } else {
+ // For email and slack channels, the config is the same in request and response
+ responseConfig = config as TEmailChannelConfig;
+ }
+
+ return {
+ id: channel.id,
+ channelType: channel.channelType as PkiAlertChannelType,
+ config: responseConfig,
+ enabled: channel.enabled,
+ createdAt: channel.createdAt,
+ updatedAt: channel.updatedAt
+ };
+ }),
+ lastRun: alert.lastRunData
+ ? {
+ timestamp: alert.lastRunData.triggeredAt,
+ status:
+ !alert.lastRunData.notificationError && alert.lastRunData.hasNotificationSent
+ ? PkiAlertRunStatus.SUCCESS
+ : PkiAlertRunStatus.FAILED,
+ error: alert.lastRunData.notificationError
+ }
+ : null,
createdAt: alert.createdAt,
updatedAt: alert.updatedAt
};
@@ -134,6 +187,21 @@ export const pkiAlertV2ServiceFactory = ({
throw new BadRequestError({ message: "Invalid alertBefore format. Use format like '30d', '1w', '3m', '1y'" });
}
+ // Validate webhook URLs early to provide immediate SSRF feedback
+ for (const channel of channels) {
+ if (channel.channelType === PkiAlertChannelType.WEBHOOK) {
+ const webhookConfig = channel.config as TWebhookChannelConfig;
+ // eslint-disable-next-line no-await-in-loop
+ await blockLocalAndPrivateIpAddresses(webhookConfig.url);
+ }
+ }
+
+ // Create encryptor/decryptor for webhook configs
+ const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
return pkiAlertV2DAL.transaction(async (tx) => {
const alert = await pkiAlertV2DAL.create(
{
@@ -151,7 +219,8 @@ export const pkiAlertV2ServiceFactory = ({
const channelInserts = channels.map((channel) => ({
alertId: alert.id,
channelType: channel.channelType,
- config: channel.config,
+ config: null,
+ encryptedConfig: encryptChannelConfig(channel.config, encryptor),
enabled: channel.enabled
}));
@@ -162,7 +231,7 @@ export const pkiAlertV2ServiceFactory = ({
throw new NotFoundError({ message: "Failed to retrieve created alert" });
}
- return formatAlertResponse(completeAlert as TAlertWithChannels);
+ return formatAlertResponse(completeAlert, decryptor);
});
};
@@ -179,7 +248,7 @@ export const pkiAlertV2ServiceFactory = ({
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
- projectId: (alert as { projectId: string }).projectId,
+ projectId: alert.projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.CertificateManager
@@ -187,7 +256,12 @@ export const pkiAlertV2ServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PkiAlerts);
- return formatAlertResponse(alert as TAlertWithChannels);
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId: alert.projectId
+ });
+
+ return formatAlertResponse(alert, decryptor);
};
const listAlerts = async ({
@@ -217,8 +291,13 @@ export const pkiAlertV2ServiceFactory = ({
const { alerts, total } = await pkiAlertV2DAL.findByProjectIdWithCount(projectId, filters);
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
return {
- alerts: alerts.map((alert) => formatAlertResponse(alert as TAlertWithChannels)),
+ alerts: alerts.map((alert) => formatAlertResponse(alert, decryptor)),
total
};
};
@@ -243,7 +322,7 @@ export const pkiAlertV2ServiceFactory = ({
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
- projectId: (alert as { projectId: string }).projectId,
+ projectId: alert.projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.CertificateManager
@@ -274,18 +353,75 @@ export const pkiAlertV2ServiceFactory = ({
if (filters !== undefined) updateData.filters = filters;
if (enabled !== undefined) updateData.enabled = enabled;
+ // Validate webhook URLs early to provide immediate SSRF feedback
+ if (channels) {
+ for (const channel of channels) {
+ if (channel.channelType === PkiAlertChannelType.WEBHOOK) {
+ const webhookConfig = channel.config as TWebhookChannelConfig;
+ // eslint-disable-next-line no-await-in-loop
+ await blockLocalAndPrivateIpAddresses(webhookConfig.url);
+ }
+ }
+ }
+
+ // Create encryptor/decryptor for webhook configs
+ const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId: alert.projectId
+ });
+
return pkiAlertV2DAL.transaction(async (tx) => {
alert = await pkiAlertV2DAL.updateById(alertId, updateData, tx);
if (channels) {
+ // Get existing channels to preserve signing secrets if needed
+ const existingChannels = await pkiAlertChannelDAL.findByAlertId(alertId, tx);
+ const existingWebhookConfigs = new Map<string, TWebhookChannelConfig>();
+
+ // Build a map of existing webhook configs by channel id for preserving signing secrets
+ for (const existingChannel of existingChannels) {
+ if (existingChannel.channelType === PkiAlertChannelType.WEBHOOK) {
+ const config = decryptChannelConfig<TWebhookChannelConfig>(existingChannel, decryptor);
+ existingWebhookConfigs.set(existingChannel.id, config);
+ }
+ }
+
await pkiAlertChannelDAL.deleteByAlertId(alertId, tx);
- const channelInserts = channels.map((channel) => ({
- alertId,
- channelType: channel.channelType,
- config: channel.config,
- enabled: channel.enabled
- }));
+ const channelInserts = channels.map((channel) => {
+ let configToEncrypt = channel.config;
+
+ // Handle webhook signing secret preserve/clear logic
+ if (channel.channelType === PkiAlertChannelType.WEBHOOK) {
+ const webhookConfig = channel.config as TWebhookChannelConfig;
+ const existingConfig = channel.id ? existingWebhookConfigs.get(channel.id) : undefined;
+
+ // If signingSecret is undefined and we have an existing config, preserve the existing secret
+ // If signingSecret is null, explicitly clear it
+ // If signingSecret has a value, use the new value
+ let finalSigningSecret: string | undefined;
+ if (webhookConfig.signingSecret === undefined && existingConfig?.signingSecret) {
+ finalSigningSecret = existingConfig.signingSecret;
+ } else if (webhookConfig.signingSecret === null) {
+ finalSigningSecret = undefined;
+ } else {
+ finalSigningSecret = webhookConfig.signingSecret;
+ }
+
+ configToEncrypt = {
+ url: webhookConfig.url,
+ signingSecret: finalSigningSecret
+ };
+ }
+
+ return {
+ alertId,
+ channelType: channel.channelType,
+ config: null,
+ encryptedConfig: encryptChannelConfig(configToEncrypt, encryptor),
+ enabled: channel.enabled
+ };
+ });
await pkiAlertChannelDAL.insertMany(channelInserts, tx);
}
@@ -295,7 +431,7 @@ export const pkiAlertV2ServiceFactory = ({
throw new NotFoundError({ message: "Failed to retrieve updated alert" });
}
- return formatAlertResponse(completeAlert as TAlertWithChannels);
+ return formatAlertResponse(completeAlert, decryptor);
});
};
@@ -312,7 +448,7 @@ export const pkiAlertV2ServiceFactory = ({
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
- projectId: (alert as { projectId: string }).projectId,
+ projectId: alert.projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.CertificateManager
@@ -320,7 +456,12 @@ export const pkiAlertV2ServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Delete, ProjectPermissionSub.PkiAlerts);
- const formattedAlert = formatAlertResponse(alert as TAlertWithChannels);
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId: alert.projectId
+ });
+
+ const formattedAlert = formatAlertResponse(alert, decryptor);
await pkiAlertV2DAL.deleteById(alertId);
return formattedAlert;
@@ -341,7 +482,7 @@ export const pkiAlertV2ServiceFactory = ({
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
- projectId: (alert as { projectId: string }).projectId,
+ projectId: alert.projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.CertificateManager
@@ -359,13 +500,13 @@ export const pkiAlertV2ServiceFactory = ({
limit,
offset,
showPreview: true,
- excludeAlerted: (alert as { eventType: string }).eventType === PkiAlertEventType.EXPIRATION,
+ excludeAlerted: alert.eventType === PkiAlertEventType.EXPIRATION,
alertId
};
const result = await pkiAlertV2DAL.findMatchingCertificates(
- (alert as { projectId: string }).projectId,
- (alert as { filters: TPkiFilterRule[] }).filters,
+ alert.projectId,
+ alert.filters as TPkiFilterRule[],
options
);
@@ -425,21 +566,18 @@ export const pkiAlertV2ServiceFactory = ({
const sendAlertNotifications = async (alertId: string, certificateIds: string[]) => {
const alert = await pkiAlertV2DAL.findByIdWithChannels(alertId);
- if (!alert || !(alert as { enabled: boolean }).enabled) return;
+ if (!alert || !alert.enabled) return;
- const channels =
- (alert as { channels?: Array<{ enabled: boolean; channelType: string; config: unknown }> }).channels?.filter(
- (channel: { enabled: boolean; channelType: string; config: unknown }) => channel.enabled
- ) || [];
+ const { projectId } = alert;
+ const channels = alert.channels.filter((channel) => channel.enabled);
if (channels.length === 0) return;
- const { certificates } = await pkiAlertV2DAL.findMatchingCertificates(
- (alert as { projectId: string }).projectId,
- (alert as { filters: TPkiFilterRule[] }).filters,
- {
- alertBefore: parseTimeToPostgresInterval((alert as { alertBefore: string }).alertBefore)
- }
- );
+ const alertBefore = alert.alertBefore ?? "";
+ const filters = (alert.filters ?? []) as TPkiFilterRule[];
+
+ const { certificates } = await pkiAlertV2DAL.findMatchingCertificates(projectId, filters, {
+ alertBefore: parseTimeToPostgresInterval(alertBefore)
+ });
const matchingCertificates = certificates.filter(
(cert) => certificateIds.includes(cert.id) && cert.enrollmentType !== CertificateOrigin.CA
@@ -449,43 +587,132 @@ export const pkiAlertV2ServiceFactory = ({
let hasNotificationSent = false;
let notificationError: string | undefined;
+ const errors: string[] = [];
- try {
- const emailChannels = channels.filter(
- (channel: { enabled: boolean; channelType: string; config: unknown }) =>
- channel.channelType === PkiAlertChannelType.EMAIL
- );
+ const alertBeforeDays = parseTimeToDays(alertBefore);
+ const alertData = {
+ id: alert.id,
+ name: alert.name,
+ alertBefore,
+ projectId
+ };
- const alertBeforeDays = parseTimeToDays((alert as { alertBefore: string }).alertBefore);
- const alertName = (alert as { name: string }).name;
-
- const emailPromises = emailChannels.map((channel) => {
- const config = channel.config as TEmailChannelConfig;
-
- return smtpService.sendMail({
- recipients: config.recipients,
- subjectLine: `Infisical Certificate Alert - ${alertName}`,
- substitutions: {
- alertName,
- alertBeforeDays,
- projectId: (alert as { projectId: string }).projectId,
- items: matchingCertificates.map((cert) => ({
- type: "Certificate",
- friendlyName: cert.commonName,
- serialNumber: cert.serialNumber,
- expiryDate: cert.notAfter.toLocaleDateString()
- }))
- },
- template: SmtpTemplates.PkiExpirationAlert
- });
- });
+ // Get decryptor for channel configs
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
- await Promise.all(emailPromises);
+ // Process each channel
+ const channelPromises = channels.map(async (channel) => {
+ try {
+ switch (channel.channelType) {
+ case PkiAlertChannelType.EMAIL: {
+ const config = decryptChannelConfig<TEmailChannelConfig>(channel, decryptor);
+ const result = await sendEmailNotificationWithRetry(
+ smtpService,
+ config,
+ alert.name,
+ alertBeforeDays,
+ projectId,
+ matchingCertificates,
+ alertId
+ );
+ return { ...result, channelType: channel.channelType, recipients: config.recipients };
+ }
+ case PkiAlertChannelType.WEBHOOK: {
+ const config = decryptChannelConfig<TWebhookChannelConfig>(channel, decryptor);
+ const result = await sendWebhookNotification(
+ config,
+ alertData,
+ matchingCertificates,
+ PkiWebhookEventType.CERTIFICATE_EXPIRATION
+ );
+ return { ...result, channelType: channel.channelType, url: config.url };
+ }
+ case PkiAlertChannelType.SLACK: {
+ logger.info(`Slack channel not yet implemented for alert ${alertId}`);
+ return { success: false, channelType: channel.channelType, error: "Slack not yet implemented" };
+ }
+ default:
+ return { success: false, channelType: channel.channelType, error: "Unknown channel type" };
+ }
+ } catch (err) {
+ const errorMessage = err instanceof Error ? err.message : "Unknown error";
+ logger.error(err, `Failed to send ${channel.channelType} notification for alert ${alertId}`);
+
+ // Include context info in error result based on channel type
+ if (channel.channelType === PkiAlertChannelType.EMAIL) {
+ const config = decryptChannelConfig<TEmailChannelConfig>(channel, decryptor);
+ return {
+ success: false,
+ channelType: channel.channelType,
+ error: errorMessage,
+ recipients: config.recipients
+ };
+ }
+ if (channel.channelType === PkiAlertChannelType.WEBHOOK) {
+ const config = decryptChannelConfig<TWebhookChannelConfig>(channel, decryptor);
+ return { success: false, channelType: channel.channelType, error: errorMessage, url: config.url };
+ }
+
+ return { success: false, channelType: channel.channelType, error: errorMessage };
+ }
+ });
- hasNotificationSent = true;
- } catch (error) {
- notificationError = error instanceof Error ? error.message : "Unknown error occurred";
- logger.error(error, `Failed to send notifications for alert ${alertId}`);
+ const results = await Promise.all(channelPromises);
+
+ // After attempting all channels with retries, always mark as success
+ // This ensures the alert history records the attempt, even if some channels failed
+ // Error details are still captured and shown to admins via in-app notifications
+ hasNotificationSent = true;
+
+ // Collect errors from failed channels with context info
+ results.forEach((r) => {
+ if (!r.success && r.error) {
+ if (r.channelType === PkiAlertChannelType.EMAIL && "recipients" in r && r.recipients) {
+ errors.push(`EMAIL (recipients: ${r.recipients.join(", ")}): ${r.error}`);
+ } else if (r.channelType === PkiAlertChannelType.WEBHOOK && "url" in r && r.url) {
+ errors.push(`WEBHOOK (url: ${r.url}): ${r.error}`);
+ } else {
+ errors.push(`${r.channelType}: ${r.error}`);
+ }
+ }
+ });
+
+ if (errors.length > 0) {
+ notificationError = errors.join("\n");
+
+ // Send in-app notifications to project admins
+ try {
+ const projectMembers = await projectMembershipDAL.findAllProjectMembers(projectId);
+ const project = await projectDAL.findById(projectId);
+
+ if (project) {
+ const projectAdmins = projectMembers.filter((member) =>
+ member.roles.some((role) => role.role === ProjectMembershipRole.Admin)
+ );
+
+ if (projectAdmins.length > 0) {
+ const alertingPath = `/organizations/${project.orgId}/projects/cert-manager/${projectId}/alerting`;
+ const truncatedError =
+ notificationError.length > 200 ? `${notificationError.substring(0, 200)}...` : notificationError;
+
+ await notificationService.createUserNotifications(
+ projectAdmins.map((admin) => ({
+ userId: admin.userId,
+ orgId: project.orgId,
+ type: NotificationType.PKI_ALERT_CHANNEL_FAILED,
+ title: `PKI Alert Channel Failed: ${alert.name}`,
+ body: `Your PKI alert **${alert.name}** failed to deliver notifications: \`${truncatedError}\``,
+ link: alertingPath
+ }))
+ );
+ }
+ }
+ } catch (notifyErr) {
+ logger.error(notifyErr, `Failed to send in-app notification for PKI alert channel failure: ${alertId}`);
+ }
}
await pkiAlertHistoryDAL.createWithCertificates(alertId, certificateIds, {
@@ -494,6 +721,69 @@ export const pkiAlertV2ServiceFactory = ({
});
};
+ const testWebhookConfig = async ({
+ projectId,
+ url,
+ signingSecret,
+ actorId,
+ actorAuthMethod,
+ actor,
+ actorOrgId
+ }: TTestWebhookConfigDTO): Promise<{ success: boolean; error?: string }> => {
+ // Permission check - user must have edit access to PKI alerts in this project
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.PkiAlerts);
+
+ // Create test data (SSRF validation is done in sendWebhookNotification)
+ const alertData = {
+ id: "00000000-0000-0000-0000-000000000000",
+ name: "Test Alert",
+ alertBefore: "30d",
+ projectId
+ };
+
+ const testCertificates: TCertificatePreview[] = [
+ {
+ id: "00000000-0000-0000-0000-000000000000",
+ serialNumber: "TEST-SERIAL-NUMBER",
+ commonName: "test.example.com",
+ san: ["test.example.com", "www.test.example.com"],
+ profileName: "Test Profile",
+ enrollmentType: CertificateOrigin.PROFILE,
+ notBefore: new Date(),
+ notAfter: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
+ status: "active"
+ }
+ ];
+
+ try {
+ const config: TWebhookChannelConfig = { url, signingSecret };
+ const result = await sendWebhookNotification(
+ config,
+ alertData,
+ testCertificates,
+ PkiWebhookEventType.CERTIFICATE_TEST
+ );
+
+ if (!result.success) {
+ return { success: false, error: result.error };
+ }
+ return { success: true };
+ } catch (err) {
+ const errorMessage = err instanceof Error ? err.message : "Unknown error occurred";
+ logger.error(err, `Failed to test webhook config for project ${projectId}`);
+ return { success: false, error: errorMessage };
+ }
+ };
+
return {
createAlert,
getAlertById,
@@ -502,6 +792,7 @@ export const pkiAlertV2ServiceFactory = ({
deleteAlert,
listMatchingCertificates,
listCurrentMatchingCertificates,
- sendAlertNotifications
+ sendAlertNotifications,
+ testWebhookConfig
};
};
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-types.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-types.ts
index fe6055402b..34d18d28e2 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-v2-types.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-types.ts
@@ -57,6 +57,60 @@ export enum CertificateOrigin {
CA = "ca"
}
+export enum PkiAlertRunStatus {
+ SUCCESS = "success",
+ FAILED = "failed"
+}
+
+export enum PkiWebhookEventType {
+ CERTIFICATE_EXPIRATION = "com.infisical.pki.certificate.expiration",
+ CERTIFICATE_TEST = "com.infisical.pki.certificate.test"
+}
+
+// Alert info used across event types
+export type TAlertInfo = {
+ id: string;
+ name: string;
+ alertBefore: string;
+ projectId: string;
+};
+
+// Certificate data for webhook payloads
+export type TCertificateData = {
+ id: string;
+ serialNumber: string;
+ commonName: string;
+ san: string[];
+ profileName: string | null;
+ notBefore: string;
+ notAfter: string;
+ status: string;
+ daysUntilExpiry: number;
+};
+
+export type TPkiWebhookPayload = {
+ // Required CloudEvents attributes
+ specversion: "1.0";
+ type: PkiWebhookEventType;
+ source: string;
+ id: string;
+
+ // Optional CloudEvents attributes
+ time: string;
+ datacontenttype: "application/json";
+ subject: string;
+
+ // Event data
+ data: {
+ alert: TAlertInfo;
+ certificates: TCertificateData[];
+ metadata: {
+ totalCertificates: number;
+ viewUrl: string;
+ };
+ };
+};
+
export const PkiFilterRuleSchema = z.object({
field: z.nativeEnum(PkiFilterField),
operator: z.nativeEnum(PkiFilterOperator),
@@ -73,11 +127,19 @@ export const EmailChannelConfigSchema = z.object({
});
export const WebhookChannelConfigSchema = z.object({
- url: z.string().url(),
- method: z.enum(["POST", "PUT"]).default("POST"),
- headers: z.record(z.string()).optional()
+ url: z
+ .string()
+ .url()
+ .refine((url) => url.startsWith("https://"), "Webhook URL must use HTTPS"),
+ signingSecret: z.string().max(256).optional().nullable()
});
+// Response type for webhook config - signingSecret is replaced with hasSigningSecret
+export type TWebhookChannelConfigResponse = {
+ url: string;
+ hasSigningSecret: boolean;
+};
+
export const SlackChannelConfigSchema = z.object({
webhookUrl: z.string().url(),
channel: z.string().optional(),
@@ -96,6 +158,7 @@ export type TSlackChannelConfig = z.infer<typeof SlackChannelConfigSchema>;
export type TChannelConfig = z.infer<typeof ChannelConfigSchema>;
export const CreateChannelSchema = z.object({
+ id: z.string().uuid().optional(),
channelType: z.nativeEnum(PkiAlertChannelType),
config: ChannelConfigSchema,
enabled: z.boolean().default(true)
@@ -114,7 +177,11 @@ export const CreatePkiAlertV2Schema = z.object({
alertBefore: z.string().refine(createSecureAlertBeforeValidator(), "Must be in format like '30d', '1w', '3m', '1y'"),
filters: PkiFiltersSchema,
enabled: z.boolean().default(true),
- channels: z.array(CreateChannelSchema).min(1, "At least one channel is required")
+ channels: z
+ .array(CreateChannelSchema)
+ .min(1, "At least one notification channel is required")
+ .max(10)
+ .refine((channels) => channels.some((ch) => ch.enabled), "At least one notification channel must be enabled")
});
export type TCreatePkiAlertV2 = z.infer<typeof CreatePkiAlertV2Schema>;
@@ -173,6 +240,15 @@ export type TCertificatePreview = {
status: string;
};
+// Channel config type for responses (webhook has hasSigningSecret instead of signingSecret)
+export type TChannelConfigResponse = TEmailChannelConfig | TWebhookChannelConfigResponse | TSlackChannelConfig;
+
+export type TLastRun = {
+ timestamp: Date;
+ status: PkiAlertRunStatus;
+ error: string | null;
+};
+
export type TAlertV2Response = {
id: string;
name: string;
@@ -185,11 +261,12 @@ export type TAlertV2Response = {
channels: Array<{
id: string;
channelType: PkiAlertChannelType;
- config: TChannelConfig;
+ config: TChannelConfigResponse;
enabled: boolean;
createdAt: Date;
updatedAt: Date;
}>;
+ lastRun: TLastRun | null;
createdAt: Date;
updatedAt: Date;
};
@@ -203,3 +280,11 @@ export type TListMatchingCertificatesResponse = {
certificates: TCertificatePreview[];
total: number;
};
+
+export type TTestWebhookConfigDTO = TGenericPermission & {
+ projectId: string;
+ url: string;
+ signingSecret?: string;
+};
+
+export type TChannelResult = { success: boolean; error?: string };
diff --git a/docs/documentation/platform/pki/alerting.mdx b/docs/documentation/platform/pki/alerting.mdx
index c2342e0205..4f460a4838 100644
--- a/docs/documentation/platform/pki/alerting.mdx
+++ b/docs/documentation/platform/pki/alerting.mdx
@@ -15,11 +15,114 @@ To create an alert, head to your Certificate Management Project > Alerting and p
![pki alerting modal](/images/platform/pki/alerting/alert-create-modal.png)
+### Field Descriptions
+
Here's some guidance for each field in the alert configuration sequence:
-- Alert Type: The type of alert to create such as **Certificate Expiration**.
-- Alert Name: A slug-friendly name for the alert such as `tls-expiry-alert`.
-- Description: An optional description for the alert.
-- Alert Before: The time before certificate expiration to trigger the alert such as 30 days denoted by `30d`.
-- Filters: A list of filters that determine which certificates the alert applies to. Each row includes a **Field**, **Operator**, and **Value** to match against. For example, you can filter for certificates with a common name containing `example.com` by setting the field to **Common Name**, the operator to **Contains**, and the value to `example.com`.
-- Channels / Email Recipients: A list of email addresses to notify when the alert triggers.
+- **Alert Type**: The type of alert to create such as **Certificate Expiration**.
+- **Alert Name**: A slug-friendly name for the alert such as `tls-expiry-alert`.
+- **Description**: An optional description for the alert.
+- **Alert Before**: The time before certificate expiration to trigger the alert such as 30 days denoted by `30d`.
+- **Filters**: A list of filters that determine which certificates the alert applies to. Each row includes a **Field**, **Operator**, and **Value** to match against. For example, you can filter for certificates with a common name containing `example.com` by setting the field to **Common Name**, the operator to **Contains**, and the value to `example.com`.
+
+### Notification Channels
+
+Alerts can be delivered through one or more notification channels:
+
+- **Email**: Send alert notifications to a list of email recipients. Enter one or more email addresses to notify when the alert triggers.
+- **Webhook**: Send alert notifications to a webhook URL. The URL must use HTTPS. Optionally configure a signing secret to verify the authenticity of webhook payloads.
+
+You can configure up to 10 notification channels per alert.
+
+![pki alerting channels](/images/platform/pki/alerting/alert-create-channels.png)
+
+<Note>
+All configured channels must successfully deliver for an alert to be marked as complete. If any channel fails, the alert will retry until all channels succeed. Make sure all channels are working correctly to avoid repeated notifications.
+</Note>
+
+## Webhook Payload Format
+
+Webhook notifications are sent as HTTP POST requests with a [CloudEvents](https://cloudevents.io/)-compliant JSON payload.
+
+```json
+{
+ "specversion": "1.0",
+ "type": "com.infisical.pki.certificate.expiration",
+ "source": "/projects/<project-id>/alerts/<alert-id>",
+ "id": "<unique-event-id>",
+ "time": "2024-01-15T10:30:00.000Z",
+ "datacontenttype": "application/json",
+ "subject": "certificate-expiration-alert",
+ "data": {
+ "alert": {
+ "id": "<alert-id>",
+ "name": "tls-expiry-alert",
+ "alertBefore": "30d",
+ "projectId": "<project-id>"
+ },
+ "certificates": [
+ {
+ "id": "<certificate-id>",
+ "serialNumber": "1234567890",
+ "commonName": "example.com",
+ "san": ["example.com", "www.example.com"],
+ "profileName": "TLS Server",
+ "notBefore": "2024-01-01T00:00:00.000Z",
+ "notAfter": "2024-12-31T23:59:59.000Z",
+ "status": "active",
+ "daysUntilExpiry": 30
+ }
+ ],
+ "metadata": {
+ "totalCertificates": 1,
+ "viewUrl": "https://app.infisical.com/cert-manager/<project-id>/policies"
+ }
+ }
+}
+```
+
+## Webhook Signature Verification
+
+If you configure a signing secret for your webhook channel, Infisical will include an `x-infisical-signature` header with each request. This allows you to verify that the webhook payload originated from Infisical.
+
+The header format is:
+
+```
+x-infisical-signature: t=<timestamp>,v1=<signature>
+```
+
+Where:
+- `<timestamp>` is the Unix timestamp (in milliseconds) when the signature was generated
+- `v1` indicates the signature version
+- `<signature>` is the HMAC-SHA256 signature of the payload
+
+To verify the signature:
+
+1. Extract the timestamp and signature from the header
+2. Construct the signature payload by concatenating the timestamp, a period (`.`), and the raw request body: `{timestamp}.{body}`
+3. Compute an HMAC-SHA256 hash using your signing secret
+4. Compare the computed signature with the signature from the header
+
+Example verification in Node.js:
+
+```javascript
+const crypto = require('crypto');
+
+function verifyWebhookSignature(header, body, secret) {
+ // Parse header format: t=<timestamp>,v1=<signature>
+ const parts = header.split(',');
+ const timestamp = parts[0].replace('t=', '');
+ const signature = parts[1].replace('v1=', '');
+
+ const signaturePayload = `${timestamp}.${body}`;
+ const expectedSignature = crypto
+ .createHmac('sha256', secret)
+ .update(signaturePayload)
+ .digest('hex');
+
+ return crypto.timingSafeEqual(
+ Buffer.from(signature),
+ Buffer.from(expectedSignature)
+ );
+}
+```
diff --git a/docs/images/platform/pki/alerting/alert-create-channels.png b/docs/images/platform/pki/alerting/alert-create-channels.png
new file mode 100644
index 0000000000..7f34de0583
Binary files /dev/null and b/docs/images/platform/pki/alerting/alert-create-channels.png differ
diff --git a/docs/images/platform/pki/alerting/alert-create-modal.png b/docs/images/platform/pki/alerting/alert-create-modal.png
index f65530ce4e..8bd285b569 100644
Binary files a/docs/images/platform/pki/alerting/alert-create-modal.png and b/docs/images/platform/pki/alerting/alert-create-modal.png differ
diff --git a/docs/images/platform/pki/alerting/alert-create.png b/docs/images/platform/pki/alerting/alert-create.png
index 6204842233..e58d4ff5e9 100644
Binary files a/docs/images/platform/pki/alerting/alert-create.png and b/docs/images/platform/pki/alerting/alert-create.png differ
diff --git a/frontend/src/components/v3/generic/Accordion/Accordion.tsx b/frontend/src/components/v3/generic/Accordion/Accordion.tsx
index 15f9cb4028..30aa52adff 100644
--- a/frontend/src/components/v3/generic/Accordion/Accordion.tsx
+++ b/frontend/src/components/v3/generic/Accordion/Accordion.tsx
@@ -6,11 +6,17 @@ import { ChevronDownIcon } from "lucide-react";
import { cn } from "../../utils";
-function UnstableAccordion({ ...props }: React.ComponentProps<typeof AccordionPrimitive.Root>) {
+function UnstableAccordion({
+ className,
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
return (
<AccordionPrimitive.Root
data-slot="accordion"
- className="overflow-clip rounded-md border border-border bg-container text-foreground"
+ className={cn(
+ "overflow-clip rounded-md border border-border bg-container text-foreground",
+ className
+ )}
{...props}
/>
);
diff --git a/frontend/src/hooks/api/pkiAlertsV2/index.ts b/frontend/src/hooks/api/pkiAlertsV2/index.ts
index 4f822c74c1..6424018bda 100644
--- a/frontend/src/hooks/api/pkiAlertsV2/index.ts
+++ b/frontend/src/hooks/api/pkiAlertsV2/index.ts
@@ -1,4 +1,9 @@
-export { useCreatePkiAlertV2, useDeletePkiAlertV2, useUpdatePkiAlertV2 } from "./mutations";
+export {
+ useCreatePkiAlertV2,
+ useDeletePkiAlertV2,
+ useTestPkiWebhookConfigV2,
+ useUpdatePkiAlertV2
+} from "./mutations";
export {
pkiAlertsV2Keys,
useGetPkiAlertsV2,
@@ -15,6 +20,8 @@ export type {
TGetPkiAlertV2CurrentMatchingCertificatesResponse,
TGetPkiAlertV2MatchingCertificates,
TPkiAlertChannelConfigEmail,
+ TPkiAlertChannelConfigWebhook,
+ TPkiAlertChannelConfigWebhookResponse,
TPkiAlertChannelV2,
TPkiAlertV2,
TPkiFilterRuleV2,
@@ -26,5 +33,6 @@ export {
PkiAlertEventTypeV2,
PkiFilterFieldV2,
PkiFilterOperatorV2,
+ SIGNING_SECRET_MASK,
updatePkiAlertV2Schema
} from "./types";
diff --git a/frontend/src/hooks/api/pkiAlertsV2/mutations.ts b/frontend/src/hooks/api/pkiAlertsV2/mutations.ts
index e9159550ff..e840aa7106 100644
--- a/frontend/src/hooks/api/pkiAlertsV2/mutations.ts
+++ b/frontend/src/hooks/api/pkiAlertsV2/mutations.ts
@@ -66,3 +66,26 @@ export const useDeletePkiAlertV2 = () => {
}
});
};
+
+export interface TTestPkiWebhookConfigV2 {
+ projectId: string;
+ url: string;
+ signingSecret?: string;
+}
+
+export interface TTestPkiWebhookConfigV2Response {
+ success: boolean;
+ error?: string;
+}
+
+export const useTestPkiWebhookConfigV2 = () => {
+ return useMutation<TTestPkiWebhookConfigV2Response, unknown, TTestPkiWebhookConfigV2>({
+ mutationFn: async ({ projectId, url, signingSecret }) => {
+ const { data } = await apiRequest.post<TTestPkiWebhookConfigV2Response>(
+ "/api/v2/pki/alerts/test-webhook",
+ { projectId, url, signingSecret }
+ );
+ return data;
+ }
+ });
+};
diff --git a/frontend/src/hooks/api/pkiAlertsV2/types.ts b/frontend/src/hooks/api/pkiAlertsV2/types.ts
index 0f824ed103..536905ab87 100644
--- a/frontend/src/hooks/api/pkiAlertsV2/types.ts
+++ b/frontend/src/hooks/api/pkiAlertsV2/types.ts
@@ -1,5 +1,8 @@
import { z } from "zod";
+// Sentinel value for masked signing secret display in edit mode
+export const SIGNING_SECRET_MASK = "*****";
+
export enum PkiAlertEventTypeV2 {
EXPIRATION = "expiration",
RENEWAL = "renewal",
@@ -8,7 +11,8 @@ export enum PkiAlertEventTypeV2 {
}
export enum PkiAlertChannelTypeV2 {
- EMAIL = "email"
+ EMAIL = "email",
+ WEBHOOK = "webhook"
}
export enum PkiFilterFieldV2 {
@@ -36,8 +40,18 @@ export interface TPkiAlertChannelConfigEmail {
recipients: string[];
}
-// In the future other channels like webhooks will be supported here
-export type TPkiAlertChannelConfig = TPkiAlertChannelConfigEmail;
+export interface TPkiAlertChannelConfigWebhook {
+ url: string;
+ signingSecret?: string | null;
+}
+
+// Response type for webhook config - signingSecret is replaced with hasSigningSecret
+export interface TPkiAlertChannelConfigWebhookResponse {
+ url: string;
+ hasSigningSecret: boolean;
+}
+
+export type TPkiAlertChannelConfig = TPkiAlertChannelConfigEmail | TPkiAlertChannelConfigWebhook;
export interface TPkiAlertChannelV2 {
id: string;
@@ -48,6 +62,16 @@ export interface TPkiAlertChannelV2 {
updatedAt: string;
}
+export type TPkiAlertChannelInput = Omit<TPkiAlertChannelV2, "createdAt" | "updatedAt" | "id"> & {
+ id?: string;
+};
+
+export interface TLastRun {
+ timestamp: string;
+ status: "success" | "failed";
+ error: string | null;
+}
+
export interface TPkiAlertV2 {
id: string;
projectId: string;
@@ -58,6 +82,7 @@ export interface TPkiAlertV2 {
filters: TPkiFilterRuleV2[];
enabled: boolean;
channels: TPkiAlertChannelV2[];
+ lastRun: TLastRun | null;
createdAt: string;
updatedAt: string;
}
@@ -100,7 +125,7 @@ export interface TCreatePkiAlertV2 {
alertBefore?: string;
filters: TPkiFilterRuleV2[];
enabled?: boolean;
- channels: Omit<TPkiAlertChannelV2, "id" | "createdAt" | "updatedAt">[];
+ channels: TPkiAlertChannelInput[];
}
export interface TUpdatePkiAlertV2 {
@@ -111,7 +136,7 @@ export interface TUpdatePkiAlertV2 {
alertBefore?: string;
filters?: TPkiFilterRuleV2[];
enabled?: boolean;
- channels?: Omit<TPkiAlertChannelV2, "id" | "createdAt" | "updatedAt">[];
+ channels?: TPkiAlertChannelInput[];
}
export interface TDeletePkiAlertV2 {
@@ -155,21 +180,46 @@ export const pkiFilterRuleV2Schema = z.object({
const emailChannelConfigSchema = z.object({
recipients: z
.array(z.string())
- .transform((emails) => emails.filter(Boolean).map((email) => email.trim()))
+ .transform((emails) => emails.filter(Boolean).map((email) => email.trim().toLowerCase()))
.refine((emails) => emails.length > 0, "At least one email recipient is required")
.refine((emails) => emails.length <= 10, "Maximum 10 email recipients allowed")
.refine(
(emails) => emails.every((email) => z.string().email().safeParse(email).success),
"All recipients must be valid email addresses"
)
+ .refine(
+ (emails) => new Set(emails).size === emails.length,
+ "Duplicate email addresses are not allowed"
+ )
});
-export const pkiAlertChannelV2Schema = z.object({
- channelType: z.nativeEnum(PkiAlertChannelTypeV2),
+const webhookChannelConfigSchema = z.object({
+ url: z
+ .string()
+ .url("Must be a valid URL")
+ .refine((url) => url.startsWith("https://"), "Webhook URL must use HTTPS"),
+ signingSecret: z.string().max(256).nullable().optional()
+});
+
+const emailChannelSchema = z.object({
+ id: z.string().uuid().optional(),
+ channelType: z.literal(PkiAlertChannelTypeV2.EMAIL),
config: emailChannelConfigSchema,
enabled: z.boolean().default(true)
});
+const webhookChannelSchema = z.object({
+ id: z.string().uuid().optional(),
+ channelType: z.literal(PkiAlertChannelTypeV2.WEBHOOK),
+ config: webhookChannelConfigSchema,
+ enabled: z.boolean().default(true)
+});
+
+export const pkiAlertChannelV2Schema = z.discriminatedUnion("channelType", [
+ emailChannelSchema,
+ webhookChannelSchema
+]);
+
export const createPkiAlertV2Schema = z.object({
projectId: z.string().uuid(),
name: z
@@ -186,7 +236,13 @@ export const createPkiAlertV2Schema = z.object({
.optional(),
filters: z.array(pkiFilterRuleV2Schema),
enabled: z.boolean().default(true),
- channels: z.array(pkiAlertChannelV2Schema).min(1)
+ channels: z
+ .array(pkiAlertChannelV2Schema)
+ .min(1, "At least one notification channel is required")
+ .refine(
+ (channels) => channels.some((ch) => ch.enabled),
+ "At least one notification channel must be enabled"
+ )
});
export const updatePkiAlertV2Schema = createPkiAlertV2Schema.partial().omit({ projectId: true });
diff --git a/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsx b/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsx
index 6bd1562540..2ff6e758c1 100644
--- a/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsx
+++ b/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsx
@@ -95,6 +95,9 @@ export const PkiAlertsV2Page = ({ hideContainer = false }: Props) => {
<Td>
<Skeleton className="h-4 w-16" />
</Td>
+ <Td>
+ <Skeleton className="h-4 w-20" />
+ </Td>
<Td className="text-right">
<Skeleton className="ml-auto h-4 w-24" />
</Td>
@@ -122,7 +125,7 @@ export const PkiAlertsV2Page = ({ hideContainer = false }: Props) => {
return (
<Tr>
- <Td colSpan={5} className="py-8 text-center text-gray-400">
+ <Td colSpan={6} className="py-8 text-center text-gray-400">
{search ? "No alerts found matching your search." : "No PKI alerts configured yet."}
</Td>
</Tr>
@@ -131,9 +134,21 @@ export const PkiAlertsV2Page = ({ hideContainer = false }: Props) => {
return (
<div className={hideContainer ? "" : "container mx-auto p-6"}>
- <div className="mb-4 flex items-center justify-between">
- <div className="flex w-full items-center space-x-4">
- <div className="relative mr-2 w-full">
+ <div className="flex w-full flex-col gap-3 rounded-lg border border-mineshaft-600 bg-mineshaft-900 px-4 py-3">
+ <div className="flex items-center justify-between border-b border-mineshaft-400 pb-2">
+ <h3 className="text-lg font-medium text-mineshaft-100">Certificate Alerts</h3>
+ <Button
+ variant="solid"
+ colorSchema="primary"
+ leftIcon={<FontAwesomeIcon icon={faPlus} />}
+ onClick={() => setAlertModal({ isOpen: true })}
+ >
+ Create Certificate Alert
+ </Button>
+ </div>
+
+ <div className="mb-4 flex items-center">
+ <div className="relative w-full">
<FontAwesomeIcon
icon={faSearch}
className="absolute top-1/2 left-3 -translate-y-1/2 transform text-gray-400"
@@ -147,43 +162,35 @@ export const PkiAlertsV2Page = ({ hideContainer = false }: Props) => {
</div>
</div>
- <Button
- variant="solid"
- colorSchema="primary"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- onClick={() => setAlertModal({ isOpen: true })}
- >
- Create Certificate Alert
- </Button>
+ <TableContainer>
+ <Table>
+ <THead>
+ <Tr>
+ <Th>Name</Th>
+ <Th>Event Type</Th>
+ <Th>Status</Th>
+ <Th>Alert Before</Th>
+ <Th>Last Run</Th>
+ <Th className="text-right">Actions</Th>
+ </Tr>
+ </THead>
+ <TBody>{renderTableContent()}</TBody>
+ </Table>
+ </TableContainer>
+
+ {totalPages > 1 && (
+ <div className="mt-4 flex justify-center">
+ <Pagination
+ count={totalPages}
+ page={page}
+ onChangePage={setPage}
+ perPage={perPage}
+ onChangePerPage={setPerPage}
+ />
+ </div>
+ )}
</div>
- <TableContainer>
- <Table>
- <THead>
- <Tr>
- <Th>Name</Th>
- <Th>Event Type</Th>
- <Th>Status</Th>
- <Th>Alert Before</Th>
- <Th className="text-right">Actions</Th>
- </Tr>
- </THead>
- <TBody>{renderTableContent()}</TBody>
- </Table>
- </TableContainer>
-
- {totalPages > 1 && (
- <div className="mt-4 flex justify-center">
- <Pagination
- count={totalPages}
- page={page}
- onChangePage={setPage}
- perPage={perPage}
- onChangePerPage={setPerPage}
- />
- </div>
- )}
-
<CreatePkiAlertV2Modal
isOpen={alertModal.isOpen}
onOpenChange={(isOpen) => setAlertModal({ isOpen, alertId: undefined })}
diff --git a/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2FormSteps.tsx b/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2FormSteps.tsx
index 9dff01a315..041c70a252 100644
--- a/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2FormSteps.tsx
+++ b/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2FormSteps.tsx
@@ -1,13 +1,27 @@
/* eslint-disable react/no-array-index-key */
-import { useState } from "react";
-import { Controller, useFormContext } from "react-hook-form";
-import { faPlus, faTrash } from "@fortawesome/free-solid-svg-icons";
+import { useEffect, useRef, useState } from "react";
+import { Controller, useFieldArray, useFormContext } from "react-hook-form";
+import {
+ faCheck,
+ faChevronDown,
+ faEnvelope,
+ faKey,
+ faLink,
+ faPlus,
+ faTrash,
+ faTriangleExclamation,
+ faXmark
+} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Tab } from "@headlessui/react";
import { CertificateDisplayName } from "@app/components/utilities/certificateDisplayUtils";
import {
Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
FormControl,
FormLabel,
GenericFieldLabel,
@@ -17,6 +31,7 @@ import {
Select,
SelectItem,
Skeleton,
+ Switch,
Table,
TableContainer,
TBody,
@@ -24,29 +39,87 @@ import {
TextArea,
Th,
THead,
+ Tooltip,
Tr
} from "@app/components/v2";
-import { Badge } from "@app/components/v3";
+import {
+ Badge,
+ UnstableAccordion as Accordion,
+ UnstableAccordionContent as AccordionContent,
+ UnstableAccordionItem as AccordionItem,
+ UnstableAccordionTrigger as AccordionTrigger
+} from "@app/components/v3";
import { useProject } from "@app/context";
import {
+ PkiAlertChannelTypeV2,
PkiAlertEventTypeV2,
PkiFilterFieldV2,
PkiFilterOperatorV2,
TCreatePkiAlertV2,
- TPkiAlertChannelV2,
+ TPkiAlertChannelConfigEmail,
+ TPkiAlertChannelConfigWebhook,
TPkiFilterRuleV2,
- useGetPkiAlertV2CurrentMatchingCertificates
+ useGetPkiAlertV2CurrentMatchingCertificates,
+ useTestPkiWebhookConfigV2
} from "@app/hooks/api/pkiAlertsV2";
-export const CreatePkiAlertV2FormSteps = () => {
- const { control, watch, setValue } = useFormContext<TCreatePkiAlertV2>();
+import {
+ formatAlertBefore,
+ formatEventType,
+ getChannelIcon,
+ getChannelSummary
+} from "../utils/pki-alert-formatters";
+
+const MAX_CHANNELS = 10;
+
+interface CreatePkiAlertV2FormStepsProps {
+ expandedChannel: string | undefined;
+ setExpandedChannel: (channel: string | undefined) => void;
+}
+
+type ChannelUIState = {
+ emailInput?: string;
+ webhookTest?: {
+ success: boolean | null;
+ error?: string;
+ isLoading?: boolean;
+ };
+};
+
+export const CreatePkiAlertV2FormSteps = ({
+ expandedChannel,
+ setExpandedChannel
+}: CreatePkiAlertV2FormStepsProps) => {
+ const {
+ control,
+ watch,
+ setValue,
+ trigger,
+ formState: { errors }
+ } = useFormContext<TCreatePkiAlertV2>();
const { currentProject } = useProject();
const [certificatesPage, setCertificatesPage] = useState(1);
- const certificatesPerPage = 10;
+ const certificatesPerPage = 6;
+
+ const [channelUIStates, setChannelUIStates] = useState<Record<string, ChannelUIState>>({});
+
+ // Track when a channel is intentionally added (vs loaded from existing data)
+ const justAddedRef = useRef(false);
+
+ const { mutateAsync: testWebhookConfig } = useTestPkiWebhookConfigV2();
+
+ const {
+ fields: channelFields,
+ prepend: prependChannel,
+ remove: removeChannel
+ } = useFieldArray({
+ control,
+ name: "channels"
+ });
const watchedFilters = watch("filters");
- const watchedChannels = watch("channels");
+ const watchedChannels = watch("channels") || [];
const watchedEventType = watch("eventType");
const watchedAlertBefore = watch("alertBefore");
@@ -91,13 +164,118 @@ export const CreatePkiAlertV2FormSteps = () => {
setValue("filters", currentFilters);
};
- const updateChannel = (
- index: number,
- updatedChannel: Partial<Omit<TPkiAlertChannelV2, "id" | "createdAt" | "updatedAt">>
- ) => {
- const currentChannels = [...(watchedChannels || [])];
- currentChannels[index] = { ...currentChannels[index], ...updatedChannel };
- setValue("channels", currentChannels);
+ const isChannelLimitReached = watchedChannels.length >= MAX_CHANNELS;
+
+ const addChannel = (type: PkiAlertChannelTypeV2) => {
+ if (isChannelLimitReached) return;
+ justAddedRef.current = true;
+ prependChannel({
+ channelType: type,
+ config: type === PkiAlertChannelTypeV2.EMAIL ? { recipients: [] } : { url: "" },
+ enabled: true
+ });
+ trigger("channels");
+ };
+
+ // Auto-expand newly added channel (prepended at index 0)
+ useEffect(() => {
+ if (justAddedRef.current && channelFields[0]?.id) {
+ setExpandedChannel(channelFields[0].id);
+ justAddedRef.current = false;
+ }
+ }, [channelFields[0]?.id, setExpandedChannel]);
+
+ // Convert index-based expandedChannel (from modal validation) to field.id
+ useEffect(() => {
+ if (expandedChannel?.startsWith("channel-")) {
+ const match = expandedChannel.match(/^channel-(\d+)$/);
+ if (match) {
+ const index = parseInt(match[1], 10);
+ const fieldId = channelFields[index]?.id;
+ if (fieldId) {
+ setExpandedChannel(fieldId);
+ }
+ }
+ }
+ }, [expandedChannel, channelFields, setExpandedChannel]);
+
+ /**
+ * Sends a test request to the webhook URL to verify connectivity.
+ *
+ * Validates URL format client-side before making the API call.
+ * The backend sends a test payload and reports success/failure,
+ * which we display inline next to the test button.
+ */
+ const handleTestWebhook = async (fieldId: string, index: number) => {
+ if (!currentProject?.id) return;
+
+ // Trigger validation on the URL field - this will show Zod errors (invalid URL, non-HTTPS, etc.)
+ const isValid = await trigger(`channels.${index}.config.url`);
+ if (!isValid) return;
+
+ const channel = watchedChannels[index];
+ const webhookConfig = channel.config as TPkiAlertChannelConfigWebhook;
+
+ setChannelUIStates((prev) => ({
+ ...prev,
+ [fieldId]: { ...prev[fieldId], webhookTest: { success: null, isLoading: true } }
+ }));
+
+ try {
+ const result = await testWebhookConfig({
+ projectId: currentProject.id,
+ url: webhookConfig.url,
+ signingSecret: webhookConfig.signingSecret || undefined
+ });
+
+ if (result.success) {
+ setChannelUIStates((prev) => ({
+ ...prev,
+ [fieldId]: { ...prev[fieldId], webhookTest: { success: true, isLoading: false } }
+ }));
+ } else {
+ setChannelUIStates((prev) => ({
+ ...prev,
+ [fieldId]: {
+ ...prev[fieldId],
+ webhookTest: {
+ success: false,
+ error: result.error || "Failed to send test notification",
+ isLoading: false
+ }
+ }
+ }));
+ }
+ } catch {
+ setChannelUIStates((prev) => ({
+ ...prev,
+ [fieldId]: {
+ ...prev[fieldId],
+ webhookTest: {
+ success: false,
+ error: "Failed to send test notification",
+ isLoading: false
+ }
+ }
+ }));
+ }
+ };
+
+ const deleteChannel = (fieldId: string, index: number, e: React.MouseEvent) => {
+ e.stopPropagation();
+
+ removeChannel(index);
+
+ // Clean up unified channel state
+ setChannelUIStates((prev) => {
+ const newStates = { ...prev };
+ delete newStates[fieldId];
+ return newStates;
+ });
+
+ if (expandedChannel === fieldId) {
+ setExpandedChannel(undefined);
+ }
};
const getFieldOperators = (field: PkiFilterFieldV2) => {
@@ -115,44 +293,12 @@ export const CreatePkiAlertV2FormSteps = () => {
return operator === PkiFilterOperatorV2.MATCHES;
};
- const formatEventType = (eventType: PkiAlertEventTypeV2) => {
- switch (eventType) {
- case PkiAlertEventTypeV2.EXPIRATION:
- return "Certificate Expiration";
- case PkiAlertEventTypeV2.RENEWAL:
- return "Certificate Renewal";
- case PkiAlertEventTypeV2.ISSUANCE:
- return "Certificate Issuance";
- case PkiAlertEventTypeV2.REVOCATION:
- return "Certificate Revocation";
- default:
- return eventType;
- }
- };
-
- const formatAlertBefore = (alertBefore?: string) => {
- if (!alertBefore) return "-";
-
- const match = alertBefore.match(/^(\d+)([dwmy])$/);
- if (!match) return alertBefore;
-
- const [, value, unit] = match;
- const unitMap = {
- d: "days",
- w: "weeks",
- m: "months",
- y: "years"
- };
-
- return `${value} ${unitMap[unit as keyof typeof unitMap] || unit}`;
- };
-
return (
<>
<Tab.Panel>
<div className="space-y-6">
<p className="mb-4 text-sm text-bunker-300">
- Choose the event that will trigger this alert notification.
+ Choose the event type and configure basic details for your alert.
</p>
<div className="w-full">
@@ -174,14 +320,6 @@ export const CreatePkiAlertV2FormSteps = () => {
)}
/>
</div>
- </div>
- </Tab.Panel>
-
- <Tab.Panel>
- <div className="space-y-6">
- <p className="mb-4 text-sm text-bunker-300">
- Configure the name, description, and timing for your alert.
- </p>
<Controller
control={control}
@@ -482,38 +620,238 @@ export const CreatePkiAlertV2FormSteps = () => {
</Tab.Panel>
<Tab.Panel>
- <div className="space-y-6">
- <p className="mb-4 text-sm text-bunker-300">
- Set up email notifications to receive alerts when events occur.
- </p>
-
- <div className="space-y-4">
- <FormControl label="Email Recipients">
- <TextArea
- value={
- Array.isArray((watchedChannels?.[0]?.config as any)?.recipients)
- ? (watchedChannels[0].config as any).recipients.join(", ")
- : ""
- }
- onChange={(e) => {
- const emailList = e.target.value
- .split(",")
- .map((email) => email.trim())
- .filter((email) => email.length > 0);
- updateChannel(0, { config: { recipients: emailList }, enabled: true });
- }}
- className="w-full"
- rows={2}
- />
- </FormControl>
+ <div className="flex min-h-[400px] flex-col gap-6">
+ <div className="flex items-center justify-end gap-3">
+ {isChannelLimitReached && (
+ <span className="text-xs text-mineshaft-400">
+ Maximum of {MAX_CHANNELS} channels reached
+ </span>
+ )}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild disabled={isChannelLimitReached}>
+ <Button
+ type="button"
+ variant="outline_bg"
+ size="sm"
+ disabled={isChannelLimitReached}
+ rightIcon={<FontAwesomeIcon icon={faChevronDown} className="ml-1" />}
+ >
+ Add Channel
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" sideOffset={4}>
+ <DropdownMenuItem onClick={() => addChannel(PkiAlertChannelTypeV2.EMAIL)}>
+ <FontAwesomeIcon icon={faEnvelope} className="mr-2" />
+ Email
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => addChannel(PkiAlertChannelTypeV2.WEBHOOK)}>
+ <FontAwesomeIcon icon={faLink} className="mr-2" />
+ Webhook
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
</div>
+
+ {channelFields.length > 0 && (
+ <Accordion
+ type="single"
+ collapsible
+ value={expandedChannel}
+ onValueChange={setExpandedChannel}
+ className="border-mineshaft-500 bg-mineshaft-600"
+ >
+ {channelFields.map((field, index) => {
+ const channel = watchedChannels[index];
+ const channelError = errors.channels?.[index];
+ return (
+ <AccordionItem key={field.id} value={field.id} className="border-mineshaft-600">
+ <AccordionTrigger className="group overflow-hidden bg-mineshaft-800 hover:bg-mineshaft-600 data-[state=open]:bg-mineshaft-700 data-[state=open]:hover:bg-mineshaft-600">
+ <div className="flex w-0 flex-1 items-center justify-between gap-3">
+ <div className="flex min-w-0 flex-1 items-center gap-3">
+ <FontAwesomeIcon
+ icon={getChannelIcon(channel?.channelType)}
+ className="shrink-0 text-mineshaft-300"
+ />
+ <span className="shrink-0 text-sm font-medium capitalize">
+ {channel?.channelType}
+ </span>
+ <span className="truncate text-xs text-mineshaft-400 group-data-[state=open]:hidden">
+ {channel && getChannelSummary(channel)}
+ </span>
+ </div>
+ <div
+ role="presentation"
+ className="flex shrink-0 items-center gap-2"
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ >
+ <Controller
+ control={control}
+ name={`channels.${index}.enabled`}
+ render={({ field: enabledField }) => (
+ <Switch
+ id={`channel-enabled-${index}`}
+ isChecked={enabledField.value}
+ onCheckedChange={(checked) => {
+ enabledField.onChange(checked);
+ trigger("channels");
+ }}
+ />
+ )}
+ />
+ <IconButton
+ size="sm"
+ variant="plain"
+ colorSchema="danger"
+ ariaLabel="Delete channel"
+ onClick={(e) => deleteChannel(field.id, index, e)}
+ >
+ <FontAwesomeIcon icon={faTrash} />
+ </IconButton>
+ </div>
+ </div>
+ </AccordionTrigger>
+ <AccordionContent className="bg-mineshaft-800">
+ {channel?.channelType === PkiAlertChannelTypeV2.EMAIL && (
+ <Controller
+ control={control}
+ name={`channels.${index}.config.recipients`}
+ render={({ field: recipientsField, fieldState: { error } }) => (
+ <FormControl
+ label="Email Recipients"
+ helperText="Enter email addresses separated by commas"
+ isError={Boolean(error || channelError?.config)}
+ errorText={
+ error?.message ||
+ (channelError?.config as { message?: string })?.message
+ }
+ >
+ <TextArea
+ value={
+ channelUIStates[field.id]?.emailInput !== undefined
+ ? channelUIStates[field.id].emailInput
+ : recipientsField.value?.join(", ") || ""
+ }
+ onChange={(e) => {
+ // Store raw text while typing - don't parse yet
+ setChannelUIStates((prev) => ({
+ ...prev,
+ [field.id]: { ...prev[field.id], emailInput: e.target.value }
+ }));
+ }}
+ onBlur={() => {
+ // Parse to array only on blur
+ const rawValue = channelUIStates[field.id]?.emailInput;
+ if (rawValue !== undefined) {
+ const emails = rawValue
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean);
+ recipientsField.onChange(emails);
+ }
+ recipientsField.onBlur();
+ }}
+ rows={2}
+ />
+ </FormControl>
+ )}
+ />
+ )}
+
+ {channel?.channelType === PkiAlertChannelTypeV2.WEBHOOK && (
+ <div className="space-y-4">
+ <Controller
+ control={control}
+ name={`channels.${index}.config.url`}
+ render={({ field: urlField, fieldState: { error } }) => (
+ <FormControl
+ label="Webhook URL"
+ isRequired
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <Input
+ value={urlField.value || ""}
+ onChange={urlField.onChange}
+ onBlur={urlField.onBlur}
+ placeholder="https://api.example.com/webhook"
+ />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name={`channels.${index}.config.signingSecret`}
+ render={({ field: secretField }) => (
+ <FormControl
+ label="Signing Secret"
+ tooltipText="Adding a signing secret enables webhook signature verification, helping ensure requests are genuinely from Infisical. The signature is sent via the x-infisical-signature header."
+ >
+ <Input
+ type="password"
+ value={secretField.value || ""}
+ onChange={secretField.onChange}
+ onBlur={secretField.onBlur}
+ placeholder="Enter signing secret..."
+ />
+ </FormControl>
+ )}
+ />
+ <div className="flex items-center gap-2">
+ <Button
+ type="button"
+ variant="outline_bg"
+ size="sm"
+ onClick={() => handleTestWebhook(field.id, index)}
+ isLoading={channelUIStates[field.id]?.webhookTest?.isLoading}
+ isDisabled={channelUIStates[field.id]?.webhookTest?.isLoading}
+ >
+ Test
+ </Button>
+ {channelUIStates[field.id]?.webhookTest?.success === true && (
+ <span className="flex items-center gap-1 text-sm text-green-500">
+ <FontAwesomeIcon icon={faCheck} />
+ Success
+ </span>
+ )}
+ {channelUIStates[field.id]?.webhookTest?.success === false && (
+ <span className="flex items-center gap-1 text-sm text-red-500">
+ <FontAwesomeIcon icon={faXmark} />
+ {channelUIStates[field.id]?.webhookTest?.error || "Failed"}
+ </span>
+ )}
+ </div>
+ </div>
+ )}
+ </AccordionContent>
+ </AccordionItem>
+ );
+ })}
+ </Accordion>
+ )}
+
+ {channelFields.length > 0 && errors.channels?.message && (
+ <span className="text-sm text-red-500">{errors.channels.message}</span>
+ )}
+
+ {channelFields.length === 0 && (
+ <div className="flex flex-1 flex-col items-center justify-center gap-2">
+ <span className="text-bunker-400">
+ At least one notification channel is required. Click &quot;Add Channel&quot; to add
+ one.
+ </span>
+ {errors.channels?.message && (
+ <span className="text-sm text-red-500">{errors.channels.message}</span>
+ )}
+ </div>
+ )}
</div>
</Tab.Panel>
<Tab.Panel>
<div className="mb-4 flex flex-col gap-6">
- <p className="mb-4 text-sm text-bunker-300">
+ <p className="text-sm text-bunker-300">
Please review the settings below before creating your alert.
</p>
@@ -575,15 +913,89 @@ export const CreatePkiAlertV2FormSteps = () => {
<div className="flex flex-col gap-3">
<div className="w-full border-b border-mineshaft-600">
- <span className="text-sm text-mineshaft-300">Notifications</span>
- </div>
- <div className="flex flex-wrap gap-x-8 gap-y-3">
- <GenericFieldLabel label="Email Recipients">
- {Array.isArray((watchedChannels?.[0]?.config as any)?.recipients)
- ? (watchedChannels[0].config as any).recipients.join(", ")
- : (watchedChannels?.[0]?.config as any)?.recipients || "No recipients"}
- </GenericFieldLabel>
+ <span className="text-sm text-mineshaft-300">Notification Channels</span>
</div>
+ {watchedChannels.length > 0 ? (
+ <div className="space-y-2">
+ {watchedChannels.map((channel, index) => (
+ <div
+ key={`review-channel-${index}`}
+ className="flex items-center gap-3 rounded-md border border-mineshaft-600 px-3 py-2"
+ >
+ <FontAwesomeIcon
+ icon={getChannelIcon(channel.channelType)}
+ className="text-mineshaft-400"
+ />
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium text-mineshaft-100 capitalize">
+ {channel.channelType}
+ </span>
+ {channel.channelType === PkiAlertChannelTypeV2.WEBHOOK &&
+ ((channel.config as TPkiAlertChannelConfigWebhook).signingSecret ? (
+ <Tooltip content="Signed webhook - requests will include signature verification">
+ <FontAwesomeIcon
+ icon={faKey}
+ className="text-xs text-mineshaft-400"
+ />
+ </Tooltip>
+ ) : (
+ <Tooltip content="Unsigned webhook - consider adding a signing secret for security">
+ <FontAwesomeIcon
+ icon={faTriangleExclamation}
+ className="text-xs text-mineshaft-400"
+ />
+ </Tooltip>
+ ))}
+ </div>
+ <span className="truncate text-xs text-mineshaft-400">
+ {channel.channelType === PkiAlertChannelTypeV2.EMAIL
+ ? (() => {
+ const config = channel.config as TPkiAlertChannelConfigEmail;
+ const count = config.recipients.length;
+ if (count === 0) return "No recipients";
+ const displayEmails = config.recipients.slice(0, 3);
+ const truncated = displayEmails.map((e) =>
+ e.length > 20 ? `${e.slice(0, 20)}...` : e
+ );
+ const displayText =
+ count <= 3
+ ? truncated.join(", ")
+ : `${truncated.join(", ")} +${count - 3} more`;
+
+ if (count > 3) {
+ return (
+ <Tooltip content={config.recipients.join(", ")}>
+ <span className="cursor-help">{displayText}</span>
+ </Tooltip>
+ );
+ }
+ return displayText;
+ })()
+ : (() => {
+ const config = channel.config as TPkiAlertChannelConfigWebhook;
+ try {
+ const url = new URL(config.url);
+ return url.hostname;
+ } catch {
+ return config.url || "Not configured";
+ }
+ })()}
+ </span>
+ </div>
+ {!channel.enabled && (
+ <Badge variant="neutral" className="text-xs">
+ Disabled
+ </Badge>
+ )}
+ </div>
+ ))}
+ </div>
+ ) : (
+ <span className="text-sm text-red-400">
+ No channels configured - at least one is required
+ </span>
+ )}
</div>
</div>
</Tab.Panel>
diff --git a/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2Modal.tsx b/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2Modal.tsx
index d91fab6730..959ed27d93 100644
--- a/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2Modal.tsx
+++ b/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2Modal.tsx
@@ -1,5 +1,5 @@
import React, { useState } from "react";
-import { FormProvider, useForm } from "react-hook-form";
+import { FieldError, FormProvider, useForm } from "react-hook-form";
import { Tab } from "@headlessui/react";
import { zodResolver } from "@hookform/resolvers/zod";
import { twMerge } from "tailwind-merge";
@@ -11,8 +11,11 @@ import {
createPkiAlertV2Schema,
PkiAlertChannelTypeV2,
PkiAlertEventTypeV2,
+ SIGNING_SECRET_MASK,
TCreatePkiAlertV2,
TPkiAlertChannelConfigEmail,
+ TPkiAlertChannelConfigWebhook,
+ TPkiAlertChannelConfigWebhookResponse,
TPkiAlertV2,
TUpdatePkiAlertV2,
updatePkiAlertV2Schema,
@@ -33,11 +36,10 @@ interface Props {
type TFormData = TCreatePkiAlertV2;
const FORM_TABS: { name: string; key: string; fields: (keyof TFormData)[] }[] = [
- { name: "Alert Type", key: "alertType", fields: ["eventType"] },
{
name: "Details",
key: "basicInfo",
- fields: ["name", "description", "alertBefore"]
+ fields: ["eventType", "name", "description", "alertBefore"]
},
{ name: "Filters", key: "filterRules", fields: ["filters"] },
{ name: "Preview", key: "preview", fields: [] },
@@ -45,9 +47,12 @@ const FORM_TABS: { name: string; key: string; fields: (keyof TFormData)[] }[] =
{ name: "Review", key: "review", fields: [] }
];
+const CHANNELS_TAB_INDEX = 3;
+
export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alertId }: Props) => {
const { currentProject } = useProject();
const [selectedTabIndex, setSelectedTabIndex] = useState(0);
+ const [expandedChannel, setExpandedChannel] = useState<string | undefined>(undefined);
const { data: fetchedAlert } = useGetPkiAlertV2ById(
{ alertId: alertId || "" },
@@ -67,18 +72,17 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
alertBefore: "30d",
filters: [],
enabled: true,
- channels: [
- {
- channelType: PkiAlertChannelTypeV2.EMAIL,
- config: { recipients: [] },
- enabled: true
- }
- ]
+ channels: []
},
reValidateMode: "onBlur"
});
- const { handleSubmit, trigger, reset } = formMethods;
+ const {
+ handleSubmit,
+ trigger,
+ reset,
+ formState: { errors }
+ } = formMethods;
const { mutateAsync: createAlert } = useCreatePkiAlertV2();
const { mutateAsync: updateAlert } = useUpdatePkiAlertV2();
@@ -86,6 +90,7 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
const handleModalClose = () => {
reset();
setSelectedTabIndex(0);
+ setExpandedChannel(undefined);
onOpenChange(false);
};
@@ -99,24 +104,30 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
alertBefore: editingAlert.alertBefore || "30d",
filters: editingAlert.filters || [],
enabled: editingAlert.enabled,
- channels: editingAlert.channels?.map(({ id, createdAt, updatedAt, ...channel }) => {
- if (channel.channelType === PkiAlertChannelTypeV2.EMAIL) {
- const emailConfig = channel.config as TPkiAlertChannelConfigEmail;
- return {
- ...channel,
- config: {
- recipients: Array.isArray(emailConfig.recipients) ? emailConfig.recipients : []
- }
- };
- }
- return channel;
- }) || [
- {
- channelType: PkiAlertChannelTypeV2.EMAIL,
- config: { recipients: [] },
- enabled: true
- }
- ]
+ channels:
+ editingAlert.channels?.map(({ createdAt, updatedAt, ...channel }) => {
+ if (channel.channelType === PkiAlertChannelTypeV2.EMAIL) {
+ const emailConfig = channel.config as TPkiAlertChannelConfigEmail;
+ return {
+ ...channel,
+ config: {
+ recipients: Array.isArray(emailConfig.recipients) ? emailConfig.recipients : []
+ }
+ };
+ }
+ if (channel.channelType === PkiAlertChannelTypeV2.WEBHOOK) {
+ const webhookConfig = channel.config as TPkiAlertChannelConfigWebhookResponse;
+ return {
+ ...channel,
+ config: {
+ url: webhookConfig.url,
+ // Show mask if secret exists, otherwise undefined
+ signingSecret: webhookConfig.hasSigningSecret ? SIGNING_SECRET_MASK : undefined
+ }
+ };
+ }
+ return channel;
+ }) || []
});
} else if (!isEditing) {
reset({
@@ -127,13 +138,7 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
alertBefore: "30d",
filters: [],
enabled: true,
- channels: [
- {
- channelType: PkiAlertChannelTypeV2.EMAIL,
- config: { recipients: [] },
- enabled: true
- }
- ]
+ channels: []
});
}
}, [editingAlert, isEditing, currentProject?.id, reset]);
@@ -153,6 +158,30 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
}
};
}
+ if (channel.channelType === PkiAlertChannelTypeV2.WEBHOOK) {
+ const webhookConfig = channel.config as TPkiAlertChannelConfigWebhook;
+
+ // Determine what to send for signingSecret
+ let signingSecret: string | null | undefined;
+ if (webhookConfig.signingSecret === SIGNING_SECRET_MASK) {
+ // User didn't change it - send undefined to preserve existing
+ signingSecret = undefined;
+ } else if (!webhookConfig.signingSecret) {
+ // User cleared it - send null to remove from DB
+ signingSecret = null;
+ } else {
+ // User entered a new value (or appended to mask)
+ signingSecret = webhookConfig.signingSecret;
+ }
+
+ return {
+ ...channel,
+ config: {
+ url: webhookConfig.url,
+ signingSecret
+ }
+ };
+ }
return channel;
})
};
@@ -196,6 +225,13 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
const isFinalStep = selectedTabIndex === FORM_TABS.length - 1;
+ // Helper to find first channel with error and expand it
+ const getFirstChannelErrorIndex = (): number => {
+ if (!errors.channels) return -1;
+ const channelsErrors = errors.channels as Array<FieldError | undefined>;
+ return channelsErrors.findIndex((err) => err !== undefined);
+ };
+
const handleNext = async () => {
if (isFinalStep) {
await handleSubmit(onSubmit)();
@@ -203,7 +239,16 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
}
const isValid = await isStepValid(selectedTabIndex);
- if (!isValid) return;
+ if (!isValid) {
+ // If on channels tab and validation failed, expand first channel with error
+ if (selectedTabIndex === CHANNELS_TAB_INDEX) {
+ const firstErrorIdx = getFirstChannelErrorIndex();
+ if (firstErrorIdx >= 0) {
+ setExpandedChannel(`channel-${firstErrorIdx}`);
+ }
+ }
+ return;
+ }
setSelectedTabIndex((prev) => prev + 1);
};
@@ -222,36 +267,47 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
<ModalContent
title={`${isEditing ? "Update" : "Create"} Certificate Alert`}
className="max-w-2xl"
+ closeOnOutsideClick={false}
>
- <form className={twMerge(isFinalStep && "max-h-[70vh] overflow-y-auto")}>
- <FormProvider {...formMethods}>
- <Tab.Group selectedIndex={selectedTabIndex} onChange={setSelectedTabIndex}>
- <Tab.List className="-pb-1 mb-6 w-full border-b-2 border-mineshaft-600">
- {FORM_TABS.map((tab, index) => (
- <Tab
- onClick={async (e) => {
- e.preventDefault();
- const isEnabled = await isTabEnabled(index);
- setSelectedTabIndex((prev) => (isEnabled ? index : prev));
- }}
- className={({ selected }) =>
- `-mb-[0.14rem] whitespace-nowrap ${index > selectedTabIndex ? "opacity-30" : ""} px-4 py-2 text-sm font-medium outline-hidden disabled:opacity-60 ${
- selected
- ? "border-b-2 border-mineshaft-300 text-mineshaft-200"
- : "text-bunker-300"
- }`
- }
- key={tab.key}
- >
- {index + 1}. {tab.name}
- </Tab>
- ))}
- </Tab.List>
- <Tab.Panels>
- <CreatePkiAlertV2FormSteps />
- </Tab.Panels>
- </Tab.Group>
- </FormProvider>
+ <form
+ className={twMerge(
+ "flex min-h-[60vh] flex-col",
+ isFinalStep && "max-h-[70vh] overflow-y-auto"
+ )}
+ >
+ <div className="flex-1 overflow-y-auto">
+ <FormProvider {...formMethods}>
+ <Tab.Group selectedIndex={selectedTabIndex} onChange={setSelectedTabIndex}>
+ <Tab.List className="-pb-1 mb-6 flex w-full justify-center border-b-2 border-mineshaft-600">
+ {FORM_TABS.map((tab, index) => (
+ <Tab
+ onClick={async (e) => {
+ e.preventDefault();
+ const isEnabled = await isTabEnabled(index);
+ setSelectedTabIndex((prev) => (isEnabled ? index : prev));
+ }}
+ className={({ selected }) =>
+ `-mb-[0.14rem] w-28 whitespace-nowrap ${index > selectedTabIndex ? "opacity-30" : ""} px-2 py-2 text-sm font-medium outline-hidden disabled:opacity-60 ${
+ selected
+ ? "border-b-2 border-mineshaft-300 text-mineshaft-200"
+ : "text-bunker-300"
+ }`
+ }
+ key={tab.key}
+ >
+ {index + 1}. {tab.name}
+ </Tab>
+ ))}
+ </Tab.List>
+ <Tab.Panels>
+ <CreatePkiAlertV2FormSteps
+ expandedChannel={expandedChannel}
+ setExpandedChannel={setExpandedChannel}
+ />
+ </Tab.Panels>
+ </Tab.Group>
+ </FormProvider>
+ </div>
<div className="flex w-full flex-row-reverse justify-between gap-4 pt-4">
<Button onClick={handleNext} colorSchema="secondary">
diff --git a/frontend/src/views/PkiAlertsV2Page/components/PkiAlertV2Row.tsx b/frontend/src/views/PkiAlertsV2Page/components/PkiAlertV2Row.tsx
index af4a706303..36ec071da0 100644
--- a/frontend/src/views/PkiAlertsV2Page/components/PkiAlertV2Row.tsx
+++ b/frontend/src/views/PkiAlertsV2Page/components/PkiAlertV2Row.tsx
@@ -21,7 +21,9 @@ import {
Tr
} from "@app/components/v2";
import { Badge } from "@app/components/v3";
-import { PkiAlertEventTypeV2, TPkiAlertV2, useUpdatePkiAlertV2 } from "@app/hooks/api/pkiAlertsV2";
+import { TPkiAlertV2, useUpdatePkiAlertV2 } from "@app/hooks/api/pkiAlertsV2";
+
+import { formatAlertBefore, formatEventType } from "../utils/pki-alert-formatters";
interface Props {
alert: TPkiAlertV2;
@@ -33,21 +35,6 @@ interface Props {
export const PkiAlertV2Row = ({ alert, onView, onEdit, onDelete }: Props) => {
const { mutateAsync: updateAlert } = useUpdatePkiAlertV2();
- const formatEventType = (eventType: PkiAlertEventTypeV2) => {
- switch (eventType) {
- case PkiAlertEventTypeV2.EXPIRATION:
- return "Certificate Expiration";
- case PkiAlertEventTypeV2.RENEWAL:
- return "Certificate Renewal";
- case PkiAlertEventTypeV2.ISSUANCE:
- return "Certificate Issuance";
- case PkiAlertEventTypeV2.REVOCATION:
- return "Certificate Revocation";
- default:
- return eventType;
- }
- };
-
const handleToggleAlert = async () => {
try {
await updateAlert({
@@ -66,23 +53,6 @@ export const PkiAlertV2Row = ({ alert, onView, onEdit, onDelete }: Props) => {
}
};
- const formatAlertBefore = (alertBefore?: string) => {
- if (!alertBefore) return "-";
-
- const match = alertBefore.match(/^(\\d+)([dwmy])$/);
- if (!match) return alertBefore;
-
- const [, value, unit] = match;
- const unitMap = {
- d: "days",
- w: "weeks",
- m: "months",
- y: "years"
- };
-
- return `${value} ${unitMap[unit as keyof typeof unitMap] || unit}`;
- };
-
return (
<Tr>
<Td>
@@ -104,6 +74,33 @@ export const PkiAlertV2Row = ({ alert, onView, onEdit, onDelete }: Props) => {
</Badge>
</Td>
<Td className="text-gray-300">{formatAlertBefore(alert.alertBefore)}</Td>
+ <Td>
+ {alert.lastRun ? (
+ <Tooltip
+ content={
+ <div className="max-w-sm">
+ <div className="text-xs text-mineshaft-300">
+ {new Date(alert.lastRun.timestamp)
+ .toISOString()
+ .replace("T", " ")
+ .replace("Z", " UTC")}
+ </div>
+ {alert.lastRun.error && (
+ <div className="mt-1 max-h-32 thin-scrollbar overflow-y-auto text-xs break-words text-red-400">
+ {alert.lastRun.error}
+ </div>
+ )}
+ </div>
+ }
+ >
+ <Badge variant={alert.lastRun.status === "success" ? "success" : "danger"}>
+ {alert.lastRun.status === "success" ? "Success" : "Failed"}
+ </Badge>
+ </Tooltip>
+ ) : (
+ <span className="text-mineshaft-500">—</span>
+ )}
+ </Td>
<Td className="text-right">
<DropdownMenu>
<DropdownMenuTrigger asChild>
diff --git a/frontend/src/views/PkiAlertsV2Page/components/UpdatePkiAlertV2Modal.tsx b/frontend/src/views/PkiAlertsV2Page/components/UpdatePkiAlertV2Modal.tsx
deleted file mode 100644
index 70735b8fc4..0000000000
--- a/frontend/src/views/PkiAlertsV2Page/components/UpdatePkiAlertV2Modal.tsx
+++ /dev/null
@@ -1,478 +0,0 @@
-import { useEffect, useState } from "react";
-import { Controller, useForm } from "react-hook-form";
-import { faPlus, faTrash } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { zodResolver } from "@hookform/resolvers/zod";
-
-import { createNotification } from "@app/components/notifications";
-import {
- Button,
- FormControl,
- FormLabel,
- IconButton,
- Input,
- Modal,
- ModalContent,
- Select,
- SelectItem,
- Skeleton,
- Switch,
- TextArea
-} from "@app/components/v2";
-import {
- PkiAlertChannelTypeV2,
- PkiAlertEventTypeV2,
- PkiFilterFieldV2,
- PkiFilterOperatorV2,
- TPkiAlertChannelV2,
- TPkiFilterRuleV2,
- TUpdatePkiAlertV2,
- updatePkiAlertV2Schema,
- useGetPkiAlertV2ById,
- useUpdatePkiAlertV2
-} from "@app/hooks/api/pkiAlertsV2";
-
-interface Props {
- isOpen: boolean;
- onOpenChange: (isOpen: boolean) => void;
- alertId?: string;
-}
-
-type TFormData = Omit<TUpdatePkiAlertV2, "alertId">;
-
-export const UpdatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertId }: Props) => {
- const [isSubmitting, setIsSubmitting] = useState(false);
-
- const { control, handleSubmit, reset, watch, setValue } = useForm<TFormData>({
- resolver: zodResolver(updatePkiAlertV2Schema)
- });
-
- const { data: alert, isLoading } = useGetPkiAlertV2ById(
- { alertId: alertId || "" },
- { enabled: !!alertId && isOpen }
- );
-
- const { mutateAsync: updateAlert } = useUpdatePkiAlertV2();
-
- const watchedFilters = watch("filters");
- const watchedChannels = watch("channels");
-
- useEffect(() => {
- if (alert) {
- reset({
- name: alert.name,
- description: alert.description || "",
- eventType: alert.eventType,
- alertBefore: alert.alertBefore || "",
- filters: alert.filters,
- enabled: alert.enabled,
- channels: alert.channels.map(({ id, createdAt, updatedAt, ...channel }) => channel)
- });
- }
- }, [alert, reset]);
-
- const addFilter = () => {
- const currentFilters = watchedFilters || [];
- setValue("filters", [
- ...currentFilters,
- {
- field: PkiFilterFieldV2.COMMON_NAME,
- operator: PkiFilterOperatorV2.CONTAINS,
- value: ""
- }
- ]);
- };
-
- const removeFilter = (index: number) => {
- const currentFilters = watchedFilters || [];
- setValue(
- "filters",
- currentFilters.filter((_, i) => i !== index)
- );
- };
-
- const updateFilter = (index: number, updatedFilter: Partial<TPkiFilterRuleV2>) => {
- const currentFilters = [...(watchedFilters || [])];
- currentFilters[index] = { ...currentFilters[index], ...updatedFilter };
- setValue("filters", currentFilters);
- };
-
- const addChannel = () => {
- const currentChannels = watchedChannels || [];
- setValue("channels", [
- ...currentChannels,
- {
- channelType: PkiAlertChannelTypeV2.EMAIL,
- config: { recipients: [] },
- enabled: true
- }
- ]);
- };
-
- const removeChannel = (index: number) => {
- const currentChannels = watchedChannels || [];
- if (currentChannels.length > 1) {
- setValue(
- "channels",
- currentChannels.filter((_, i) => i !== index)
- );
- }
- };
-
- const updateChannel = (
- index: number,
- updatedChannel: Partial<Omit<TPkiAlertChannelV2, "id" | "createdAt" | "updatedAt">>
- ) => {
- const currentChannels = [...(watchedChannels || [])];
- currentChannels[index] = { ...currentChannels[index], ...updatedChannel };
- setValue("channels", currentChannels);
- };
-
- const onSubmit = async (data: TFormData) => {
- if (!alertId) return;
-
- setIsSubmitting(true);
- try {
- await updateAlert({
- alertId,
- ...data
- });
-
- createNotification({
- text: "PKI alert updated successfully",
- type: "success"
- });
-
- onOpenChange(false);
- } catch {
- createNotification({
- text: "Failed to update PKI alert",
- type: "error"
- });
- } finally {
- setIsSubmitting(false);
- }
- };
-
- const getFieldOperators = (field: PkiFilterFieldV2) => {
- if (field === PkiFilterFieldV2.INCLUDE_CAS) {
- return [PkiFilterOperatorV2.EQUALS];
- }
- return Object.values(PkiFilterOperatorV2);
- };
-
- const isValueBoolean = (field: PkiFilterFieldV2) => {
- return field === PkiFilterFieldV2.INCLUDE_CAS;
- };
-
- const canOperatorTakeArray = (operator: PkiFilterOperatorV2) => {
- return operator === PkiFilterOperatorV2.MATCHES;
- };
-
- if (isLoading) {
- return (
- <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
- <ModalContent title="Update Certificate Alert" className="max-w-4xl">
- <div className="space-y-6">
- <Skeleton className="h-8 w-full" />
- <Skeleton className="h-8 w-full" />
- <Skeleton className="h-32 w-full" />
- </div>
- </ModalContent>
- </Modal>
- );
- }
-
- return (
- <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
- <ModalContent title="Update Certificate Alert" className="max-w-4xl">
- <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
- <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
- <Controller
- control={control}
- name="name"
- render={({ field, fieldState: { error } }) => (
- <FormControl label="Alert Name" isError={Boolean(error)} errorText={error?.message}>
- <Input {...field} placeholder="certificate-expiration-alert" />
- </FormControl>
- )}
- />
-
- <Controller
- control={control}
- name="eventType"
- render={({ field, fieldState: { error } }) => (
- <FormControl label="Event Type" isError={Boolean(error)} errorText={error?.message}>
- <Select value={field.value} onValueChange={(value) => field.onChange(value)}>
- <SelectItem value={PkiAlertEventTypeV2.EXPIRATION}>
- Certificate Expiration
- </SelectItem>
- <SelectItem value={PkiAlertEventTypeV2.RENEWAL}>Certificate Renewal</SelectItem>
- <SelectItem value={PkiAlertEventTypeV2.ISSUANCE}>
- Certificate Issuance
- </SelectItem>
- <SelectItem value={PkiAlertEventTypeV2.REVOCATION}>
- Certificate Revocation
- </SelectItem>
- </Select>
- </FormControl>
- )}
- />
- </div>
-
- <Controller
- control={control}
- name="description"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Description (Optional)"
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <TextArea {...field} placeholder="Alert description..." rows={2} />
- </FormControl>
- )}
- />
-
- <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
- <Controller
- control={control}
- name="alertBefore"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Alert Before (for expiration)"
- isError={Boolean(error)}
- errorText={error?.message}
- helperText="Format: number + unit (d=days, w=weeks, m=months, y=years). Example: 30d"
- >
- <Input {...field} placeholder="30d" />
- </FormControl>
- )}
- />
-
- <Controller
- control={control}
- name="enabled"
- render={({ field }) => (
- <FormControl label="Status">
- <div className="mt-2 flex items-center space-x-2">
- <Switch
- id="alert-enabled-update"
- isChecked={field.value}
- onCheckedChange={field.onChange}
- />
- <span className="text-sm text-gray-300">
- {field.value ? "Enabled" : "Disabled"}
- </span>
- </div>
- </FormControl>
- )}
- />
- </div>
-
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <FormLabel label="Certificate Filter Rules" />
- <Button
- type="button"
- variant="outline_bg"
- size="sm"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- onClick={addFilter}
- >
- Add Filter
- </Button>
- </div>
-
- {watchedFilters?.map((filter, index) => (
- <div
- key={`filter-${filter.field}-${filter.operator}-${String(filter.value)}`}
- className="space-y-3 rounded-lg border border-gray-600 p-4"
- >
- <div className="flex items-center justify-between">
- <h4 className="text-sm font-medium text-gray-200">Filter Rule #{index + 1}</h4>
- <IconButton
- size="sm"
- variant="plain"
- colorSchema="danger"
- ariaLabel="Remove filter"
- onClick={() => removeFilter(index)}
- >
- <FontAwesomeIcon icon={faTrash} />
- </IconButton>
- </div>
-
- <div className="grid grid-cols-1 gap-3 md:grid-cols-3">
- <FormControl label="Field">
- <Select
- value={filter.field}
- onValueChange={(value) =>
- updateFilter(index, {
- field: value as PkiFilterFieldV2,
- operator:
- value === PkiFilterFieldV2.INCLUDE_CAS
- ? PkiFilterOperatorV2.EQUALS
- : filter.operator,
- value: isValueBoolean(value as PkiFilterFieldV2) ? false : ""
- })
- }
- >
- <SelectItem value={PkiFilterFieldV2.COMMON_NAME}>Common Name</SelectItem>
- <SelectItem value={PkiFilterFieldV2.PROFILE_NAME}>Profile Name</SelectItem>
- <SelectItem value={PkiFilterFieldV2.SAN}>
- Subject Alternative Names
- </SelectItem>
- <SelectItem value={PkiFilterFieldV2.INCLUDE_CAS}>
- Include Certificate Authorities
- </SelectItem>
- </Select>
- </FormControl>
-
- <FormControl label="Operator">
- <Select
- value={filter.operator}
- onValueChange={(value) =>
- updateFilter(index, { operator: value as PkiFilterOperatorV2 })
- }
- >
- {getFieldOperators(filter.field).map((operator) => (
- <SelectItem key={operator} value={operator}>
- {operator.replace("_", " ").toUpperCase()}
- </SelectItem>
- ))}
- </Select>
- </FormControl>
-
- <FormControl label="Value">
- {isValueBoolean(filter.field) ? (
- <Select
- value={String(filter.value)}
- onValueChange={(value) => updateFilter(index, { value: value === "true" })}
- >
- <SelectItem value="true">Yes</SelectItem>
- <SelectItem value="false">No</SelectItem>
- </Select>
- ) : (
- <Input
- value={
- Array.isArray(filter.value)
- ? filter.value.join(", ")
- : String(filter.value)
- }
- onChange={(e) => {
- const { value } = e.target;
- const finalValue =
- canOperatorTakeArray(filter.operator) && value.includes(",")
- ? value
- .split(",")
- .map((v) => v.trim())
- .filter(Boolean)
- : value;
- updateFilter(index, { value: finalValue });
- }}
- placeholder={
- canOperatorTakeArray(filter.operator)
- ? "example.com, test.com"
- : "example.com"
- }
- />
- )}
- </FormControl>
- </div>
- </div>
- ))}
- </div>
-
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <FormLabel label="Notification Channels" />
- <Button
- type="button"
- variant="outline_bg"
- size="sm"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- onClick={addChannel}
- >
- Add Channel
- </Button>
- </div>
-
- {watchedChannels?.map((channel, index) => (
- <div
- key={`channel-${channel.channelType}-${JSON.stringify(channel.config)}`}
- className="space-y-3 rounded-lg border border-gray-600 p-4"
- >
- <div className="flex items-center justify-between">
- <h4 className="text-sm font-medium text-gray-200">Channel #{index + 1}</h4>
- {watchedChannels.length > 1 && (
- <IconButton
- size="sm"
- variant="plain"
- colorSchema="danger"
- ariaLabel="Remove channel"
- onClick={() => removeChannel(index)}
- >
- <FontAwesomeIcon icon={faTrash} />
- </IconButton>
- )}
- </div>
-
- <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
- <FormControl label="Channel Type">
- <Select
- value={channel.channelType}
- onValueChange={(value) =>
- updateChannel(index, {
- channelType: value as PkiAlertChannelTypeV2,
- config: { recipients: [] }
- })
- }
- >
- <SelectItem value={PkiAlertChannelTypeV2.EMAIL}>Email</SelectItem>
- </Select>
- </FormControl>
-
- <FormControl label="Status">
- <div className="mt-2 flex items-center space-x-2">
- <Switch
- id={`channel-enabled-update-${index}`}
- isChecked={channel.enabled}
- onCheckedChange={(enabled) => updateChannel(index, { enabled })}
- />
- <span className="text-sm text-gray-300">
- {channel.enabled ? "Enabled" : "Disabled"}
- </span>
- </div>
- </FormControl>
- </div>
-
- <FormControl label="Email Recipients">
- <Input
- value={(channel.config as any)?.recipients?.join(", ") || ""}
- onChange={(e) => {
- const recipients = e.target.value
- .split(",")
- .map((email) => email.trim())
- .filter(Boolean);
- updateChannel(index, { config: { recipients } });
- }}
- />
- </FormControl>
- </div>
- ))}
- </div>
-
- <div className="flex justify-end space-x-3 pt-4">
- <Button type="button" variant="plain" onClick={() => onOpenChange(false)}>
- Cancel
- </Button>
- <Button type="submit" isLoading={isSubmitting} isDisabled={isSubmitting}>
- Update Alert
- </Button>
- </div>
- </form>
- </ModalContent>
- </Modal>
- );
-};
diff --git a/frontend/src/views/PkiAlertsV2Page/components/ViewPkiAlertV2Modal.tsx b/frontend/src/views/PkiAlertsV2Page/components/ViewPkiAlertV2Modal.tsx
index 9aaa85592d..f94d0c6d75 100644
--- a/frontend/src/views/PkiAlertsV2Page/components/ViewPkiAlertV2Modal.tsx
+++ b/frontend/src/views/PkiAlertsV2Page/components/ViewPkiAlertV2Modal.tsx
@@ -1,4 +1,6 @@
import { useEffect, useState } from "react";
+import { faKey } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { CertificateDisplayName } from "@app/components/utilities/certificateDisplayUtils";
import {
@@ -16,15 +18,25 @@ import {
Td,
Th,
THead,
+ Tooltip,
Tr
} from "@app/components/v2";
import { Badge } from "@app/components/v3";
import {
- PkiAlertEventTypeV2,
+ PkiAlertChannelTypeV2,
+ TPkiAlertChannelConfigEmail,
+ TPkiAlertChannelConfigWebhookResponse,
useGetPkiAlertV2ById,
useGetPkiAlertV2MatchingCertificates
} from "@app/hooks/api/pkiAlertsV2";
+import {
+ formatAlertBefore,
+ formatEventType,
+ getChannelIcon,
+ getWebhookHostname
+} from "../utils/pki-alert-formatters";
+
interface Props {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
@@ -65,38 +77,6 @@ export const ViewPkiAlertV2Modal = ({ isOpen, onOpenChange, alertId }: Props) =>
}
}, [isOpen]);
- const formatEventType = (eventType: PkiAlertEventTypeV2) => {
- switch (eventType) {
- case PkiAlertEventTypeV2.EXPIRATION:
- return "Certificate Expiration";
- case PkiAlertEventTypeV2.RENEWAL:
- return "Certificate Renewal";
- case PkiAlertEventTypeV2.ISSUANCE:
- return "Certificate Issuance";
- case PkiAlertEventTypeV2.REVOCATION:
- return "Certificate Revocation";
- default:
- return eventType;
- }
- };
-
- const formatAlertBefore = (alertBefore?: string) => {
- if (!alertBefore) return "Not set";
-
- const match = alertBefore.match(/^(\\d+)([dwmy])$/);
- if (!match) return alertBefore;
-
- const [, value, unit] = match;
- const unitMap = {
- d: "days",
- w: "weeks",
- m: "months",
- y: "years"
- };
-
- return `${value} ${unitMap[unit as keyof typeof unitMap] || unit}`;
- };
-
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString("en-US", {
year: "numeric",
@@ -164,7 +144,9 @@ export const ViewPkiAlertV2Modal = ({ isOpen, onOpenChange, alertId }: Props) =>
<div className="mb-1 block text-sm font-medium text-gray-400">
Alert Before
</div>
- <span className="text-gray-300">{formatAlertBefore(alert.alertBefore)}</span>
+ <span className="text-gray-300">
+ {formatAlertBefore(alert.alertBefore, "Not set")}
+ </span>
</div>
<div>
@@ -206,28 +188,73 @@ export const ViewPkiAlertV2Modal = ({ isOpen, onOpenChange, alertId }: Props) =>
</div>
<div className="space-y-3">
- <h3 className="text-lg font-medium text-gray-200">Notification Recipients</h3>
- {(alert.channels || []).some(
- (channel) =>
- channel.channelType === "email" && (channel.config as any)?.recipients
- ) ? (
+ <h3 className="text-lg font-medium text-gray-200">Notification Channels</h3>
+ {(alert.channels || []).length > 0 ? (
<div className="space-y-3">
- <div>
- <div className="flex flex-wrap gap-1">
- {(alert.channels || [])
- .filter(
- (channel) =>
- channel.channelType === "email" &&
- (channel.config as any)?.recipients
- )
- .flatMap((channel) => (channel.config as any).recipients)
- .map((email: string) => (
- <Badge key={`email-${email}`} variant="neutral" className="text-sm">
- {email}
- </Badge>
- ))}
+ {(alert.channels || []).map((channel) => (
+ <div
+ key={channel.id}
+ className="flex items-start gap-3 rounded-md border border-mineshaft-600 p-3"
+ >
+ <FontAwesomeIcon
+ icon={getChannelIcon(channel.channelType)}
+ className="mt-1 shrink-0 text-mineshaft-400"
+ />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className="font-medium text-mineshaft-100 capitalize">
+ {channel.channelType}
+ </span>
+ {channel.channelType === PkiAlertChannelTypeV2.WEBHOOK &&
+ (channel.config as TPkiAlertChannelConfigWebhookResponse)
+ ?.hasSigningSecret && (
+ <Tooltip content="Signed webhook">
+ <FontAwesomeIcon
+ icon={faKey}
+ className="text-xs text-mineshaft-400"
+ />
+ </Tooltip>
+ )}
+ {!channel.enabled && (
+ <Badge variant="neutral" className="text-xs">
+ Disabled
+ </Badge>
+ )}
+ </div>
+ {channel.channelType === PkiAlertChannelTypeV2.EMAIL && (
+ <div className="mt-1 text-sm text-mineshaft-400">
+ {(() => {
+ const config = channel.config as TPkiAlertChannelConfigEmail;
+ const recipients = config?.recipients || [];
+ const count = recipients.length;
+ if (count === 0) return "No recipients";
+ const displayEmails = recipients.slice(0, 3);
+ const displayText =
+ count <= 3
+ ? displayEmails.join(", ")
+ : `${displayEmails.join(", ")} +${count - 3} more`;
+
+ if (count > 3) {
+ return (
+ <Tooltip content={recipients.join(", ")}>
+ <span className="cursor-help">{displayText}</span>
+ </Tooltip>
+ );
+ }
+ return displayText;
+ })()}
+ </div>
+ )}
+ {channel.channelType === PkiAlertChannelTypeV2.WEBHOOK && (
+ <div className="mt-1 truncate text-sm text-mineshaft-400">
+ {getWebhookHostname(
+ (channel.config as TPkiAlertChannelConfigWebhookResponse).url
+ )}
+ </div>
+ )}
+ </div>
</div>
- </div>
+ ))}
</div>
) : (
<p className="text-gray-400">No notification channels configured</p>
diff --git a/frontend/src/views/PkiAlertsV2Page/components/index.ts b/frontend/src/views/PkiAlertsV2Page/components/index.ts
index 64ccf6dc40..e46bb445e7 100644
--- a/frontend/src/views/PkiAlertsV2Page/components/index.ts
+++ b/frontend/src/views/PkiAlertsV2Page/components/index.ts
@@ -1,4 +1,3 @@
export { CreatePkiAlertV2Modal } from "./CreatePkiAlertV2Modal";
export { PkiAlertV2Row } from "./PkiAlertV2Row";
-export { UpdatePkiAlertV2Modal } from "./UpdatePkiAlertV2Modal";
export { ViewPkiAlertV2Modal } from "./ViewPkiAlertV2Modal";
diff --git a/frontend/src/views/PkiAlertsV2Page/utils/pki-alert-formatters.ts b/frontend/src/views/PkiAlertsV2Page/utils/pki-alert-formatters.ts
new file mode 100644
index 0000000000..cf157278c9
--- /dev/null
+++ b/frontend/src/views/PkiAlertsV2Page/utils/pki-alert-formatters.ts
@@ -0,0 +1,101 @@
+import { IconDefinition } from "@fortawesome/fontawesome-svg-core";
+import { faEnvelope, faLink } from "@fortawesome/free-solid-svg-icons";
+
+import {
+ PkiAlertChannelTypeV2,
+ PkiAlertEventTypeV2,
+ TPkiAlertChannelConfigEmail,
+ TPkiAlertChannelConfigWebhook
+} from "@app/hooks/api/pkiAlertsV2";
+
+/**
+ * Formats the alert event type enum into a human-readable string.
+ */
+export const formatEventType = (eventType: PkiAlertEventTypeV2): string => {
+ switch (eventType) {
+ case PkiAlertEventTypeV2.EXPIRATION:
+ return "Certificate Expiration";
+ case PkiAlertEventTypeV2.RENEWAL:
+ return "Certificate Renewal";
+ case PkiAlertEventTypeV2.ISSUANCE:
+ return "Certificate Issuance";
+ case PkiAlertEventTypeV2.REVOCATION:
+ return "Certificate Revocation";
+ default:
+ return eventType;
+ }
+};
+
+/**
+ * Converts alert timing notation (e.g., "30d") to readable format (e.g., "30 days").
+ * Returns the fallback value for undefined/null values.
+ */
+export const formatAlertBefore = (alertBefore?: string, fallback = "-"): string => {
+ if (!alertBefore) return fallback;
+
+ const match = alertBefore.match(/^(\d+)([dwmy])$/);
+ if (!match) return alertBefore;
+
+ const [, value, unit] = match;
+ const unitMap: Record<string, string> = {
+ d: "days",
+ w: "weeks",
+ m: "months",
+ y: "years"
+ };
+
+ return `${value} ${unitMap[unit] || unit}`;
+};
+
+/**
+ * Returns the appropriate FontAwesome icon for a channel type.
+ */
+export const getChannelIcon = (type: PkiAlertChannelTypeV2): IconDefinition => {
+ switch (type) {
+ case PkiAlertChannelTypeV2.EMAIL:
+ return faEnvelope;
+ case PkiAlertChannelTypeV2.WEBHOOK:
+ return faLink;
+ default:
+ return faEnvelope;
+ }
+};
+
+/**
+ * Extracts hostname from a webhook URL for display purposes.
+ * Returns the URL or "Not configured" if parsing fails.
+ */
+export const getWebhookHostname = (url: string): string => {
+ if (!url) return "Not configured";
+ try {
+ const parsed = new URL(url);
+ return parsed.hostname;
+ } catch {
+ return url || "Not configured";
+ }
+};
+
+/**
+ * Generates a brief summary string for a channel configuration.
+ * Used in collapsed accordion headers and review panels.
+ *
+ * For email: shows recipients (truncated if >2)
+ * For webhook: shows hostname from URL
+ */
+export const getChannelSummary = (channel: {
+ channelType: PkiAlertChannelTypeV2;
+ config: TPkiAlertChannelConfigEmail | TPkiAlertChannelConfigWebhook;
+}): string => {
+ if (channel.channelType === PkiAlertChannelTypeV2.EMAIL) {
+ const config = channel.config as TPkiAlertChannelConfigEmail;
+ const count = config.recipients.length;
+ if (count === 0) return "No recipients";
+ if (count <= 2) return config.recipients.join(", ");
+ return `${config.recipients.slice(0, 2).join(", ")} +${count - 2}`;
+ }
+ if (channel.channelType === PkiAlertChannelTypeV2.WEBHOOK) {
+ const config = channel.config as TPkiAlertChannelConfigWebhook;
+ return getWebhookHostname(config.url);
+ }
+ return "";
+};