Skip to content

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

Add new PKI alert types

Carlos Monastyrskif0cf8650c462
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index a8f57fda40..623951d70d 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -2746,7 +2746,7 @@ interface CreatePkiAlert {
pkiAlertId: string;
pkiCollectionId?: string;
name: string;
- alertBefore: string;
+ alertBefore?: string;
eventType: PkiAlertEventType;
recipientEmails?: string;
};
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index cc6c6ca41b..f4e629e41f 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -71,6 +71,7 @@ export enum QueueName {
FrequentResourceCleanUp = "frequent-resource-cleanup",
DailyExpiringPkiItemAlert = "daily-expiring-pki-item-alert",
DailyPkiAlertV2Processing = "daily-pki-alert-v2-processing",
+ PkiAlertV2Event = "pki-alert-v2-event",
PkiSyncCleanup = "pki-sync-cleanup",
PkiSubscriber = "pki-subscriber",
TelemetryInstanceStats = "telemtry-self-hosted-stats",
@@ -128,6 +129,7 @@ export enum QueueJobs {
FrequentResourceCleanUp = "frequent-resource-cleanup-job",
DailyExpiringPkiItemAlert = "daily-expiring-pki-item-alert",
DailyPkiAlertV2Processing = "daily-pki-alert-v2-processing",
+ PkiAlertV2ProcessEvent = "pki-alert-v2-process-event",
PkiSyncCleanup = "pki-sync-cleanup-job",
SecWebhook = "secret-webhook-trigger",
TelemetryInstanceStats = "telemetry-self-hosted-stats",
@@ -253,6 +255,14 @@ export type TQueueJobTypes = {
name: QueueJobs.DailyPkiAlertV2Processing;
payload: undefined;
};
+ [QueueName.PkiAlertV2Event]: {
+ name: QueueJobs.PkiAlertV2ProcessEvent;
+ payload: {
+ certificateId: string;
+ projectId: string;
+ eventType: string;
+ };
+ };
[QueueName.PkiSyncCleanup]: {
name: QueueJobs.PkiSyncCleanup;
payload: undefined;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 04305b5232..121b864225 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2442,7 +2442,8 @@ export const registerRoutes = async (
pkiSyncDAL,
pkiSyncQueue,
certificateAuthorityService,
- resourceMetadataDAL
+ resourceMetadataDAL,
+ pkiAlertV2Queue
});
const certificateRequestService = certificateRequestServiceFactory({
@@ -2469,7 +2470,8 @@ export const registerRoutes = async (
pkiSyncQueue,
certificateProfileDAL,
certificateRequestService,
- resourceMetadataDAL
+ resourceMetadataDAL,
+ pkiAlertV2Queue
});
const certificateApprovalService = certificateApprovalServiceFactory({
@@ -2532,7 +2534,8 @@ export const registerRoutes = async (
userDAL,
identityDAL,
approvalPolicyService,
- resourceMetadataDAL
+ resourceMetadataDAL,
+ pkiAlertV2Queue
});
const certificateV3Queue = certificateV3QueueServiceFactory({
diff --git a/backend/src/server/routes/v1/pki-alert-router.ts b/backend/src/server/routes/v1/pki-alert-router.ts
index 4cbb194a88..f18728a23a 100644
--- a/backend/src/server/routes/v1/pki-alert-router.ts
+++ b/backend/src/server/routes/v1/pki-alert-router.ts
@@ -6,7 +6,7 @@ import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
import {
- CreatePkiAlertV2Schema,
+ BasePkiAlertV2Schema,
createSecureAlertBeforeValidator,
NotificationConfigSchema,
PkiAlertChannelType,
@@ -29,7 +29,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
operationId: "createPkiAlertV1",
description: "Create a new PKI alert",
tags: [ApiDocsTags.PkiAlerting],
- body: CreatePkiAlertV2Schema.extend({
+ body: BasePkiAlertV2Schema.extend({
projectId: z.string().uuid().describe("Project ID")
}),
response: {
@@ -39,7 +39,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
name: z.string(),
description: z.string().nullable(),
eventType: z.nativeEnum(PkiAlertEventType),
- alertBefore: z.string(),
+ alertBefore: z.string().optional(),
filters: z.array(PkiFilterRuleSchema),
enabled: z.boolean(),
projectId: z.string().uuid(),
@@ -115,7 +115,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
name: z.string(),
description: z.string().nullable(),
eventType: z.nativeEnum(PkiAlertEventType),
- alertBefore: z.string(),
+ alertBefore: z.string().optional(),
filters: z.array(PkiFilterRuleSchema),
enabled: z.boolean(),
notificationConfig: NotificationConfigSchema.nullable(),
@@ -179,7 +179,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
name: z.string(),
description: z.string().nullable(),
eventType: z.nativeEnum(PkiAlertEventType),
- alertBefore: z.string(),
+ alertBefore: z.string().optional(),
filters: z.array(PkiFilterRuleSchema),
enabled: z.boolean(),
projectId: z.string().uuid(),
@@ -247,7 +247,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
name: z.string(),
description: z.string().nullable(),
eventType: z.nativeEnum(PkiAlertEventType),
- alertBefore: z.string(),
+ alertBefore: z.string().optional(),
filters: z.array(PkiFilterRuleSchema),
enabled: z.boolean(),
projectId: z.string().uuid(),
@@ -318,7 +318,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
name: z.string(),
description: z.string().nullable(),
eventType: z.nativeEnum(PkiAlertEventType),
- alertBefore: z.string(),
+ alertBefore: z.string().optional(),
filters: z.array(PkiFilterRuleSchema),
enabled: z.boolean(),
projectId: z.string().uuid(),
diff --git a/backend/src/server/routes/v2/pki-alert-router.ts b/backend/src/server/routes/v2/pki-alert-router.ts
index fcf51c0de0..80e3d25375 100644
--- a/backend/src/server/routes/v2/pki-alert-router.ts
+++ b/backend/src/server/routes/v2/pki-alert-router.ts
@@ -6,7 +6,7 @@ import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
import {
- CreatePkiAlertV2Schema,
+ BasePkiAlertV2Schema,
createSecureAlertBeforeValidator,
NotificationConfigSchema,
PkiAlertChannelType,
@@ -28,7 +28,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
operationId: "createPkiAlert",
description: "Create a new PKI alert",
tags: [ApiDocsTags.PkiAlerting],
- body: CreatePkiAlertV2Schema.extend({
+ body: BasePkiAlertV2Schema.extend({
projectId: z.string().uuid().describe("Project ID")
}),
response: {
@@ -38,7 +38,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
name: z.string(),
description: z.string().nullable(),
eventType: z.nativeEnum(PkiAlertEventType),
- alertBefore: z.string(),
+ alertBefore: z.string().optional(),
filters: z.array(PkiFilterRuleSchema),
enabled: z.boolean(),
projectId: z.string().uuid(),
@@ -113,7 +113,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
name: z.string(),
description: z.string().nullable(),
eventType: z.nativeEnum(PkiAlertEventType),
- alertBefore: z.string(),
+ alertBefore: z.string().optional(),
filters: z.array(PkiFilterRuleSchema),
enabled: z.boolean(),
notificationConfig: NotificationConfigSchema.nullable(),
@@ -176,7 +176,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
name: z.string(),
description: z.string().nullable(),
eventType: z.nativeEnum(PkiAlertEventType),
- alertBefore: z.string(),
+ alertBefore: z.string().optional(),
filters: z.array(PkiFilterRuleSchema),
enabled: z.boolean(),
projectId: z.string().uuid(),
@@ -243,7 +243,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
name: z.string(),
description: z.string().nullable(),
eventType: z.nativeEnum(PkiAlertEventType),
- alertBefore: z.string(),
+ alertBefore: z.string().optional(),
filters: z.array(PkiFilterRuleSchema),
enabled: z.boolean(),
projectId: z.string().uuid(),
@@ -313,7 +313,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
name: z.string(),
description: z.string().nullable(),
eventType: z.nativeEnum(PkiAlertEventType),
- alertBefore: z.string(),
+ alertBefore: z.string().optional(),
filters: z.array(PkiFilterRuleSchema),
enabled: z.boolean(),
projectId: z.string().uuid(),
diff --git a/backend/src/services/certificate-authority/certificate-issuance-queue.ts b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
index ca4dad647a..041e156ae1 100644
--- a/backend/src/services/certificate-authority/certificate-issuance-queue.ts
+++ b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
@@ -21,6 +21,8 @@ import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-
import { CertKeyAlgorithm } from "../certificate-common/certificate-constants";
import { TCertificateRequestServiceFactory } from "../certificate-request/certificate-request-service";
import { CertificateRequestStatus } from "../certificate-request/certificate-request-types";
+import { TPkiAlertV2QueueServiceFactory } from "../pki-alert-v2/pki-alert-v2-queue";
+import { PkiAlertEventType } from "../pki-alert-v2/pki-alert-v2-types";
import { TPkiSubscriberDALFactory } from "../pki-subscriber/pki-subscriber-dal";
import { TPkiSyncDALFactory } from "../pki-sync/pki-sync-dal";
import { TPkiSyncQueueFactory } from "../pki-sync/pki-sync-queue";
@@ -108,6 +110,7 @@ type TCertificateIssuanceQueueFactoryDep = {
"attachCertificateToRequest" | "updateCertificateRequestStatus"
>;
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find" | "insertMany">;
+ pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;
};
export type TCertificateIssuanceQueueFactory = ReturnType<typeof certificateIssuanceQueueFactory>;
@@ -128,7 +131,8 @@ export const certificateIssuanceQueueFactory = ({
pkiSyncQueue,
certificateProfileDAL,
certificateRequestService,
- resourceMetadataDAL
+ resourceMetadataDAL,
+ pkiAlertV2Queue
}: TCertificateIssuanceQueueFactoryDep) => {
const acmeFns = AcmeCertificateAuthorityFns({
appConnectionDAL,
@@ -472,6 +476,16 @@ export const certificateIssuanceQueueFactory = ({
logger.info(
`Successfully processed certificate issuance job with [certificateId=${certificateId}] [caId=${caId}]`
);
+
+ try {
+ await pkiAlertV2Queue?.queueCertificateEvent({
+ certificateId,
+ projectId: ca.projectId,
+ eventType: isRenewal ? PkiAlertEventType.RENEWAL : PkiAlertEventType.ISSUANCE
+ });
+ } catch {
+ logger.debug("Failed to queue PKI alert event for async certificate issuance");
+ }
} catch (error: unknown) {
logger.error(error, `Certificate issuance job failed for [certificateId=${certificateId}] [caId=${caId}]`);
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index c1ec2faff0..eb23031d5b 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -49,6 +49,8 @@ import { TCertificateProfileDALFactory } from "@app/services/certificate-profile
import { EnrollmentType, IssuerType } from "@app/services/certificate-profile/certificate-profile-types";
import { TIdentityDALFactory } from "@app/services/identity/identity-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TPkiAlertV2QueueServiceFactory } from "@app/services/pki-alert-v2/pki-alert-v2-queue";
+import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
import { TUserDALFactory } from "@app/services/user/user-dal";
@@ -152,6 +154,7 @@ type TCertificateV3ServiceFactoryDep = {
identityDAL: Pick<TIdentityDALFactory, "findById">;
approvalPolicyService: Pick<TApprovalPolicyServiceFactory, "createRequestFromPolicy">;
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete" | "find">;
+ pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;
};
export type TCertificateV3ServiceFactory = ReturnType<typeof certificateV3ServiceFactory>;
@@ -633,7 +636,8 @@ export const certificateV3ServiceFactory = ({
userDAL,
identityDAL,
approvalPolicyService,
- resourceMetadataDAL
+ resourceMetadataDAL,
+ pkiAlertV2Queue
}: TCertificateV3ServiceFactoryDep) => {
/**
* Resolves requester name and email based on actor type
@@ -1212,6 +1216,16 @@ export const certificateV3ServiceFactory = ({
const privateKeyForResponse = canReadPrivateKey ? bufferToString(privateKey) : undefined;
+ try {
+ await pkiAlertV2Queue?.queueCertificateEvent({
+ certificateId: cert.id,
+ projectId: profile.projectId,
+ eventType: PkiAlertEventType.ISSUANCE
+ });
+ } catch {
+ logger.debug("Failed to queue PKI issuance alert event");
+ }
+
return {
status: CertificateRequestStatus.ISSUED,
certificate: bufferToString(certificate),
@@ -1578,6 +1592,16 @@ export const certificateV3ServiceFactory = ({
certificateChainString = removeRootCaFromChain(certificateChainString);
}
+ try {
+ await pkiAlertV2Queue?.queueCertificateEvent({
+ certificateId: cert.id,
+ projectId: profile.projectId,
+ eventType: PkiAlertEventType.ISSUANCE
+ });
+ } catch {
+ logger.debug("Failed to queue PKI issuance alert event");
+ }
+
return {
status: CertificateRequestStatus.ISSUED,
certificate: certificateString,
@@ -2374,6 +2398,17 @@ export const certificateV3ServiceFactory = ({
if (removeRootsFromChain) {
finalCertificateChain = removeRootCaFromChain(finalCertificateChain);
}
+
+ try {
+ await pkiAlertV2Queue?.queueCertificateEvent({
+ certificateId: renewalResult.newCert.id,
+ projectId: renewalResult.originalCert.projectId,
+ eventType: PkiAlertEventType.RENEWAL
+ });
+ } catch {
+ logger.debug("Failed to queue PKI renewal alert event");
+ }
+
return {
status: CertificateRequestStatus.ISSUED,
certificate: renewalResult.certificate,
diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.ts
index ccac812c7c..0c50497be8 100644
--- a/backend/src/services/certificate/certificate-service.ts
+++ b/backend/src/services/certificate/certificate-service.ts
@@ -11,6 +11,7 @@ import {
} from "@app/ee/services/permission/project-permission";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";
@@ -21,6 +22,8 @@ import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate
import { TCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/certificate-authority-service";
import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TPkiAlertV2QueueServiceFactory } from "@app/services/pki-alert-v2/pki-alert-v2-queue";
+import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types";
import { TPkiCollectionDALFactory } from "@app/services/pki-collection/pki-collection-dal";
import { TPkiCollectionItemDALFactory } from "@app/services/pki-collection/pki-collection-item-dal";
import { TPkiSyncDALFactory } from "@app/services/pki-sync/pki-sync-dal";
@@ -79,6 +82,7 @@ type TCertificateServiceFactoryDep = {
pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;
certificateAuthorityService: Pick<TCertificateAuthorityServiceFactory, "revokeCertificate">;
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find">;
+ pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;
};
export type TCertificateServiceFactory = ReturnType<typeof certificateServiceFactory>;
@@ -100,7 +104,8 @@ export const certificateServiceFactory = ({
pkiSyncDAL,
pkiSyncQueue,
certificateAuthorityService,
- resourceMetadataDAL
+ resourceMetadataDAL,
+ pkiAlertV2Queue
}: TCertificateServiceFactoryDep) => {
/**
* Return details for certificate with serial number [serialNumber]
@@ -427,6 +432,16 @@ export const certificateServiceFactory = ({
});
}
+ try {
+ await pkiAlertV2Queue?.queueCertificateEvent({
+ certificateId: cert.id,
+ projectId: ca.projectId,
+ eventType: PkiAlertEventType.REVOCATION
+ });
+ } catch {
+ logger.debug("Failed to queue PKI revocation alert event");
+ }
+
// Return appropriate CA format based on CA type
const caResult = ca.externalCa?.id
? {
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
index f3bbb25e9f..39b22e6df9 100644
--- 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
@@ -3,7 +3,27 @@ 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";
+import {
+ getRevocationReasonLabel,
+ PkiAlertEventType,
+ TCertificatePreview,
+ TChannelResult,
+ TEmailChannelConfig
+} from "./pki-alert-v2-types";
+
+const getEmailEventLabel = (eventType: PkiAlertEventType): string => {
+ switch (eventType) {
+ case PkiAlertEventType.ISSUANCE:
+ return "Issuance";
+ case PkiAlertEventType.RENEWAL:
+ return "Renewal";
+ case PkiAlertEventType.REVOCATION:
+ return "Revocation";
+ case PkiAlertEventType.EXPIRATION:
+ default:
+ return "Expiration";
+ }
+};
const isEmailErrorRetryable = (err: Error): boolean => {
const msg = err.message.toLowerCase();
@@ -19,20 +39,27 @@ export const sendEmailNotification = async (
alertName: string,
alertBeforeDays: number,
projectId: string,
- matchingCertificates: TCertificatePreview[]
+ matchingCertificates: TCertificatePreview[],
+ eventType: PkiAlertEventType = PkiAlertEventType.EXPIRATION
): Promise<void> => {
+ const eventLabel = getEmailEventLabel(eventType);
+
await smtpService.sendMail({
recipients: config.recipients,
- subjectLine: `Infisical Certificate Alert - ${alertName}`,
+ subjectLine: `Infisical Certificate ${eventLabel} Alert - ${alertName}`,
substitutions: {
alertName,
alertBeforeDays,
projectId,
+ eventLabel,
items: matchingCertificates.map((cert) => ({
type: "Certificate",
friendlyName: cert.commonName,
serialNumber: cert.serialNumber,
- expiryDate: cert.notAfter.toLocaleDateString()
+ expiryDate: cert.notAfter.toLocaleDateString(),
+ ...(eventType === PkiAlertEventType.REVOCATION
+ ? { revocationReason: getRevocationReasonLabel(cert.revocationReason) }
+ : {})
}))
},
template: SmtpTemplates.PkiExpirationAlert
@@ -46,7 +73,8 @@ export const sendEmailNotificationWithRetry = async (
alertBeforeDays: number,
projectId: string,
matchingCertificates: TCertificatePreview[],
- channelId: string
+ channelId: string,
+ eventType: PkiAlertEventType = PkiAlertEventType.EXPIRATION
): Promise<TChannelResult> => {
const { maxRetries, delayMs } = PKI_ALERT_RETRY_CONFIG;
let lastError: Error | undefined;
@@ -54,7 +82,15 @@ export const sendEmailNotificationWithRetry = async (
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);
+ await sendEmailNotification(
+ smtpService,
+ config,
+ alertName,
+ alertBeforeDays,
+ projectId,
+ matchingCertificates,
+ eventType
+ );
return { success: true };
} catch (err) {
lastError = err instanceof Error ? err : new Error(String(err));
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-channel-pagerduty-fns.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-channel-pagerduty-fns.ts
index 4f40246626..487546ffdd 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-v2-channel-pagerduty-fns.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-channel-pagerduty-fns.ts
@@ -7,7 +7,9 @@ import { logger } from "@app/lib/logger";
import { PKI_ALERT_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "./pki-alert-v2-constants";
import {
+ getRevocationReasonLabel,
pagerDutyIntegrationKeyRegex,
+ PkiAlertEventType,
TAlertInfo,
TBuildPagerDutyPayloadParams,
TCertificatePreview,
@@ -60,15 +62,47 @@ const getSeverity = (certificates: TCertificatePreview[]): "critical" | "error"
* - Caps certificates at 10 to stay under the 512KB payload limit
* - Severity is auto-mapped from the most urgent certificate
*/
+const getPagerDutyEventConfig = (eventType: PkiAlertEventType): { classLabel: string; summaryVerb: string } => {
+ switch (eventType) {
+ case PkiAlertEventType.ISSUANCE:
+ return { classLabel: "certificate-issuance", summaryVerb: "newly issued" };
+ case PkiAlertEventType.RENEWAL:
+ return { classLabel: "certificate-renewal", summaryVerb: "recently renewed" };
+ case PkiAlertEventType.REVOCATION:
+ return { classLabel: "certificate-revocation", summaryVerb: "revoked" };
+ case PkiAlertEventType.EXPIRATION:
+ default:
+ return { classLabel: "certificate-expiration", summaryVerb: "expiring" };
+ }
+};
+
+const getEventSeverity = (
+ eventType: PkiAlertEventType,
+ certificates: TCertificatePreview[]
+): "critical" | "error" | "warning" | "info" => {
+ switch (eventType) {
+ case PkiAlertEventType.REVOCATION:
+ return "warning";
+ case PkiAlertEventType.ISSUANCE:
+ case PkiAlertEventType.RENEWAL:
+ return "info";
+ case PkiAlertEventType.EXPIRATION:
+ default:
+ return getSeverity(certificates);
+ }
+};
+
export const buildPagerDutyPayload = ({
alert,
certificates,
integrationKey,
+ eventType,
appUrl = "https://app.infisical.com"
}: TBuildPagerDutyPayloadParams): TPagerDutyPayload => {
const now = new Date();
const totalCertificates = certificates.length;
- const severity = getSeverity(certificates);
+ const { classLabel, summaryVerb } = getPagerDutyEventConfig(eventType);
+ const severity = getEventSeverity(eventType, certificates);
const sortedCertificates = [...certificates].sort((a, b) => {
const aExpiry = new Date(a.notAfter).getTime();
@@ -80,21 +114,26 @@ export const buildPagerDutyPayload = ({
const viewUrl = `${appUrl}/projects/cert-manager/${alert.projectId}/policies`;
+ const summary =
+ eventType === PkiAlertEventType.EXPIRATION
+ ? `Infisical: ${totalCertificates} certificate(s) expiring within ${alert.alertBefore} - Alert: ${alert.name}`
+ : `Infisical: ${totalCertificates} certificate(s) ${summaryVerb} - Alert: ${alert.name}`;
+
return {
routing_key: integrationKey,
event_action: "trigger",
dedup_key: alert.id,
payload: {
- summary: `Infisical: ${totalCertificates} certificate(s) expiring within ${alert.alertBefore} - Alert: ${alert.name}`,
+ summary,
severity,
source: "infisical-pki-alerts",
timestamp: now.toISOString(),
component: "certificate-manager",
group: alert.projectId,
- class: "certificate-expiration",
+ class: classLabel,
custom_details: {
alert_name: alert.name,
- alert_before: alert.alertBefore,
+ ...(alert.alertBefore ? { alert_before: alert.alertBefore } : {}),
total_certificates: totalCertificates,
certificates: displayCertificates.map((cert) => {
const notAfter = new Date(cert.notAfter);
@@ -103,7 +142,10 @@ export const buildPagerDutyPayload = ({
common_name: cert.commonName || "N/A",
serial_number: cert.serialNumber,
expires_at: notAfter.toISOString(),
- days_until_expiry: daysUntilExpiry
+ days_until_expiry: daysUntilExpiry,
+ ...(eventType === PkiAlertEventType.REVOCATION && cert.revocationReason != null
+ ? { revocation_reason: getRevocationReasonLabel(cert.revocationReason) }
+ : {})
};
}),
view_url: viewUrl
@@ -193,7 +235,8 @@ export const sendPagerDutyNotificationWithRetry = async (
config: TPagerDutyChannelConfig,
alertData: TAlertInfo,
matchingCertificates: TCertificatePreview[],
- channelId: string
+ channelId: string,
+ eventType: PkiAlertEventType = PkiAlertEventType.EXPIRATION
): Promise<TChannelResult> => {
if (!config.integrationKey || !validatePagerDutyIntegrationKey(config.integrationKey)) {
return { success: false, error: "Invalid PagerDuty integration key" };
@@ -204,6 +247,7 @@ export const sendPagerDutyNotificationWithRetry = async (
alert: alertData,
certificates: matchingCertificates,
integrationKey: config.integrationKey,
+ eventType,
appUrl: appCfg.SITE_URL
});
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-channel-slack-fns.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-channel-slack-fns.ts
index 471198df68..a80f719c85 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-v2-channel-slack-fns.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-channel-slack-fns.ts
@@ -9,6 +9,8 @@ import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator/validate-url
import { PKI_ALERT_RETRY_CONFIG, RETRYABLE_NETWORK_ERRORS } from "./pki-alert-v2-constants";
import {
+ getRevocationReasonLabel,
+ PkiAlertEventType,
TAlertInfo,
TBuildSlackPayloadParams,
TCertificatePreview,
@@ -59,13 +61,29 @@ export const validateSlackWebhookUrl = async (url: string): Promise<void> => {
* - "+N more" context if there are additional certificates
* - Action button linking to Infisical
*/
+const getSlackEventConfig = (eventType: PkiAlertEventType): { label: string; color: string; summaryPrefix: string } => {
+ switch (eventType) {
+ case PkiAlertEventType.ISSUANCE:
+ return { label: "Certificate Issuance", color: "#2ea44f", summaryPrefix: "newly issued" };
+ case PkiAlertEventType.RENEWAL:
+ return { label: "Certificate Renewal", color: "#1f6feb", summaryPrefix: "recently renewed" };
+ case PkiAlertEventType.REVOCATION:
+ return { label: "Certificate Revocation", color: "#da3633", summaryPrefix: "revoked" };
+ case PkiAlertEventType.EXPIRATION:
+ default:
+ return { label: "Certificate Expiration", color: "#f0b429", summaryPrefix: "expiring" };
+ }
+};
+
export const buildSlackPayload = ({
alert,
certificates,
+ eventType,
appUrl = "https://app.infisical.com"
}: TBuildSlackPayloadParams): TSlackPayload => {
const totalCertificates = certificates.length;
const now = new Date();
+ const { label, color, summaryPrefix } = getSlackEventConfig(eventType);
// Sort certificates by urgency (days until expiry, ascending - most urgent first)
const sortedCertificates = [...certificates].sort((a, b) => {
@@ -80,10 +98,10 @@ export const buildSlackPayload = ({
const viewUrl = `${appUrl}/projects/cert-manager/${alert.projectId}/policies`;
- const headerText = `Certificate Expiration Alert: ${alert.name}`;
+ const headerText = `${label} Alert: ${alert.name}`;
// Fallback text for notifications
- const fallbackText = `${headerText} - ${totalCertificates} certificate(s) expiring`;
+ const fallbackText = `${headerText} - ${totalCertificates} certificate(s) ${summaryPrefix}`;
// Build header block
const headerBlock: TSlackBlock = {
@@ -98,18 +116,24 @@ export const buildSlackPayload = ({
const notAfter = new Date(cert.notAfter);
const daysUntilExpiry = Math.ceil((notAfter.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
- certificateBlocks.push({
- type: "section",
- fields: [
- { type: "mrkdwn", text: `*Common Name:*\n${cert.commonName || "N/A"}` },
- { type: "mrkdwn", text: `*Serial:*\n\`${cert.serialNumber}\`` },
- {
- type: "mrkdwn",
- text: `*Expires:*\n${notAfter.toISOString().split("T")[0]}`
- },
- { type: "mrkdwn", text: `*Days Until Expiry:*\n${daysUntilExpiry}` }
- ]
- });
+ const fields: Array<{ type: "mrkdwn"; text: string }> = [
+ { type: "mrkdwn", text: `*Common Name:*\n${cert.commonName || "N/A"}` },
+ { type: "mrkdwn", text: `*Serial:*\n\`${cert.serialNumber}\`` },
+ {
+ type: "mrkdwn",
+ text: `*Expires:*\n${notAfter.toISOString().split("T")[0]}`
+ },
+ { type: "mrkdwn", text: `*Days Until Expiry:*\n${daysUntilExpiry}` }
+ ];
+
+ if (eventType === PkiAlertEventType.REVOCATION) {
+ const reason = getRevocationReasonLabel(cert.revocationReason);
+ if (reason) {
+ fields.push({ type: "mrkdwn", text: `*Revocation Reason:*\n${reason}` });
+ }
+ }
+
+ certificateBlocks.push({ type: "section", fields });
// Add divider between certificates (but not after the last one)
if (displayCertificates.indexOf(cert) < displayCertificates.length - 1) {
@@ -118,24 +142,20 @@ export const buildSlackPayload = ({
}
// Build attachment blocks (colored sidebar)
+ const alertInfoFields = [{ type: "mrkdwn" as const, text: `*Alert Name:*\n${alert.name}` }];
+ if (alert.alertBefore) {
+ alertInfoFields.push({ type: "mrkdwn" as const, text: `*Alert Before:*\n${alert.alertBefore}` });
+ }
+
+ const summaryText =
+ eventType === PkiAlertEventType.EXPIRATION && alert.alertBefore
+ ? `*${totalCertificates}* certificate(s) expiring within *${alert.alertBefore}*`
+ : `*${totalCertificates}* certificate(s) ${summaryPrefix}`;
+
const attachmentBlocks: TSlackBlock[] = [
- // Alert info section
- {
- type: "section",
- fields: [
- { type: "mrkdwn", text: `*Alert Name:*\n${alert.name}` },
- { type: "mrkdwn", text: `*Alert Before:*\n${alert.alertBefore}` }
- ]
- },
+ { type: "section", fields: alertInfoFields },
{ type: "divider" },
- // Summary section
- {
- type: "section",
- text: {
- type: "mrkdwn",
- text: `*${totalCertificates}* certificate(s) expiring within *${alert.alertBefore}*`
- }
- },
+ { type: "section", text: { type: "mrkdwn", text: summaryText } },
...certificateBlocks
];
@@ -163,12 +183,7 @@ export const buildSlackPayload = ({
return {
text: fallbackText,
blocks: [headerBlock],
- attachments: [
- {
- color: "#f0b429", // Warning yellow
- blocks: attachmentBlocks
- }
- ]
+ attachments: [{ color, blocks: attachmentBlocks }]
};
};
@@ -247,7 +262,8 @@ export const sendSlackNotificationWithRetry = async (
config: TSlackChannelConfig,
alertData: TAlertInfo,
matchingCertificates: TCertificatePreview[],
- channelId: string
+ channelId: string,
+ eventType: PkiAlertEventType = PkiAlertEventType.EXPIRATION
): Promise<TChannelResult> => {
await validateSlackWebhookUrl(config.webhookUrl);
@@ -255,6 +271,7 @@ export const sendSlackNotificationWithRetry = async (
const payload = buildSlackPayload({
alert: alertData,
certificates: matchingCertificates,
+ eventType,
appUrl: appCfg.SITE_URL
});
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
index 1cdd4276a2..85caa0c589 100644
--- 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
@@ -73,39 +73,29 @@ const transformCertificates = (certificates: TCertificatePreview[]): TCertificat
notBefore: cert.notBefore.toISOString(),
notAfter: cert.notAfter.toISOString(),
status: cert.status,
- daysUntilExpiry
+ daysUntilExpiry,
+ ...(cert.revokedAt ? { revokedAt: new Date(cert.revokedAt).toISOString() } : {}),
+ ...(cert.revocationReason != null ? { revocationReason: cert.revocationReason } : {})
};
});
};
-// 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`
- }
- }
-});
+// Maps webhook event types to their CloudEvents subject string
+const WEBHOOK_EVENT_SUBJECT: Record<PkiWebhookEventType, string> = {
+ [PkiWebhookEventType.CERTIFICATE_EXPIRATION]: "certificate-expiration-alert",
+ [PkiWebhookEventType.CERTIFICATE_ISSUANCE]: "certificate-issuance-alert",
+ [PkiWebhookEventType.CERTIFICATE_RENEWAL]: "certificate-renewal-alert",
+ [PkiWebhookEventType.CERTIFICATE_REVOCATION]: "certificate-revocation-alert",
+ [PkiWebhookEventType.CERTIFICATE_TEST]: "certificate-test"
+};
-const buildCertificateTestEventData = (params: {
+const buildEventData = (params: {
alert: TAlertInfo;
certificates: TCertificatePreview[];
appUrl: string;
+ eventType: PkiWebhookEventType;
}): TBaseEventPayload => ({
- subject: "certificate-test",
+ subject: WEBHOOK_EVENT_SUBJECT[params.eventType],
data: {
alert: {
id: params.alert.id,
@@ -133,18 +123,7 @@ export const buildWebhookPayload = ({
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}`);
- }
- })();
+ const eventData = buildEventData({ alert, certificates, appUrl, eventType });
return { ...base, ...eventData };
};
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 bddd6c3bb5..7e893ffcc6 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
@@ -354,6 +354,7 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
showPreview?: boolean;
excludeAlerted?: boolean;
alertId?: string;
+ certificateId?: string;
},
tx?: Knex
): Promise<{ certificates: TCertificatePreview[]; total: number }> => {
@@ -401,6 +402,10 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
let certCountQuery = (tx || db.replicaNode()).count("* as count").from(TableName.Certificate);
certCountQuery = applyCertificateFilters(certCountQuery, filters, projectId) as typeof certCountQuery;
+ if (options?.certificateId) {
+ certCountQuery = certCountQuery.where(`${TableName.Certificate}.id`, options.certificateId);
+ }
+
if (options?.showPreview) {
certCountQuery = certCountQuery
.whereRaw(`"${TableName.Certificate}"."notAfter" > NOW()`)
@@ -457,7 +462,9 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
`${TableName.Certificate}.notAfter`,
`${TableName.Certificate}.status`,
`${TableName.Certificate}.profileId`,
- `${TableName.Certificate}.pkiSubscriberId`
+ `${TableName.Certificate}.pkiSubscriberId`,
+ `${TableName.Certificate}.revokedAt`,
+ `${TableName.Certificate}.revocationReason`
];
if (needsProfileJoin) {
@@ -468,6 +475,10 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
certificateQuery = applyCertificateFilters(certificateQuery, filters, projectId) as typeof certificateQuery;
+ if (options?.certificateId) {
+ certificateQuery = certificateQuery.where(`${TableName.Certificate}.id`, options.certificateId);
+ }
+
if (options?.showPreview) {
certificateQuery = certificateQuery
.whereRaw(`"${TableName.Certificate}"."notAfter" > NOW()`)
@@ -526,6 +537,8 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
notBefore: Date;
notAfter: Date;
status: string;
+ revokedAt?: Date | null;
+ revocationReason?: number | null;
}>
).map((cert) => {
let enrollmentType = CertificateOrigin.UNKNOWN;
@@ -544,7 +557,9 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
enrollmentType,
notBefore: cert.notBefore,
notAfter: cert.notAfter,
- status: cert.status
+ status: cert.status,
+ revokedAt: cert.revokedAt,
+ revocationReason: cert.revocationReason
};
});
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-queue.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-queue.ts
index 27be954805..e7948a95d0 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-v2-queue.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-queue.ts
@@ -12,7 +12,7 @@ import { CertificateOrigin, PkiAlertEventType, TNotificationConfig, TPkiFilterRu
type TPkiAlertV2QueueServiceFactoryDep = {
queueService: TQueueServiceFactory;
- pkiAlertV2Service: Pick<TPkiAlertV2ServiceFactory, "sendAlertNotifications">;
+ pkiAlertV2Service: Pick<TPkiAlertV2ServiceFactory, "sendAlertNotifications" | "sendEventNotifications">;
pkiAlertV2DAL: Pick<TPkiAlertV2DALFactory, "findByProjectId" | "findMatchingCertificates" | "getDistinctProjectIds">;
pkiAlertHistoryDAL: Pick<TPkiAlertHistoryDALFactory, "findRecentlyAlertedCertificates">;
};
@@ -194,6 +194,42 @@ export const pkiAlertV2QueueServiceFactory = ({
);
};
+ const processEventAlert = async (payload: { certificateId: string; projectId: string; eventType: string }) => {
+ const { certificateId, projectId, eventType } = payload;
+
+ const alerts = await pkiAlertV2DAL.findByProjectId(projectId, {
+ eventType,
+ enabled: true
+ });
+
+ if (alerts.length === 0) return;
+
+ for (const alert of alerts) {
+ try {
+ await pkiAlertV2Service.sendEventNotifications(alert.id, [certificateId], eventType as PkiAlertEventType);
+ logger.info(
+ `Sent ${eventType} notification for alert ${alert.id} (${alert.name}) for certificate ${certificateId}`
+ );
+ } catch (error) {
+ logger.error(error, `Failed to process ${eventType} alert ${alert.id} for certificate ${certificateId}`);
+ }
+ }
+ };
+
+ const queueCertificateEvent = async (payload: {
+ certificateId: string;
+ projectId: string;
+ eventType: PkiAlertEventType;
+ }) => {
+ await queueService.queue(QueueName.PkiAlertV2Event, QueueJobs.PkiAlertV2ProcessEvent, payload, {
+ jobId: `pki-alert-event-${payload.projectId}-${payload.certificateId}-${payload.eventType}`,
+ removeOnFail: { count: 5 },
+ removeOnComplete: true,
+ attempts: 3,
+ backoff: { type: "exponential", delay: 5000 }
+ });
+ };
+
const init = async () => {
if (appCfg.isSecondaryInstance) {
return;
@@ -210,6 +246,17 @@ export const pkiAlertV2QueueServiceFactory = ({
}
});
+ queueService.start(QueueName.PkiAlertV2Event, async (job) => {
+ try {
+ logger.info(`${QueueJobs.PkiAlertV2ProcessEvent}: processing ${job.data.eventType} event`);
+ await processEventAlert(job.data);
+ logger.info(`${QueueJobs.PkiAlertV2ProcessEvent}: completed successfully`);
+ } catch (error) {
+ logger.error(error, `${QueueJobs.PkiAlertV2ProcessEvent}: failed`);
+ throw error;
+ }
+ });
+
await queueService.upsertJobScheduler(
QueueName.DailyPkiAlertV2Processing,
`${JOB_SCHEDULER_PREFIX}:${QueueJobs.DailyPkiAlertV2Processing}`,
@@ -219,6 +266,7 @@ export const pkiAlertV2QueueServiceFactory = ({
};
return {
- init
+ init,
+ queueCertificateEvent
};
};
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 73cfb75bb7..afa84e9377 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
@@ -23,6 +23,7 @@ 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 {
+ alertEventTypeToWebhookEventType,
CertificateOrigin,
PkiAlertChannelType,
PkiAlertEventType,
@@ -187,10 +188,16 @@ export const pkiAlertV2ServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.PkiAlerts);
- try {
- parseTimeToPostgresInterval(alertBefore);
- } catch (error) {
- throw new BadRequestError({ message: "Invalid alertBefore format. Use format like '30d', '1w', '3m', '1y'" });
+ if (eventType === PkiAlertEventType.EXPIRATION && !alertBefore) {
+ throw new BadRequestError({ message: "alertBefore is required for expiration alerts" });
+ }
+
+ if (alertBefore) {
+ try {
+ parseTimeToPostgresInterval(alertBefore);
+ } catch (error) {
+ throw new BadRequestError({ message: "Invalid alertBefore format. Use format like '30d', '1w', '3m', '1y'" });
+ }
}
// Validate webhook and Slack URLs early to provide immediate SSRF feedback
@@ -342,6 +349,12 @@ export const pkiAlertV2ServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.PkiAlerts);
+ const resultingEventType = eventType ?? (alert.eventType as PkiAlertEventType);
+ const resultingAlertBefore = alertBefore !== undefined ? alertBefore : alert.alertBefore;
+ if (resultingEventType === PkiAlertEventType.EXPIRATION && !resultingAlertBefore) {
+ throw new BadRequestError({ message: "alertBefore is required for expiration alerts" });
+ }
+
if (alertBefore) {
try {
parseTimeToPostgresInterval(alertBefore);
@@ -582,38 +595,43 @@ export const pkiAlertV2ServiceFactory = ({
};
};
- const sendAlertNotifications = async (alertId: string, certificateIds: string[]) => {
- const alert = await pkiAlertV2DAL.findByIdWithChannels(alertId);
- if (!alert || !alert.enabled) return;
-
- const { projectId } = alert;
- const channels = alert.channels.filter((channel) => channel.enabled);
- if (channels.length === 0) return;
-
- 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
- );
-
- if (matchingCertificates.length === 0) return;
-
+ const dispatchToChannels = async ({
+ alertId,
+ alertName,
+ alertBefore,
+ projectId,
+ eventType,
+ channels,
+ matchingCertificates,
+ certificateIds
+ }: {
+ alertId: string;
+ alertName: string;
+ alertBefore?: string;
+ projectId: string;
+ eventType: PkiAlertEventType;
+ channels: Array<{
+ id: string;
+ channelType: string;
+ config: unknown;
+ encryptedConfig?: Buffer | null;
+ enabled: boolean;
+ }>;
+ matchingCertificates: TCertificatePreview[];
+ certificateIds: string[];
+ }) => {
let hasNotificationSent = false;
let notificationError: string | undefined;
const errors: string[] = [];
- const alertBeforeDays = parseTimeToDays(alertBefore);
+ const alertBeforeDays = alertBefore ? parseTimeToDays(alertBefore) : 0;
const alertData = {
- id: alert.id,
- name: alert.name,
+ id: alertId,
+ name: alertName,
alertBefore,
projectId
};
+ const webhookEventType = alertEventTypeToWebhookEventType[eventType];
// Get decryptor for channel configs
const { decryptor } = await kmsService.createCipherPairWithDataKey({
@@ -630,11 +648,12 @@ export const pkiAlertV2ServiceFactory = ({
const result = await sendEmailNotificationWithRetry(
smtpService,
config,
- alert.name,
+ alertName,
alertBeforeDays,
projectId,
matchingCertificates,
- channel.id
+ channel.id,
+ eventType
);
return { ...result, channelType: channel.channelType };
}
@@ -644,14 +663,20 @@ export const pkiAlertV2ServiceFactory = ({
config,
alertData,
matchingCertificates,
- PkiWebhookEventType.CERTIFICATE_EXPIRATION,
+ webhookEventType,
channel.id
);
return { ...result, channelType: channel.channelType };
}
case PkiAlertChannelType.SLACK: {
const config = decryptChannelConfig<TSlackChannelConfig>(channel, decryptor);
- const result = await sendSlackNotificationWithRetry(config, alertData, matchingCertificates, channel.id);
+ const result = await sendSlackNotificationWithRetry(
+ config,
+ alertData,
+ matchingCertificates,
+ channel.id,
+ eventType
+ );
return { ...result, channelType: channel.channelType };
}
case PkiAlertChannelType.PAGERDUTY: {
@@ -660,7 +685,8 @@ export const pkiAlertV2ServiceFactory = ({
config,
alertData,
matchingCertificates,
- channel.id
+ channel.id,
+ eventType
);
return { ...result, channelType: channel.channelType };
}
@@ -712,8 +738,8 @@ export const pkiAlertV2ServiceFactory = ({
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}\``,
+ title: `PKI Alert Channel Failed: ${alertName}`,
+ body: `Your PKI alert **${alertName}** failed to deliver notifications: \`${truncatedError}\``,
link: alertingPath
}))
);
@@ -730,6 +756,72 @@ export const pkiAlertV2ServiceFactory = ({
});
};
+ const sendAlertNotifications = async (alertId: string, certificateIds: string[]) => {
+ const alert = await pkiAlertV2DAL.findByIdWithChannels(alertId);
+ if (!alert || !alert.enabled) return;
+
+ const { projectId } = alert;
+ const channels = alert.channels.filter((channel) => channel.enabled);
+ if (channels.length === 0) return;
+
+ 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
+ );
+
+ if (matchingCertificates.length === 0) return;
+
+ await dispatchToChannels({
+ alertId,
+ alertName: alert.name,
+ alertBefore,
+ projectId,
+ eventType: PkiAlertEventType.EXPIRATION,
+ channels,
+ matchingCertificates,
+ certificateIds
+ });
+ };
+
+ const sendEventNotifications = async (alertId: string, certificateIds: string[], eventType: PkiAlertEventType) => {
+ const alert = await pkiAlertV2DAL.findByIdWithChannels(alertId);
+ if (!alert || !alert.enabled) return;
+
+ const { projectId } = alert;
+ const channels = alert.channels.filter((channel) => channel.enabled);
+ if (channels.length === 0) return;
+
+ const filters = (alert.filters ?? []) as TPkiFilterRule[];
+
+ const matchingCertificates: TCertificatePreview[] = [];
+ for (const certId of certificateIds) {
+ // eslint-disable-next-line no-await-in-loop
+ const { certificates } = await pkiAlertV2DAL.findMatchingCertificates(projectId, filters, {
+ certificateId: certId
+ });
+ matchingCertificates.push(...certificates);
+ }
+
+ if (matchingCertificates.length === 0) return;
+
+ await dispatchToChannels({
+ alertId,
+ alertName: alert.name,
+ alertBefore: alert.alertBefore ?? undefined,
+ projectId,
+ eventType,
+ channels,
+ matchingCertificates,
+ certificateIds
+ });
+ };
+
const testWebhookConfig = async ({
projectId,
url,
@@ -803,6 +895,7 @@ export const pkiAlertV2ServiceFactory = ({
listMatchingCertificates,
listCurrentMatchingCertificates,
sendAlertNotifications,
+ sendEventNotifications,
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 72c1f13262..e87e1c6791 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
@@ -65,14 +65,24 @@ export enum PkiAlertRunStatus {
export enum PkiWebhookEventType {
CERTIFICATE_EXPIRATION = "com.infisical.pki.certificate.expiration",
+ CERTIFICATE_ISSUANCE = "com.infisical.pki.certificate.issuance",
+ CERTIFICATE_RENEWAL = "com.infisical.pki.certificate.renewal",
+ CERTIFICATE_REVOCATION = "com.infisical.pki.certificate.revocation",
CERTIFICATE_TEST = "com.infisical.pki.certificate.test"
}
+export const alertEventTypeToWebhookEventType: Record<PkiAlertEventType, PkiWebhookEventType> = {
+ [PkiAlertEventType.EXPIRATION]: PkiWebhookEventType.CERTIFICATE_EXPIRATION,
+ [PkiAlertEventType.ISSUANCE]: PkiWebhookEventType.CERTIFICATE_ISSUANCE,
+ [PkiAlertEventType.RENEWAL]: PkiWebhookEventType.CERTIFICATE_RENEWAL,
+ [PkiAlertEventType.REVOCATION]: PkiWebhookEventType.CERTIFICATE_REVOCATION
+};
+
// Alert info used across event types
export type TAlertInfo = {
id: string;
name: string;
- alertBefore: string;
+ alertBefore?: string;
projectId: string;
};
@@ -87,6 +97,8 @@ export type TCertificateData = {
notAfter: string;
status: string;
daysUntilExpiry: number;
+ revokedAt?: string;
+ revocationReason?: number;
};
export type TPkiWebhookPayload = {
@@ -193,7 +205,7 @@ export const CreateChannelSchema = z.object({
export type TCreateChannel = z.infer<typeof CreateChannelSchema>;
-export const CreatePkiAlertV2Schema = z.object({
+export const BasePkiAlertV2Schema = z.object({
name: z
.string()
.min(1)
@@ -201,7 +213,10 @@ export const CreatePkiAlertV2Schema = z.object({
.refine(createSecureNameValidator(), "Must be a valid name (lowercase, numbers, hyphens only)"),
description: z.string().max(1000).optional(),
eventType: z.nativeEnum(PkiAlertEventType),
- alertBefore: z.string().refine(createSecureAlertBeforeValidator(), "Must be in format like '30d', '1w', '3m', '1y'"),
+ alertBefore: z
+ .string()
+ .refine(createSecureAlertBeforeValidator(), "Must be in format like '30d', '1w', '3m', '1y'")
+ .optional(),
filters: PkiFiltersSchema,
enabled: z.boolean().default(true),
notificationConfig: NotificationConfigSchema.nullable().optional(),
@@ -212,9 +227,19 @@ export const CreatePkiAlertV2Schema = z.object({
.refine((channels) => channels.some((ch) => ch.enabled), "At least one notification channel must be enabled")
});
+export const CreatePkiAlertV2Schema = BasePkiAlertV2Schema.superRefine((data, ctx) => {
+ if (data.eventType === PkiAlertEventType.EXPIRATION && !data.alertBefore) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "alertBefore is required for expiration alerts",
+ path: ["alertBefore"]
+ });
+ }
+});
+
export type TCreatePkiAlertV2 = z.infer<typeof CreatePkiAlertV2Schema>;
-export const UpdatePkiAlertV2Schema = CreatePkiAlertV2Schema.partial();
+export const UpdatePkiAlertV2Schema = BasePkiAlertV2Schema.partial();
export type TUpdatePkiAlertV2 = z.infer<typeof UpdatePkiAlertV2Schema>;
export type TCreateAlertV2DTO = TGenericPermission & {
@@ -266,6 +291,8 @@ export type TCertificatePreview = {
notBefore: Date;
notAfter: Date;
status: string;
+ revokedAt?: Date | null;
+ revocationReason?: number | null;
};
// Channel config type for responses (webhook has hasSigningSecret instead of signingSecret)
@@ -286,7 +313,7 @@ export type TAlertV2Response = {
name: string;
description: string | null;
eventType: PkiAlertEventType;
- alertBefore: string;
+ alertBefore?: string;
filters: TPkiFilters;
enabled: boolean;
projectId: string;
@@ -351,6 +378,7 @@ export type TSlackPayload = {
export type TBuildSlackPayloadParams = {
alert: TAlertInfo;
certificates: TCertificatePreview[];
+ eventType: PkiAlertEventType;
appUrl?: string;
};
@@ -368,7 +396,7 @@ export type TPagerDutyPayload = {
class: string;
custom_details: {
alert_name: string;
- alert_before: string;
+ alert_before?: string;
total_certificates: number;
certificates: Array<{
common_name: string;
@@ -382,9 +410,35 @@ export type TPagerDutyPayload = {
links: Array<{ href: string; text: string }>;
};
+// RFC 5280 CRL reason code to human-readable label
+const CRL_REASON_LABELS: Record<number, string> = {
+ 0: "Unspecified",
+ 1: "Key Compromise",
+ 2: "CA Compromise",
+ 3: "Affiliation Changed",
+ 4: "Superseded",
+ 5: "Cessation of Operation",
+ 6: "Certificate Hold",
+ 8: "Remove from CRL",
+ 9: "Privilege Withdrawn",
+ 10: "AA Compromise"
+};
+
+export const getRevocationReasonLabel = (code?: number | null): string | undefined => {
+ if (code == null) return undefined;
+ return CRL_REASON_LABELS[code] ?? `Unknown (${code})`;
+};
+
export type TBuildPagerDutyPayloadParams = {
alert: TAlertInfo;
certificates: TCertificatePreview[];
integrationKey: string;
+ eventType: PkiAlertEventType;
appUrl?: string;
};
+
+export type TPkiCertificateEventPayload = {
+ certificateId: string;
+ projectId: string;
+ eventType: PkiAlertEventType;
+};
diff --git a/backend/src/services/smtp/emails/PkiExpirationAlertTemplate.tsx b/backend/src/services/smtp/emails/PkiExpirationAlertTemplate.tsx
index 66df944393..65da992da1 100644
--- a/backend/src/services/smtp/emails/PkiExpirationAlertTemplate.tsx
+++ b/backend/src/services/smtp/emails/PkiExpirationAlertTemplate.tsx
@@ -7,14 +7,29 @@ interface PkiExpirationAlertTemplateProps extends Omit<BaseEmailWrapperProps, "t
alertName: string;
alertBeforeDays: number;
projectId: string;
- items: { type: string; friendlyName: string; serialNumber: string; expiryDate: string }[];
+ eventLabel?: string;
+ items: { type: string; friendlyName: string; serialNumber: string; expiryDate: string; revocationReason?: string }[];
}
+const getEventVerb = (eventLabel: string): string => {
+ switch (eventLabel) {
+ case "Issuance":
+ return "been issued";
+ case "Renewal":
+ return "been renewed";
+ case "Revocation":
+ return "been revoked";
+ default:
+ return "";
+ }
+};
+
export const PkiExpirationAlertTemplate = ({
alertName,
siteUrl,
alertBeforeDays,
projectId,
+ eventLabel = "Expiration",
items
}: PkiExpirationAlertTemplateProps) => {
const formatDate = (dateStr: string) => {
@@ -29,25 +44,34 @@ export const PkiExpirationAlertTemplate = ({
}
};
+ const isExpiration = eventLabel === "Expiration";
const certificateText = items.length === 1 ? "certificate" : "certificates";
- const daysText = alertBeforeDays === 1 ? "1 day" : `${alertBeforeDays} days`;
+ const countText = items.length === 1 ? "one" : String(items.length);
+
+ const title = isExpiration ? "Certificate Expiration Notice" : `Certificate ${eventLabel} Notice`;
+
+ let message: string;
+ if (isExpiration) {
+ const daysText = alertBeforeDays === 1 ? "1 day" : `${alertBeforeDays} days`;
+ message = `Alert ${alertName}: You have ${countText} ${certificateText} expiring within ${daysText}.`;
+ } else {
+ const verb = getEventVerb(eventLabel);
+ message = `Alert ${alertName}: ${items.length === 1 ? "A" : `${items.length}`} ${certificateText} ${items.length === 1 ? "has" : "have"} ${verb}.`;
+ }
- const message = `Alert ${alertName}: You have ${items.length === 1 ? "one" : items.length} ${certificateText} that will expire in ${daysText}.`;
+ const listHeading = isExpiration ? "Expiring certificates:" : "Affected certificates:";
return (
- <BaseEmailWrapper title="Certificate Expiration Notice" preview={message} siteUrl={siteUrl}>
+ <BaseEmailWrapper title={title} preview={message} siteUrl={siteUrl}>
<Heading className="text-black text-[18px] leading-[28px] text-center font-normal p-0 mx-0">
- <strong>Certificate Expiration Notice</strong>
+ <strong>{title}</strong>
</Heading>
<Section className="px-[24px] mb-[28px] mt-[36px] pt-[12px] pb-[8px] border border-solid border-gray-200 rounded-md bg-gray-50">
- <Text className="text-[14px]">
- Alert <strong className="font-semibold">{alertName}</strong>: You have{" "}
- {items.length === 1 ? "one" : items.length} {certificateText} that will expire in {daysText}.
- </Text>
+ <Text className="text-[14px]">{message}</Text>
</Section>
<Section className="mb-[28px]">
- <Text className="text-[14px] font-semibold mb-[12px]">Expiring certificates:</Text>
+ <Text className="text-[14px] font-semibold mb-[12px]">{listHeading}</Text>
{items.map((item) => (
<Section
key={item.serialNumber}
@@ -55,7 +79,10 @@ export const PkiExpirationAlertTemplate = ({
>
<Text className="text-[14px] font-semibold m-0 mb-[4px]">{item.friendlyName}</Text>
<Text className="text-[12px] text-gray-600 m-0 mb-[4px]">Serial: {item.serialNumber}</Text>
- <Text className="text-[12px] text-gray-600 m-0">Expires: {formatDate(item.expiryDate)}</Text>
+ <Text className="text-[12px] text-gray-600 m-0 mb-[4px]">Expires: {formatDate(item.expiryDate)}</Text>
+ {item.revocationReason && (
+ <Text className="text-[12px] text-red-600 m-0">Revocation Reason: {item.revocationReason}</Text>
+ )}
</Section>
))}
</Section>
diff --git a/docs/documentation/platform/pki/alerting/overview.mdx b/docs/documentation/platform/pki/alerting/overview.mdx
index 470aba0f96..d2fd8c9ab1 100644
--- a/docs/documentation/platform/pki/alerting/overview.mdx
+++ b/docs/documentation/platform/pki/alerting/overview.mdx
@@ -1,12 +1,21 @@
---
title: "Alerting"
sidebarTitle: "Overview"
-description: "Learn how to set up alerting for expiring certificates with Infisical"
+description: "Learn how to set up alerting for certificate lifecycle events with Infisical"
---
## Concept
-In order to ensure that your certificates are always up-to-date and not expired, you can set up alerting in Infisical for expiring CA and leaf certificates based on customizable filters.
+Infisical allows you to configure alerts for key certificate lifecycle events, keeping your team informed when certificates are issued, renewed, revoked, or approaching expiration. Alerts are configured per project and can be delivered through multiple notification channels.
+
+### Supported Alert Types
+
+| Alert Type | Trigger | Description |
+|---|---|---|
+| **Certificate Expiration** | Scheduled (daily check) | Notifies when certificates are approaching their expiration date, based on a configurable time window (e.g., 30 days before expiry). |
+| **Certificate Issuance** | Real time | Notifies when a new certificate is issued through a certificate profile (via API, CSR signing, or EST/ACME enrollment). |
+| **Certificate Renewal** | Real time | Notifies when an existing certificate is renewed, either manually or through auto renewal. |
+| **Certificate Revocation** | Real time | Notifies when a certificate is revoked. |
## Guide to Creating an Alert
@@ -20,17 +29,22 @@ To create an alert, head to your Certificate Management Project > Alerting and p
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`.
+- **Alert Type**: The type of certificate event to alert on. Options are **Certificate Expiration**, **Certificate Issuance**, **Certificate Renewal**, and **Certificate Revocation**.
+- **Alert Name**: A slug friendly name for the alert such as `tls-expiry-alert` or `prod-issuance-notify`.
- **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`.
-- **Daily Alerts**: When not enabled, a single notification is sent when the threshold is first reached. Enabling this option sends notifications every day until the certificate expires or is renewed.
+- **Alert Before** *(Expiration alerts only)*: The time before certificate expiration to trigger the alert, such as 30 days denoted by `30d`. Supported units: `d` (days), `w` (weeks), `m` (months), `y` (years).
+- **Daily Alerts** *(Expiration alerts only)*: When not enabled, a single notification is sent when the threshold is first reached. Enabling this option sends notifications every day until the certificate expires or is renewed.
<Warning>
For certificates that cannot be renewed through Infisical, daily alerts will continue to be sent each day until the original expiration date.
</Warning>
+
- **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`.
+<Note>
+ For event driven alert types (Issuance, Renewal, Revocation), notifications are sent in real time when the event occurs. For Expiration alerts, Infisical checks for matching certificates on a daily schedule.
+</Note>
+
### Notification Channels
Alerts can be delivered through one or more notification channels:
@@ -42,4 +56,4 @@ Alerts can be delivered through one or more notification channels:
You can configure up to 10 notification channels per alert.
-![pki alerting channels](/images/platform/pki/alerting/alert-create-channels.png)
\ No newline at end of file
+![pki alerting channels](/images/platform/pki/alerting/alert-create-channels.png)
diff --git a/docs/documentation/platform/pki/alerting/pagerduty-alerts.mdx b/docs/documentation/platform/pki/alerting/pagerduty-alerts.mdx
index 67413c4de5..a77233e81f 100644
--- a/docs/documentation/platform/pki/alerting/pagerduty-alerts.mdx
+++ b/docs/documentation/platform/pki/alerting/pagerduty-alerts.mdx
@@ -34,10 +34,10 @@ Infisical can send PKI certificate alert notifications to PagerDuty using the [E
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`.
+ - **Alert Type**: The type of certificate event to alert on. Options are **Certificate Expiration**, **Certificate Issuance**, **Certificate Renewal**, and **Certificate Revocation**.
+ - **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`.
+ - **Alert Before** *(Expiration alerts only)*: 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`.
</Step>
<Step title="Add a PagerDuty Notification Channel">
@@ -53,7 +53,9 @@ Keep your integration key secure. Anyone with access to it can send events to yo
## Severity Mapping
-Infisical automatically maps the time remaining until certificate expiry to a PagerDuty event severity:
+### Expiration Alerts
+
+For expiration alerts, Infisical automatically maps the time remaining until certificate expiry to a PagerDuty event severity:
| Time Until Expiry | PagerDuty Severity |
| --- | --- |
@@ -62,6 +64,14 @@ Infisical automatically maps the time remaining until certificate expiry to a Pa
| ≤ 30 days | `warning` |
| > 30 days | `info` |
+### Other Alert Types
+
+| Alert Type | PagerDuty Severity |
+| --- | --- |
+| Certificate Issuance | `info` |
+| Certificate Renewal | `info` |
+| Certificate Revocation | `warning` |
+
## Incident Grouping
Alerts with the same alert ID are grouped into the same PagerDuty incident via `dedup_key`. This means repeated triggers update the existing incident rather than creating duplicates.
diff --git a/docs/documentation/platform/pki/alerting/slack-alerts.mdx b/docs/documentation/platform/pki/alerting/slack-alerts.mdx
index 7c357d7348..55acd3c8f4 100644
--- a/docs/documentation/platform/pki/alerting/slack-alerts.mdx
+++ b/docs/documentation/platform/pki/alerting/slack-alerts.mdx
@@ -35,10 +35,10 @@ Infisical can send PKI certificate alert notifications to a Slack channel using
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`.
+ - **Alert Type**: The type of certificate event to alert on. Options are **Certificate Expiration**, **Certificate Issuance**, **Certificate Renewal**, and **Certificate Revocation**.
+ - **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`.
+ - **Alert Before** *(Expiration alerts only)*: 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`.
</Step>
<Step title="Add a Slack Notification Channel">
@@ -52,4 +52,4 @@ Infisical can send PKI certificate alert notifications to a Slack channel using
Keep your webhook URL secure. Anyone with access to it can post messages to your Slack channel.
</Note>
-Slack messages include alert details and the two most urgent expiring certificates, with a link to view all certificates in Infisical.
+Slack messages include alert details and the two most relevant certificates, with a link to view all certificates in Infisical. Messages are color coded by event type: amber for expiration, green for issuance, blue for renewal, and red for revocation.
diff --git a/docs/documentation/platform/pki/alerting/webhook-alerts.mdx b/docs/documentation/platform/pki/alerting/webhook-alerts.mdx
index aed27e3432..07dba94565 100644
--- a/docs/documentation/platform/pki/alerting/webhook-alerts.mdx
+++ b/docs/documentation/platform/pki/alerting/webhook-alerts.mdx
@@ -16,19 +16,32 @@ To create an alert, head to your Certificate Management Project > Alerting and p
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`.
+- **Alert Type**: The type of certificate event to alert on. Options are **Certificate Expiration**, **Certificate Issuance**, **Certificate Renewal**, and **Certificate Revocation**.
+- **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`.
+- **Alert Before** *(Expiration alerts only)*: 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`.
Next, add a **Webhook** notification channel. The URL must use HTTPS. Optionally configure a signing secret to verify the authenticity of webhook payloads.
![pki alerting channels](/images/platform/pki/alerting/alert-create-channels.png)
+## Webhook Event Types
+
+Each alert type maps to a corresponding CloudEvents event type:
+
+| Alert Type | Event Type | Subject |
+|---|---|---|
+| Certificate Expiration | `com.infisical.pki.certificate.expiration` | `certificate-expiration-alert` |
+| Certificate Issuance | `com.infisical.pki.certificate.issuance` | `certificate-issuance-alert` |
+| Certificate Renewal | `com.infisical.pki.certificate.renewal` | `certificate-renewal-alert` |
+| Certificate Revocation | `com.infisical.pki.certificate.revocation` | `certificate-revocation-alert` |
+
## Webhook Payload Format
-Webhook notifications are sent as HTTP POST requests with a [CloudEvents](https://cloudevents.io/)-compliant JSON payload.
+Webhook notifications are sent as HTTP POST requests with a [CloudEvents](https://cloudevents.io/) compliant JSON payload.
+
+### Expiration Alert Payload
```json
{
@@ -67,6 +80,48 @@ Webhook notifications are sent as HTTP POST requests with a [CloudEvents](https:
}
```
+### Issuance, Renewal, and Revocation Alert Payload
+
+Event driven alerts (issuance, renewal, revocation) share the same payload structure. The `type` and `subject` fields reflect the specific event, and `alertBefore` is omitted since these are real time notifications.
+
+For revocation alerts, each certificate in the array will also include `revokedAt` and `revocationReason` fields when available.
+
+```json
+{
+ "specversion": "1.0",
+ "type": "com.infisical.pki.certificate.issuance",
+ "source": "/projects/<project-id>/alerts/<alert-id>",
+ "id": "<unique-event-id>",
+ "time": "2024-06-15T14:22:00.000Z",
+ "datacontenttype": "application/json",
+ "subject": "certificate-issuance-alert",
+ "data": {
+ "alert": {
+ "id": "<alert-id>",
+ "name": "prod-issuance-notify",
+ "projectId": "<project-id>"
+ },
+ "certificates": [
+ {
+ "id": "<certificate-id>",
+ "serialNumber": "9876543210",
+ "commonName": "api.example.com",
+ "san": ["api.example.com"],
+ "profileName": "API Server",
+ "notBefore": "2024-06-15T00:00:00.000Z",
+ "notAfter": "2025-06-15T23:59:59.000Z",
+ "status": "active",
+ "daysUntilExpiry": 365
+ }
+ ],
+ "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.
@@ -80,13 +135,13 @@ 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
+- `<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
+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:
diff --git a/frontend/src/hooks/api/pkiAlertsV2/types.ts b/frontend/src/hooks/api/pkiAlertsV2/types.ts
index c7b511295b..47a154274c 100644
--- a/frontend/src/hooks/api/pkiAlertsV2/types.ts
+++ b/frontend/src/hooks/api/pkiAlertsV2/types.ts
@@ -277,7 +277,7 @@ export const pkiAlertChannelV2Schema = z.discriminatedUnion("channelType", [
pagerdutyChannelSchema
]);
-export const createPkiAlertV2Schema = z.object({
+const basePkiAlertV2Schema = z.object({
projectId: z.string().uuid(),
name: z
.string()
@@ -303,4 +303,14 @@ export const createPkiAlertV2Schema = z.object({
)
});
-export const updatePkiAlertV2Schema = createPkiAlertV2Schema.partial().omit({ projectId: true });
+export const createPkiAlertV2Schema = basePkiAlertV2Schema.superRefine((data, ctx) => {
+ if (data.eventType === PkiAlertEventTypeV2.EXPIRATION && !data.alertBefore) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Alert Before is required for expiration alerts",
+ path: ["alertBefore"]
+ });
+ }
+});
+
+export const updatePkiAlertV2Schema = basePkiAlertV2Schema.partial().omit({ projectId: true });
diff --git a/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2FormSteps.tsx b/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2FormSteps.tsx
index 4bab804c86..5a7191d575 100644
--- a/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2FormSteps.tsx
+++ b/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2FormSteps.tsx
@@ -80,6 +80,7 @@ const MAX_CHANNELS = 10;
interface CreatePkiAlertV2FormStepsProps {
expandedChannel: string | undefined;
setExpandedChannel: (channel: string | undefined) => void;
+ showPreview?: boolean;
}
type ChannelUIState = {
@@ -93,7 +94,8 @@ type ChannelUIState = {
export const CreatePkiAlertV2FormSteps = ({
expandedChannel,
- setExpandedChannel
+ setExpandedChannel,
+ showPreview = true
}: CreatePkiAlertV2FormStepsProps) => {
const {
control,
@@ -344,6 +346,13 @@ export const CreatePkiAlertV2FormSteps = ({
<SelectItem value={PkiAlertEventTypeV2.EXPIRATION}>
Certificate Expiration
</SelectItem>
+ <SelectItem value={PkiAlertEventTypeV2.ISSUANCE}>
+ Certificate Issuance
+ </SelectItem>
+ <SelectItem value={PkiAlertEventTypeV2.RENEWAL}>Certificate Renewal</SelectItem>
+ <SelectItem value={PkiAlertEventTypeV2.REVOCATION}>
+ Certificate Revocation
+ </SelectItem>
</Select>
</FormControl>
)}
@@ -563,112 +572,116 @@ export const CreatePkiAlertV2FormSteps = ({
</div>
</Tab.Panel>
- <Tab.Panel>
- <div className="space-y-6">
- <p className="mb-4 text-sm text-bunker-300">
- Preview all certificates that match your filter criteria. This shows all non-expired
- certificates that would be monitored by this alert.
- </p>
+ {showPreview && (
+ <Tab.Panel>
+ <div className="space-y-6">
+ <p className="mb-4 text-sm text-bunker-300">
+ Preview certificates that match your filter criteria. This helps verify your filters
+ are targeting the correct certificates.
+ </p>
+
+ <div className="space-y-4">
+ <TableContainer>
+ <Table>
+ <THead>
+ <Tr>
+ <Th className="w-1/2">SAN / CN</Th>
+ <Th className="w-1/4">Not Before</Th>
+ <Th className="w-1/4">Not After</Th>
+ </Tr>
+ </THead>
+ <TBody>
+ {(() => {
+ if (watchedEventType !== PkiAlertEventTypeV2.EXPIRATION) {
+ return (
+ <Tr>
+ <Td colSpan={3} className="py-8 text-center text-gray-400">
+ Certificate preview is available for expiration alerts. For other
+ alert types, notifications are triggered in real time when the event
+ occurs.
+ </Td>
+ </Tr>
+ );
+ }
+
+ if (isLoadingCurrentCertificates) {
+ return Array.from({ length: 5 }, (_, index) => (
+ <Tr key={`skeleton-row-${index}`}>
+ <Td>
+ <Skeleton className="h-4 w-32" />
+ </Td>
+ <Td>
+ <Skeleton className="h-4 w-24" />
+ </Td>
+ <Td>
+ <Skeleton className="h-4 w-24" />
+ </Td>
+ </Tr>
+ ));
+ }
+
+ if (currentCertificatesData?.certificates?.length) {
+ return currentCertificatesData.certificates.map((cert) => (
+ <Tr key={cert.id} className="group h-10">
+ <Td className="max-w-0">
+ <div className="flex items-center gap-2">
+ <CertificateDisplayName
+ cert={{
+ altNames: cert.san?.join(", ") || null,
+ commonName: cert.commonName
+ }}
+ maxLength={48}
+ fallback="—"
+ />
+ {(cert.enrollmentType === "ca" ||
+ cert.enrollmentType === "internal-ca") && (
+ <Badge variant="info" className="shrink-0 text-xs">
+ CA
+ </Badge>
+ )}
+ </div>
+ </Td>
+ <Td>
+ {cert.notBefore
+ ? new Date(cert.notBefore).toLocaleDateString("en-CA")
+ : "-"}
+ </Td>
+ <Td>
+ {cert.notAfter
+ ? new Date(cert.notAfter).toLocaleDateString("en-CA")
+ : "-"}
+ </Td>
+ </Tr>
+ ));
+ }
- <div className="space-y-4">
- <TableContainer>
- <Table>
- <THead>
- <Tr>
- <Th className="w-1/2">SAN / CN</Th>
- <Th className="w-1/4">Not Before</Th>
- <Th className="w-1/4">Not After</Th>
- </Tr>
- </THead>
- <TBody>
- {(() => {
- if (watchedEventType !== PkiAlertEventTypeV2.EXPIRATION) {
return (
<Tr>
<Td colSpan={3} className="py-8 text-center text-gray-400">
- Preview is only available for Certificate Expiration alerts
+ No certificates currently match this alert&apos;s criteria
</Td>
</Tr>
);
- }
-
- if (isLoadingCurrentCertificates) {
- return Array.from({ length: 5 }, (_, index) => (
- <Tr key={`skeleton-row-${index}`}>
- <Td>
- <Skeleton className="h-4 w-32" />
- </Td>
- <Td>
- <Skeleton className="h-4 w-24" />
- </Td>
- <Td>
- <Skeleton className="h-4 w-24" />
- </Td>
- </Tr>
- ));
- }
-
- if (currentCertificatesData?.certificates?.length) {
- return currentCertificatesData.certificates.map((cert) => (
- <Tr key={cert.id} className="group h-10">
- <Td className="max-w-0">
- <div className="flex items-center gap-2">
- <CertificateDisplayName
- cert={{
- altNames: cert.san?.join(", ") || null,
- commonName: cert.commonName
- }}
- maxLength={48}
- fallback="—"
- />
- {(cert.enrollmentType === "ca" ||
- cert.enrollmentType === "internal-ca") && (
- <Badge variant="info" className="shrink-0 text-xs">
- CA
- </Badge>
- )}
- </div>
- </Td>
- <Td>
- {cert.notBefore
- ? new Date(cert.notBefore).toLocaleDateString("en-CA")
- : "-"}
- </Td>
- <Td>
- {cert.notAfter
- ? new Date(cert.notAfter).toLocaleDateString("en-CA")
- : "-"}
- </Td>
- </Tr>
- ));
- }
-
- return (
- <Tr>
- <Td colSpan={3} className="py-8 text-center text-gray-400">
- No certificates currently match this alert&apos;s criteria
- </Td>
- </Tr>
- );
- })()}
- </TBody>
- </Table>
- </TableContainer>
-
- {(currentCertificatesData?.total || 0) > 0 && (
- <div className="flex justify-center">
- <Pagination
- count={currentCertificatesData?.total || 0}
- page={certificatesPage}
- onChangePage={setCertificatesPage}
- perPage={certificatesPerPage}
- onChangePerPage={() => {}}
- />
- </div>
- )}
+ })()}
+ </TBody>
+ </Table>
+ </TableContainer>
+
+ {(currentCertificatesData?.total || 0) > 0 && (
+ <div className="flex justify-center">
+ <Pagination
+ count={currentCertificatesData?.total || 0}
+ page={certificatesPage}
+ onChangePage={setCertificatesPage}
+ perPage={certificatesPerPage}
+ onChangePerPage={() => {}}
+ />
+ </div>
+ )}
+ </div>
</div>
- </div>
- </Tab.Panel>
+ </Tab.Panel>
+ )}
<Tab.Panel>
<div className="flex min-h-[400px] flex-col gap-6">
diff --git a/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2Modal.tsx b/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2Modal.tsx
index 7e66d9cb8b..c44e521a7b 100644
--- a/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2Modal.tsx
+++ b/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2Modal.tsx
@@ -1,4 +1,4 @@
-import React, { useState } from "react";
+import React, { useEffect, useState } from "react";
import { FieldError, FormProvider, useForm } from "react-hook-form";
import { Tab } from "@headlessui/react";
import { zodResolver } from "@hookform/resolvers/zod";
@@ -35,7 +35,9 @@ interface Props {
type TFormData = TCreatePkiAlertV2;
-const FORM_TABS: { name: string; key: string; fields: (keyof TFormData)[] }[] = [
+type TFormTab = { name: string; key: string; fields: (keyof TFormData)[] };
+
+const TABS_WITH_PREVIEW: TFormTab[] = [
{
name: "Details",
key: "basicInfo",
@@ -47,7 +49,27 @@ const FORM_TABS: { name: string; key: string; fields: (keyof TFormData)[] }[] =
{ name: "Review", key: "review", fields: [] }
];
-const CHANNELS_TAB_INDEX = 3;
+const TABS_WITHOUT_PREVIEW: TFormTab[] = [
+ {
+ name: "Details",
+ key: "basicInfo",
+ fields: ["eventType", "name", "description", "notificationConfig"]
+ },
+ { name: "Filters", key: "filterRules", fields: ["filters"] },
+ { name: "Channels", key: "channels", fields: ["channels"] },
+ { name: "Review", key: "review", fields: [] }
+];
+
+const getFormTabs = (eventType?: PkiAlertEventTypeV2): TFormTab[] => {
+ if (eventType === PkiAlertEventTypeV2.EXPIRATION || !eventType) {
+ return TABS_WITH_PREVIEW;
+ }
+ return TABS_WITHOUT_PREVIEW;
+};
+
+const getChannelsTabIndex = (eventType?: PkiAlertEventTypeV2): number => {
+ return eventType === PkiAlertEventTypeV2.EXPIRATION || !eventType ? 3 : 2;
+};
export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alertId }: Props) => {
const { currentProject } = useProject();
@@ -82,9 +104,20 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
handleSubmit,
trigger,
reset,
+ watch,
formState: { errors }
} = formMethods;
+ const watchedEventType = watch("eventType");
+ const formTabs = getFormTabs(watchedEventType);
+ const channelsTabIndex = getChannelsTabIndex(watchedEventType);
+
+ useEffect(() => {
+ if (selectedTabIndex >= formTabs.length) {
+ setSelectedTabIndex(0);
+ }
+ }, [watchedEventType]); // eslint-disable-line react-hooks/exhaustive-deps
+
const { mutateAsync: createAlert } = useCreatePkiAlertV2();
const { mutateAsync: updateAlert } = useUpdatePkiAlertV2();
@@ -224,9 +257,9 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
setSelectedTabIndex((prev) => prev - 1);
};
- const isStepValid = async (index: number) => trigger(FORM_TABS[index].fields);
+ const isStepValid = async (index: number) => trigger(formTabs[index].fields);
- const isFinalStep = selectedTabIndex === FORM_TABS.length - 1;
+ const isFinalStep = selectedTabIndex === formTabs.length - 1;
// Helper to find first channel with error and expand it
const getFirstChannelErrorIndex = (): number => {
@@ -244,7 +277,7 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
const isValid = await isStepValid(selectedTabIndex);
if (!isValid) {
// If on channels tab and validation failed, expand first channel with error
- if (selectedTabIndex === CHANNELS_TAB_INDEX) {
+ if (selectedTabIndex === channelsTabIndex) {
const firstErrorIdx = getFirstChannelErrorIndex();
if (firstErrorIdx >= 0) {
setExpandedChannel(`channel-${firstErrorIdx}`);
@@ -274,7 +307,8 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
>
<form
className={twMerge(
- "flex min-h-[60vh] flex-col",
+ "flex flex-col",
+ watchedEventType === PkiAlertEventTypeV2.EXPIRATION ? "min-h-[60vh]" : "min-h-[40vh]",
isFinalStep && "max-h-[70vh] overflow-y-auto"
)}
>
@@ -282,7 +316,7 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
<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) => (
+ {formTabs.map((tab, index) => (
<Tab
onClick={async (e) => {
e.preventDefault();
@@ -306,6 +340,7 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
<CreatePkiAlertV2FormSteps
expandedChannel={expandedChannel}
setExpandedChannel={setExpandedChannel}
+ showPreview={watchedEventType === PkiAlertEventTypeV2.EXPIRATION}
/>
</Tab.Panels>
</Tab.Group>