Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(pki): move application alerts to the shared alerting module and block legacy alert writes
Carlos Monastyrskib7e4fa8c624a
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 2ea5fe7129..6fe56994fc 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -678,7 +678,7 @@ See `src/services/health-alert/health-alert-queue.ts` for a minimal example, `sr`src/services/alert/` is **the** alerting module: one `alerts` table, one channel stack (email, Slack, webhook, PagerDuty), one recipient resolver, one encryption story for channel configs, one dedup + history + retention path, one cron tick that fans out into the `AlertDispatch` queue, and one set of routes (`src/server/routes/v1/alert-router.ts`, including `POST /channels/test`).-**Any new "notify someone when X happens" capability belongs here as a provider.** Do not write a per-domain alert service, per-domain channel table, or per-domain notification cron — that path produces N half-featured implementations (only one of which gets PagerDuty, or dedup, or a test button). `src/services/pki-alert-v2/` predates this module and is the thing we are converging away from, not a template to copy.+**Any new "notify someone when X happens" capability belongs here as a provider.** Do not write a per-domain alert service, per-domain channel table, or per-domain notification cron — that path produces N half-featured implementations (only one of which gets PagerDuty, or dedup, or a test button). `src/services/pki-alert-v2/` predates this module and is legacy. New PKI application alerts live here (`cert-manager.application`); existing PKI Alerts V2 rows were not migrated and keep firing, both project-wide and application-scoped, and can still be read and deleted through the deprecated routes. Creating and editing them is refused by `LEGACY_ALERT_WRITES_BLOCKED` (`pki-alert-v2-constants.ts`). Certificate code paths still queue it directly through `pkiAlertV2Queue`, next to the `certificateAlertEventEmitter` call that feeds this module (`emit` inside the certificate transaction, `notify` where there is none). Don't add features to it or copy it.Adding a new alertable resource type:@@ -705,6 +705,8 @@ Invariants worth knowing before extending it:- **The alert module owns no CASL subject.** Each provider reuses its own resource's existing permissions inside `assertPermission`, so authorization stays with the domain that owns the resource.- **New delivery mediums are channel definitions**, not providers: add one under `src/services/alert/channels/` and register it in `ALERT_CHANNEL_REGISTRY`. `directed: true` means the channel addresses principals and needs recipients (email); undirected channels carry their destination in config. `secretFields` drives masking on read and merge-from-stored on update.- **Channel configs are encrypted** with the org/project KMS cipher (`alert-channel-crypto-fns.ts`) — never store or return them in plaintext.+- **One alert per `(scope, resource, event)`**, enforced by `alert_unique_scope_resource_event`. `assertChannelTypesAllowed` is where a provider gates paid channel types on create and on update (new types only). `getResourceNames` (batched) supplies the human-readable name the alert audit events carry next to `resourceId`; without it the name is `null`. `resolveProjectId` lets create, list and test sends omit `projectId` when the resource already belongs to one project (`resolveAlertProjectId` in `alert-types.ts`). `getTelemetryEvent` lets a provider map alert create, update and delete to its own PostHog event, so the shared router never branches on a resource type. The deprecated `pki/alerts` and `applications/:applicationId/alerts` routes only serve legacy PKI Alerts V2 rows. Add features to `/api/v1/alerts`, not to them.+- **Email channels accept plain addresses as `EMAIL` recipients**, with the address as `principalId`, besides users and groups. Every address must be on one of the org's verified email domains, checked on create, update and test sends (`alert-channel-service.ts`). The resolver sends to them directly and skips an address that a user recipient on the same channel already covers.- **`findDueTargets` must return most-urgent-first.** The engine's per-channel `maxTargetsPerRun` cap keeps the head of the list and defers the tail, so ordering is what guarantees the closest-to-expiry targets are never the dropped ones.- **Deleting an alertable resource does NOT delete its alerts. You have to reap them yourself.** `alerts.resourceId` is a plain string column with **no foreign key** to the resource's table (a provider's `resourceType` can point at anything), so nothing cascades. Skip the reap and the row survives as a dangling alert whose `findDueTargets` matches nothing and whose "view" link 404s. Two helpers on `alertService`, and picking the wrong one is the bug:- **`deleteAlertsForDeletedResource({ resourceType, resourceId })`** when the resource **row is gone**. It has **no scope filter** and reaps across every org and project. This is required, not just tidier: the same resource can be watched from another org (a root-org identity invited into a child org), so an `orgId`-filtered reap leaves those rows orphaned.diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 7d0c0e6bc0..6ae64a2503 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -7775,6 +7775,7 @@ interface CreateAlertEvent {name: string;resourceType: string;resourceId?: string | null;+ resourceName?: string | null;eventType: string;};}@@ -7785,6 +7786,8 @@ interface UpdateAlertEvent {alertId: string;name: string;resourceType: string;+ resourceId?: string | null;+ resourceName?: string | null;eventType: string;};}@@ -7795,6 +7798,8 @@ interface DeleteAlertEvent {alertId: string;name: string;resourceType: string;+ resourceId?: string | null;+ resourceName?: string | null;eventType: string;};}diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 393ee4edc5..bb7058a5ab 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -243,6 +243,8 @@ import { alertProviderRegistryFactory } from "@app/services/alert/alert-providerimport { alertQueueServiceFactory } from "@app/services/alert/alert-queue";import { alertRecipientResolverFactory } from "@app/services/alert/alert-recipient-resolver";import { alertServiceFactory } from "@app/services/alert/alert-service";+import { certManagerApplicationAlertDALFactory } from "@app/services/alert/providers/cert-manager-application-alert-dal";+import { certManagerApplicationAlertProviderFactory } from "@app/services/alert/providers/cert-manager-application-alert-provider";import { identityCredentialAlertDALFactory } from "@app/services/alert/providers/identity-credential-alert-dal";import { identityCredentialAlertProviderFactory } from "@app/services/alert/providers/identity-credential-alert-provider";import { announcementServiceFactory } from "@app/services/announcement/announcement-service";@@ -279,6 +281,7 @@ import { tokenServiceFactory } from "@app/services/auth-token/auth-token-serviceimport { certManagerExportServiceFactory } from "@app/services/cert-manager-export/cert-manager-export-service";import { certManagerInstanceServiceFactory } from "@app/services/cert-manager-instance/cert-manager-instance-service";import { certManagerProjectResolverFactory } from "@app/services/cert-manager-instance/cert-manager-project-resolver";+import { certificateAlertEventEmitterFactory } from "@app/services/certificate/certificate-alert-events";import { certificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";import { certificateDALFactory } from "@app/services/certificate/certificate-dal";import { certificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";@@ -1061,6 +1064,7 @@ export const registerRoutes = async (const alertChannelDAL = alertChannelDALFactory(db);const alertChannelMembershipDAL = alertChannelMembershipDALFactory(db);const alertHistoryDAL = alertHistoryDALFactory(db);+ const certManagerApplicationAlertDAL = certManagerApplicationAlertDALFactory(db);const alertProviderRegistry = alertProviderRegistryFactory();alertProviderRegistry.register(identityCredentialAlertProviderFactory({@@ -1068,6 +1072,13 @@ export const registerRoutes = async (permissionService}));+ alertProviderRegistry.register(+ certManagerApplicationAlertProviderFactory({+ certManagerApplicationAlertDAL,+ permissionService,+ licenseService+ })+ );const alertRecipientResolver = alertRecipientResolverFactory({userDAL,userGroupMembershipDAL,@@ -1114,7 +1125,8 @@ export const registerRoutes = async (alertChannelRecipientDAL,orgDAL,projectDAL,- groupDAL+ groupDAL,+ emailDomainDAL});const alertService = alertServiceFactory({alertDAL,@@ -1122,12 +1134,14 @@ export const registerRoutes = async (alertChannelMembershipDAL,alertChannelService,kmsService,- alertProviderRegistry+ alertProviderRegistry,+ alertHistoryDAL});const alertChannelTestService = alertChannelTestServiceFactory({alertChannelDAL,alertDAL,alertRecipientResolver,+ alertChannelService,alertProviderRegistry,kmsService,smtpService,@@ -1813,7 +1827,8 @@ export const registerRoutes = async (approvalPolicyDAL,approvalRequestDAL,pkiSyncDAL,- permissionService+ permissionService,+ alertService});const pkiApplicationMembershipService = pkiApplicationMembershipServiceFactory({@@ -2944,6 +2959,11 @@ export const registerRoutes = async (pkiAlertHistoryDAL});+ const certificateAlertEventEmitter = certificateAlertEventEmitterFactory({+ eventEmitter: eventOutboxService,+ projectDAL+ });+const certificateCleanupService = certificateCleanupServiceFactory({certificateCleanupConfigDAL,permissionService@@ -3593,7 +3613,8 @@ export const registerRoutes = async (licenseService,telemetryService,keyStore,- pkiAlertV2Queue+ pkiAlertV2Queue,+ certificateAlertEventEmitter});const certificateEstService = certificateEstServiceFactory({@@ -3668,6 +3689,7 @@ export const registerRoutes = async (certificateAuthorityService,resourceMetadataDAL,pkiAlertV2Queue,+ certificateAlertEventEmitter,pkiApplicationDAL,certificateProfileDAL,pkiApplicationProfileDAL,@@ -3724,6 +3746,7 @@ export const registerRoutes = async (certificateRequestDAL,resourceMetadataDAL,pkiAlertV2Queue,+ certificateAlertEventEmitter,pkiApplicationProfileDAL,apiEnrollmentConfigDAL,gatewayV2Service,@@ -3753,7 +3776,8 @@ export const registerRoutes = async (pkiApplicationProfileDAL,apiEnrollmentConfigDAL,pkiSyncQueue,- pkiAlertV2Queue+ pkiAlertV2Queue,+ certificateAlertEventEmitter});const approvalPolicyService = approvalPolicyServiceFactory({@@ -3807,6 +3831,7 @@ export const registerRoutes = async (approvalPolicyService,resourceMetadataDAL,pkiAlertV2Queue,+ certificateAlertEventEmitter,pkiApplicationProfileDAL,apiEnrollmentConfigDAL,licenseService,@@ -3831,7 +3856,8 @@ export const registerRoutes = async (digicertFns: digicertCaFns,projectDAL,telemetryService,- pkiAlertV2Queue+ pkiAlertV2Queue,+ certificateAlertEventEmitter});const digicertRevocationSyncQueue = digicertRevocationSyncQueueFactory({@@ -3841,7 +3867,8 @@ export const registerRoutes = async (appConnectionDAL,kmsService,auditLogService,- pkiAlertV2Queue+ pkiAlertV2Queue,+ certificateAlertEventEmitter});const godaddyCaQueue = godaddyCertificateAuthorityQueueServiceFactory({@@ -3855,7 +3882,8 @@ export const registerRoutes = async (godaddyFns: godaddyCaFns,projectDAL,telemetryService,- pkiAlertV2Queue+ pkiAlertV2Queue,+ certificateAlertEventEmitter});const certificateEstV3Service = certificateEstV3ServiceFactory({diff --git a/backend/src/server/routes/v1/alert-router.ts b/backend/src/server/routes/v1/alert-router.tsindex a4ca960e77..fadc63925c 100644--- a/backend/src/server/routes/v1/alert-router.ts+++ b/backend/src/server/routes/v1/alert-router.ts@@ -1,11 +1,15 @@+import { FastifyRequest } from "fastify";import { z } from "zod";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";+import { getTelemetryDistinctId } from "@app/server/lib/telemetry";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AlertChannelType } from "@app/services/alert/alert-channel-types";import {AlertPrincipalType,+ AlertRunStatus,+ AlertTelemetryAction,MAX_CHANNELS_PER_ALERT,MAX_RECIPIENTS_PER_CHANNEL} from "@app/services/alert/alert-types";@@ -13,7 +17,7 @@ import { AuthMode } from "@app/services/auth/auth-type";const ChannelRecipientSchema = z.object({principalType: z.nativeEnum(AlertPrincipalType),- principalId: z.string().min(1)+ principalId: z.string().trim().min(1).max(255)});const CreateChannelInputSchema = z.object({@@ -45,6 +49,7 @@ const AlertResponseSchema = z.object({enabled: z.boolean(),orgId: z.string(),projectId: z.string().nullable(),+ resourceName: z.string().nullable(),channels: z.array(z.object({id: z.string().uuid(),@@ -55,11 +60,26 @@ const AlertResponseSchema = z.object({recipients: z.array(z.object({ principalType: z.string(), principalId: z.string() }))})),+ lastRun: z.object({ timestamp: z.date(), status: z.nativeEnum(AlertRunStatus) }).nullable(),createdAt: z.date(),updatedAt: z.date()});export const registerAlertRouter = async (server: FastifyZodProvider) => {+ const $sendAlertTelemetry = async (+ req: FastifyRequest,+ action: AlertTelemetryAction,+ alert: Parameters<typeof server.services.alert.getTelemetryEvent>[1]+ ) => {+ const telemetryEvent = server.services.alert.getTelemetryEvent(action, alert);+ if (!telemetryEvent) return;+ await server.services.telemetry.sendPostHogEvents({+ ...telemetryEvent,+ distinctId: getTelemetryDistinctId(req),+ organizationId: req.permission.orgId+ });+ };+server.route({method: "POST",url: "/",@@ -99,11 +119,14 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {name: alert.name,resourceType: alert.resourceType,resourceId: alert.resourceId,+ resourceName: alert.resourceName,eventType: alert.eventType}}});+ await $sendAlertTelemetry(req, AlertTelemetryAction.Create, alert);+return { alert };}});@@ -250,11 +273,15 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {alertId: alert.id,name: alert.name,resourceType: alert.resourceType,+ resourceId: alert.resourceId,+ resourceName: alert.resourceName,eventType: alert.eventType}}});+ await $sendAlertTelemetry(req, AlertTelemetryAction.Update, alert);+return { alert };}});@@ -287,11 +314,15 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {alertId: alert.id,name: alert.name,resourceType: alert.resourceType,+ resourceId: alert.resourceId,+ resourceName: alert.resourceName,eventType: alert.eventType}}});+ await $sendAlertTelemetry(req, AlertTelemetryAction.Delete, alert);+return { alert };}});diff --git a/backend/src/server/routes/v1/pki-alert-router.ts b/backend/src/server/routes/v1/pki-alert-router.tsindex 9eee9be8f1..52e2fc85bb 100644--- a/backend/src/server/routes/v1/pki-alert-router.ts+++ b/backend/src/server/routes/v1/pki-alert-router.ts@@ -27,8 +27,10 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),schema: {hide: false,+ deprecated: true,operationId: "createPkiAlertV1",- description: "Create a new PKI alert",+ description:+ "Deprecated: legacy PKI alerts can no longer be created. Use the alerts API (/api/v1/alerts) instead.",tags: [ApiDocsTags.PkiAlerting],body: BasePkiAlertV2Schema.extend({projectId: z.string().uuid().optional().describe(openApiHidden()),@@ -102,8 +104,9 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),schema: {hide: false,+ deprecated: true,operationId: "listPkiAlertsV1",- description: "List PKI alerts for a project",+ description: "Deprecated: application alerts are managed with the alerts API (/api/v1/alerts). List PKI alerts.",tags: [ApiDocsTags.PkiAlerting],querystring: z.object({applicationId: z.string().uuid().optional(),@@ -175,8 +178,10 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),schema: {hide: false,+ deprecated: true,operationId: "getPkiAlertV1",- description: "Get a PKI alert by ID",+ description:+ "Deprecated: application alerts are managed with the alerts API (/api/v1/alerts). Get a PKI alert by ID.",tags: [ApiDocsTags.PkiAlerting],params: z.object({alertId: z.string().uuid().describe("Alert ID")@@ -245,8 +250,10 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),schema: {hide: false,+ deprecated: true,operationId: "updatePkiAlertV1",- description: "Update a PKI alert",+ description:+ "Deprecated: legacy PKI alerts can no longer be edited. Use the alerts API (/api/v1/alerts) instead.",tags: [ApiDocsTags.PkiAlerting],params: z.object({alertId: z.string().uuid().describe("Alert ID")@@ -320,8 +327,10 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),schema: {hide: false,+ deprecated: true,operationId: "deletePkiAlertV1",- description: "Delete a PKI alert",+ description:+ "Deprecated: application alerts are managed with the alerts API (/api/v1/alerts). Delete a PKI alert.",tags: [ApiDocsTags.PkiAlerting],params: z.object({alertId: z.string().uuid().describe("Alert ID")diff --git a/backend/src/server/routes/v1/pki-application-alert-router.ts b/backend/src/server/routes/v1/pki-application-alert-router.tsindex 74e6a801f3..c7da6a5bc6 100644--- a/backend/src/server/routes/v1/pki-application-alert-router.ts+++ b/backend/src/server/routes/v1/pki-application-alert-router.ts@@ -23,8 +23,10 @@ export const registerPkiApplicationAlertRoutes = async (server: FastifyZodProvidconfig: { rateLimit: readLimit },schema: {hide: false,+ deprecated: true,operationId: "listPkiApplicationAlerts",- description: "List alerts for an application.",+ description:+ "Deprecated: application alerts are managed with the alerts API (/api/v1/alerts). List legacy alerts for an application.",tags: [ApiDocsTags.PkiApplications],params: ApplicationIdParamsSchema,querystring: z.object({@@ -67,8 +69,10 @@ export const registerPkiApplicationAlertRoutes = async (server: FastifyZodProvidconfig: { rateLimit: writeLimit },schema: {hide: false,+ deprecated: true,operationId: "createPkiApplicationAlert",- description: "Create an alert on an application.",+ description:+ "Deprecated: legacy application alerts can no longer be created. Use the alerts API (/api/v1/alerts) instead.",tags: [ApiDocsTags.PkiApplications],params: ApplicationIdParamsSchema,body: BasePkiAlertV2Schema,@@ -124,8 +128,10 @@ export const registerPkiApplicationAlertRoutes = async (server: FastifyZodProvidconfig: { rateLimit: writeLimit },schema: {hide: false,+ deprecated: true,operationId: "updatePkiApplicationAlert",- description: "Update an alert on an application.",+ description:+ "Deprecated: legacy application alerts can no longer be edited. Use the alerts API (/api/v1/alerts) instead.",tags: [ApiDocsTags.PkiApplications],params: z.object({applicationId: z.string().uuid(),@@ -183,8 +189,10 @@ export const registerPkiApplicationAlertRoutes = async (server: FastifyZodProvidconfig: { rateLimit: writeLimit },schema: {hide: false,+ deprecated: true,operationId: "deletePkiApplicationAlert",- description: "Delete an alert from an application.",+ description:+ "Deprecated: application alerts are managed with the alerts API (/api/v1/alerts). Delete a legacy alert from an application.",tags: [ApiDocsTags.PkiApplications],params: z.object({applicationId: z.string().uuid(),diff --git a/backend/src/server/routes/v2/pki-alert-router.ts b/backend/src/server/routes/v2/pki-alert-router.tsindex e919057a7c..a9c3ed6ea7 100644--- a/backend/src/server/routes/v2/pki-alert-router.ts+++ b/backend/src/server/routes/v2/pki-alert-router.ts@@ -26,8 +26,10 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),schema: {+ deprecated: true,operationId: "createPkiAlert",- description: "Create a new PKI alert",+ description:+ "Deprecated: legacy PKI alerts can no longer be created. Use the alerts API (/api/v1/alerts) instead.",tags: [ApiDocsTags.PkiAlerting],body: BasePkiAlertV2Schema.extend({projectId: z.string().uuid().optional().describe(openApiHidden()),@@ -98,8 +100,9 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),schema: {+ deprecated: true,operationId: "listPkiAlerts",- description: "List PKI alerts for a project",+ description: "Deprecated: application alerts are managed with the alerts API (/api/v1/alerts). List PKI alerts.",tags: [ApiDocsTags.PkiAlerting],querystring: z.object({projectId: z.string().uuid().optional().describe(openApiHidden()),@@ -171,8 +174,10 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),schema: {+ deprecated: true,operationId: "getPkiAlert",- description: "Get a PKI alert by ID",+ description:+ "Deprecated: application alerts are managed with the alerts API (/api/v1/alerts). Get a PKI alert by ID.",tags: [ApiDocsTags.PkiAlerting],params: z.object({alertId: z.string().uuid().describe("Alert ID")@@ -238,8 +243,10 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),schema: {+ deprecated: true,operationId: "updatePkiAlert",- description: "Update a PKI alert",+ description:+ "Deprecated: legacy PKI alerts can no longer be edited. Use the alerts API (/api/v1/alerts) instead.",tags: [ApiDocsTags.PkiAlerting],params: z.object({alertId: z.string().uuid().describe("Alert ID")@@ -310,8 +317,10 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),schema: {+ deprecated: true,operationId: "deletePkiAlert",- description: "Delete a PKI alert",+ description:+ "Deprecated: application alerts are managed with the alerts API (/api/v1/alerts). Delete a PKI alert.",tags: [ApiDocsTags.PkiAlerting],params: z.object({alertId: z.string().uuid().describe("Alert ID")diff --git a/backend/src/services/alert/alert-channel-service-types.ts b/backend/src/services/alert/alert-channel-service-types.tsindex c6afd36e1c..ef7b072317 100644--- a/backend/src/services/alert/alert-channel-service-types.ts+++ b/backend/src/services/alert/alert-channel-service-types.ts@@ -13,6 +13,8 @@ export type TAlertChannelEmbedded = {enabled: boolean;config: Record<string, unknown>;recipients: { principalType: string; principalId: string }[];+ createdAt: Date;+ updatedAt: Date;};export type TAlertChannelInput = {diff --git a/backend/src/services/alert/alert-channel-service.test.ts b/backend/src/services/alert/alert-channel-service.test.tsindex e467f91e12..3fb4da6ef4 100644--- a/backend/src/services/alert/alert-channel-service.test.ts+++ b/backend/src/services/alert/alert-channel-service.test.ts@@ -84,7 +84,8 @@ const buildService = (opts?: { seed?: TRow[] }) => {effectiveGroupIds: groupIds})},- groupDAL: { find: async (filter: { $in?: { id?: string[] } }) => (filter.$in?.id ?? []).map((id) => ({ id })) }+ groupDAL: { find: async (filter: { $in?: { id?: string[] } }) => (filter.$in?.id ?? []).map((id) => ({ id })) },+ emailDomainDAL: { find: async () => [{ domain: "verified-example.com" }] }} as unknown as TAlertChannelServiceFactoryDep);return { service, store, recipients };@@ -171,6 +172,60 @@ describe("alert channel service", () => {expect(recipients.get(channel.id)).toHaveLength(1);});+ test("collapses email recipients that differ only by case or spacing", async () => {+ const { service, recipients } = buildService();+ const channel = await service.createChannelInTx(+ {+ name: "Team email",+ channelType: AlertChannelType.EMAIL,+ config: {},+ recipients: [+ { principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" },+ { principalType: AlertPrincipalType.EMAIL, principalId: " [email protected] " }+ ],+ orgId: "org-1",+ ...CREATOR+ },+ encryptor as never,+ tx+ );+ expect(recipients.get(channel.id)).toEqual([+ { channelId: channel.id, principalType: "email", principalId: "[email protected]" }+ ]);+ });++ test("rejects an email recipient on an unverified domain", async () => {+ const { service } = buildService();+ await expect(+ service.createChannelInTx(+ {+ name: "Team email",+ channelType: AlertChannelType.EMAIL,+ config: {},+ orgId: "org-1",+ ...CREATOR,+ recipients: [{ principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" }]+ },+ encryptor as never,+ tx+ )+ ).rejects.toThrow("Not on a verified domain: [email protected]");+ });++ test("validates standalone email recipients against the verified domains", async () => {+ const { service } = buildService();+ await expect(+ service.validateEmailRecipients("org-1", [+ { principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" }+ ])+ ).rejects.toThrow("Not on a verified domain: [email protected]");+ await expect(+ service.validateEmailRecipients("org-1", [+ { principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" }+ ])+ ).resolves.toBeUndefined();+ });+test("keeps an omitted secret on update", async () => {const { service, store } = buildService({seed: [diff --git a/backend/src/services/alert/alert-channel-service.ts b/backend/src/services/alert/alert-channel-service.tsindex bd77b6d0de..0acd6815ed 100644--- a/backend/src/services/alert/alert-channel-service.ts+++ b/backend/src/services/alert/alert-channel-service.ts@@ -1,6 +1,9 @@import { Knex } from "knex";+import { z } from "zod";import { TAlertChannels } from "@app/db/schemas";+import { TEmailDomainDALFactory } from "@app/ee/services/email-domain/email-domain-dal";+import { EmailDomainStatus } from "@app/ee/services/email-domain/email-domain-types";import { TGroupDALFactory } from "@app/ee/services/group/group-dal";import { BadRequestError } from "@app/lib/errors";import { TOrgDALFactory } from "@app/services/org/org-dal";@@ -31,6 +34,7 @@ export type TAlertChannelServiceFactoryDep = {orgDAL: Pick<TOrgDALFactory, "findMembership">;projectDAL: Pick<TProjectDALFactory, "findEffectiveProjectSubjectsMembership">;groupDAL: Pick<TGroupDALFactory, "find">;+ emailDomainDAL: Pick<TEmailDomainDALFactory, "find">;};export type TAlertChannelServiceFactory = ReturnType<typeof alertChannelServiceFactory>;@@ -66,14 +70,56 @@ export const alertChannelServiceFactory = ({alertChannelRecipientDAL,orgDAL,projectDAL,- groupDAL+ groupDAL,+ emailDomainDAL}: TAlertChannelServiceFactoryDep) => {+ const $normalizeRecipients = (recipients: TChannelRecipientInput[]): TChannelRecipientInput[] => {+ const seen = new Set<string>();+ return recipients+ .map((recipient) =>+ recipient.principalType === AlertPrincipalType.EMAIL+ ? { ...recipient, principalId: recipient.principalId.trim().toLowerCase() }+ : recipient+ )+ .filter((recipient) => {+ const key = `${recipient.principalType}:${recipient.principalId}`;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+ };++ const $validateEmailRecipients = async (orgId: string, recipients: TChannelRecipientInput[], tx?: Knex) => {+ const emails = [+ ...new Set(recipients.filter((r) => r.principalType === AlertPrincipalType.EMAIL).map((r) => r.principalId))+ ];+ if (!emails.length) return;++ const malformed = emails.filter((email) => !z.string().email().safeParse(email).success);+ if (malformed.length) {+ throw new BadRequestError({ message: `Invalid email recipients: ${malformed.join(", ")}` });+ }++ const verifiedDomains = new Set(+ (await emailDomainDAL.find({ orgId, status: EmailDomainStatus.Verified }, { tx })).map((domain) =>+ domain.domain.toLowerCase()+ )+ );+ const unverified = emails.filter((email) => !verifiedDomains.has(email.split("@")[1]));+ if (unverified.length) {+ throw new BadRequestError({+ message: `Email recipients must use one of your organization's verified domains (Organization Settings > SSO > Email Domains). Not on a verified domain: ${unverified.join(", ")}`+ });+ }+ };+// Confirms every recipient principal (user/group) actually belongs to the channel's scope so an// alert can't be made to notify a foreign principal.const $validateRecipients = async (orgId: string,projectId: string | null | undefined,- recipients: TChannelRecipientInput[]+ recipients: TChannelRecipientInput[],+ tx?: Knex) => {const userIds = [...new Set(recipients.filter((r) => r.principalType === AlertPrincipalType.USER).map((r) => r.principalId))@@ -85,7 +131,8 @@ export const alertChannelServiceFactory = ({const inScope = await resolvePrincipalsInScope({ orgDAL, projectDAL, groupDAL },- { orgId, projectId, userIds, groupIds }+ { orgId, projectId, userIds, groupIds },+ tx);const scopeLabel = projectId ? "project" : "organization";@@ -136,10 +183,11 @@ export const alertChannelServiceFactory = ({tx: Knex): Promise<TAlertChannels> => {const definition = getChannelDefinition(input.channelType);- const recipients = input.recipients ?? [];+ const recipients = $normalizeRecipients(input.recipients ?? []);$assertRecipientRules(definition, input.channelType, recipients);assertChannelConfigValid(definition, input.channelType, input.config);- await $validateRecipients(input.orgId, input.projectId, recipients);+ await $validateRecipients(input.orgId, input.projectId, recipients, tx);+ await $validateEmailRecipients(input.orgId, recipients, tx);const created = await alertChannelDAL.create({@@ -186,9 +234,11 @@ export const alertChannelServiceFactory = ({finalConfig = merged;}- if (input.recipients !== undefined) {- $assertRecipientRules(definition, channel.channelType, input.recipients);- await $validateRecipients(channel.orgId, channel.projectId, input.recipients);+ const recipients = input.recipients === undefined ? undefined : $normalizeRecipients(input.recipients);+ if (recipients !== undefined) {+ $assertRecipientRules(definition, channel.channelType, recipients);+ await $validateRecipients(channel.orgId, channel.projectId, recipients, tx);+ await $validateEmailRecipients(channel.orgId, recipients, tx);}await alertChannelDAL.updateById(@@ -201,11 +251,11 @@ export const alertChannelServiceFactory = ({tx);- if (input.recipients !== undefined) {+ if (recipients !== undefined) {await alertChannelRecipientDAL.deleteByChannelId(channel.id, tx);- if (input.recipients.length) {+ if (recipients.length) {await alertChannelRecipientDAL.insertMany(- input.recipients.map((r) => ({+ recipients.map((r) => ({channelId: channel.id,principalType: r.principalType,principalId: r.principalId@@ -216,6 +266,9 @@ export const alertChannelServiceFactory = ({}};+ const validateEmailRecipients = (orgId: string, recipients: TChannelRecipientInput[]) =>+ $validateEmailRecipients(orgId, $normalizeRecipients(recipients));+const deleteChannelInTx = async (channelId: string, tx: Knex): Promise<void> => {await alertChannelDAL.deleteById(channelId, tx);};@@ -246,7 +299,9 @@ export const alertChannelServiceFactory = ({channelType: channel.channelType,enabled: channel.enabled,config: $redactConfig(channel.channelType, config),- recipients: recipientsByChannel.get(channel.id) ?? []+ recipients: recipientsByChannel.get(channel.id) ?? [],+ createdAt: channel.createdAt,+ updatedAt: channel.updatedAt};});};@@ -255,6 +310,7 @@ export const alertChannelServiceFactory = ({createChannelInTx,updateChannelInTx,deleteChannelInTx,- getDetailsForChannels+ getDetailsForChannels,+ validateEmailRecipients};};diff --git a/backend/src/services/alert/alert-channel-test-service.test.ts b/backend/src/services/alert/alert-channel-test-service.test.tsindex b2a13ab0ee..276189c822 100644--- a/backend/src/services/alert/alert-channel-test-service.test.ts+++ b/backend/src/services/alert/alert-channel-test-service.test.ts@@ -29,7 +29,10 @@ const actor = {actorOrgId: ORG_ID} as unknown as { actor: never; actorId: string; actorAuthMethod: never; actorOrgId: string };-const buildProvider = (opts?: { assertPermission?: (input: TAlertPermissionInput) => Promise<void> }) => {+const buildProvider = (opts?: {+ assertPermission?: (input: TAlertPermissionInput) => Promise<void>;+ resolvedProjectId?: string;+}) => {const provider: IResourceAlertProvider = {resourceType: RESOURCE_TYPE,events: [@@ -57,7 +60,8 @@ const buildProvider = (opts?: { assertPermission?: (input: TAlertPermissionInputassertPermission: async (input) => {if (opts?.assertPermission) await opts.assertPermission(input);},- assertResourceInScope: async () => {}+ assertResourceInScope: async () => {},+ ...(opts?.resolvedProjectId ? { resolveProjectId: async () => opts.resolvedProjectId as string } : {})};const registry = alertProviderRegistryFactory();@@ -108,6 +112,9 @@ const buildDeps = (overrides?: {resolveMany: async (rowsByChannel: Map<string, unknown[]>) =>new Map([...rowsByChannel.keys()].map((channelId) => [channelId, overrides?.recipients ?? []]))},+ alertChannelService: {+ validateEmailRecipients: async () => {}+ },alertProviderRegistry: overrides?.registry ?? buildProvider(),kmsService: {createCipherPairWithDataKey: async () => ({@@ -164,6 +171,35 @@ describe("alertChannelTestService", () => {}});+ test("resolves the project from the resource when projectId is omitted", async () => {+ const permissionInputs: TAlertPermissionInput[] = [];+ const restore = stubSend("slack", async () => ({ success: true }));++ try {+ const { deps } = buildDeps({+ registry: buildProvider({+ resolvedProjectId: "proj-resolved",+ assertPermission: async (input) => {+ permissionInputs.push(input);+ }+ })+ });+ const service = alertChannelTestServiceFactory(deps);++ await service.testChannel({+ ...actor,+ resourceType: RESOURCE_TYPE,+ resourceId: "resource-1",+ channelType: "slack" as never,+ config: { webhookUrl: "https://hooks.slack.com/services/T/B/x" }+ });++ expect(permissionInputs[0]?.projectId).toBe("proj-resolved");+ } finally {+ restore();+ }+ });+test("falls back to the stored secret when the config omits it", async () => {const sent: TAlertChannelSendContext[] = [];const restore = stubSend("slack", async (ctx) => {diff --git a/backend/src/services/alert/alert-channel-test-service.ts b/backend/src/services/alert/alert-channel-test-service.tsindex dc5286dff0..efe307f894 100644--- a/backend/src/services/alert/alert-channel-test-service.ts+++ b/backend/src/services/alert/alert-channel-test-service.ts@@ -11,18 +11,20 @@ import {} from "./alert-channel-config-fns";import { decryptChannelConfig, getAlertChannelCipher } from "./alert-channel-crypto-fns";import { TAlertChannelDALFactory } from "./alert-channel-dal";+import { TAlertChannelServiceFactory } from "./alert-channel-service";import { TAlertChannelDeps, TAlertRecipient } from "./alert-channel-types";import { TAlertDALFactory } from "./alert-dal";import { TAlertProviderRegistry } from "./alert-provider-registry";import { TAlertRecipientResolver } from "./alert-recipient-resolver";import { TTestAlertChannelDTO, TTestAlertChannelResponse } from "./alert-service-types";import { buildTestAlertPayload } from "./alert-test-payload-fns";-import { AlertPermissionAction, toAlertActor } from "./alert-types";+import { AlertPermissionAction, resolveAlertProjectId, toAlertActor } from "./alert-types";export type TAlertChannelTestServiceFactoryDep = {alertChannelDAL: Pick<TAlertChannelDALFactory, "findById">;alertDAL: Pick<TAlertDALFactory, "findByChannelId">;alertRecipientResolver: Pick<TAlertRecipientResolver, "resolveMany">;+ alertChannelService: Pick<TAlertChannelServiceFactory, "validateEmailRecipients">;alertProviderRegistry: TAlertProviderRegistry;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;smtpService: Pick<TSmtpService, "sendMail">;@@ -39,6 +41,7 @@ export const alertChannelTestServiceFactory = ({alertChannelDAL,alertDAL,alertRecipientResolver,+ alertChannelService,alertProviderRegistry,kmsService,smtpService,@@ -124,6 +127,8 @@ export const alertChannelTestServiceFactory = ({const rows = dto.recipients ?? [];if (rows.length === 0) return [];+ await alertChannelService.validateEmailRecipients(dto.actorOrgId, rows);+const resolved = await alertRecipientResolver.resolveMany(new Map([[TEST_CHANNEL_ID, rows]]), {orgId: dto.actorOrgId,projectId@@ -146,7 +151,11 @@ export const alertChannelTestServiceFactory = ({});}- const projectId = dto.projectId ?? null;+ const projectId = await resolveAlertProjectId(provider, {+ orgId: dto.actorOrgId,+ projectId: dto.projectId,+ resourceId: dto.resourceId+ });await provider.assertPermission({action: AlertPermissionAction.Create,diff --git a/backend/src/services/alert/alert-channel-types.ts b/backend/src/services/alert/alert-channel-types.tsindex 31801a2e88..a96df65437 100644--- a/backend/src/services/alert/alert-channel-types.ts+++ b/backend/src/services/alert/alert-channel-types.ts@@ -24,6 +24,8 @@ export type TAlertItem = {title: string; // primary label (e.g. certificate common name, client-secret description)identifier?: string; // secondary label (e.g. serial number, client-secret id)fields?: Array<{ label: string; value: string }>; // extra display key-values (expiry date, days left, reason)+ summary?: string;+ severity?: TAlertSeverity;};export type TAlertPayload = {diff --git a/backend/src/services/alert/alert-format-fns.ts b/backend/src/services/alert/alert-format-fns.tsnew file mode 100644index 0000000000..c58b893db7--- /dev/null+++ b/backend/src/services/alert/alert-format-fns.ts@@ -0,0 +1,35 @@+import RE2 from "re2";++import { TAlertSeverity } from "./alert-channel-types";++const durationRegex = new RE2("^(\\d+)([dwmy])$");+const DAYS_PER_DURATION_UNIT: Record<string, number> = { d: 1, w: 7, m: 30, y: 365 };++export const daysUntil = (date: Date): number =>+ Math.ceil((new Date(date).getTime() - Date.now()) / (1000 * 60 * 60 * 24));++export const durationToDays = (duration: string): number => {+ const match = durationRegex.exec(duration);+ return match ? parseInt(match[1], 10) * DAYS_PER_DURATION_UNIT[match[2]] : Number.NaN;+};++export const humanizeDays = (days: number): string => `${days} day${days === 1 ? "" : "s"}`;++export const formatUtcDate = (date: Date): string =>+ new Date(date).toLocaleString("en-US", {+ year: "numeric",+ month: "long",+ day: "numeric",+ hour: "2-digit",+ minute: "2-digit",+ timeZone: "UTC",+ timeZoneName: "short"+ });++export const expirySeverity = (expiryDates: Date[]): TAlertSeverity => {+ const minDays = Math.min(...expiryDates.map(daysUntil));+ if (minDays <= 7) return "critical";+ if (minDays <= 14) return "error";+ if (minDays <= 30) return "warning";+ return "info";+};diff --git a/backend/src/services/alert/alert-history-dal.ts b/backend/src/services/alert/alert-history-dal.tsindex 6f6bc16659..d7c528bb75 100644--- a/backend/src/services/alert/alert-history-dal.ts+++ b/backend/src/services/alert/alert-history-dal.ts@@ -102,6 +102,25 @@ export const alertHistoryDALFactory = (db: TDbClient) => {}};+ const findLatestByAlertIds = async (+ alertIds: string[]+ ): Promise<Pick<TAlertHistory, "alertId" | "triggeredAt" | "status">[]> => {+ if (alertIds.length === 0) return [];+ try {+ return (await db+ .replicaNode()(TableName.AlertHistory)+ .whereIn("alertId", alertIds)+ .distinctOn("alertId")+ .select("alertId", "triggeredAt", "status")+ .orderBy([{ column: "alertId" }, { column: "triggeredAt", order: "desc" }])) as Pick<+ TAlertHistory,+ "alertId" | "triggeredAt" | "status"+ >[];+ } catch (error) {+ throw new DatabaseError({ error, name: "FindLatestByAlertIds" });+ }+ };+const deleteExpiredHistory = async ({before,batchSize = ALERT_HISTORY_PRUNE_BATCH_SIZE,@@ -146,6 +165,7 @@ export const alertHistoryDALFactory = (db: TDbClient) => {createWithTargets,findRecentlyAlertedTargets,findDeliveredChannelIdsForEvent,+ findLatestByAlertIds,deleteExpiredHistory};};diff --git a/backend/src/services/alert/alert-principal-scope-fns.ts b/backend/src/services/alert/alert-principal-scope-fns.tsindex 23bec67036..1e58683241 100644--- a/backend/src/services/alert/alert-principal-scope-fns.ts+++ b/backend/src/services/alert/alert-principal-scope-fns.ts@@ -1,3 +1,5 @@+import { Knex } from "knex";+import { OrgMembershipStatus } from "@app/db/schemas";import { TGroupDALFactory } from "@app/ee/services/group/group-dal";import { TOrgDALFactory } from "@app/services/org/org-dal";@@ -30,18 +32,22 @@ export type TInScopePrincipals = { userIds: Set<string>; groupIds: Set<string> }*/export const resolvePrincipalsInScope = async ({ orgDAL, projectDAL, groupDAL }: TPrincipalScopeDALs,- { orgId, projectId, userIds, groupIds }: TPrincipalScope & { userIds: string[]; groupIds: string[] }+ { orgId, projectId, userIds, groupIds }: TPrincipalScope & { userIds: string[]; groupIds: string[] },+ tx?: Knex): Promise<TInScopePrincipals> => {if (userIds.length === 0 && groupIds.length === 0) return { userIds: new Set(), groupIds: new Set() };const activeOrgUserIds = new Set<string>();if (userIds.length) {- const memberships = await orgDAL.findMembership({- $in: { actorUserId: userIds },- scopeOrgId: orgId,- isActive: true,- status: OrgMembershipStatus.Accepted- });+ const memberships = await orgDAL.findMembership(+ {+ $in: { actorUserId: userIds },+ scopeOrgId: orgId,+ isActive: true,+ status: OrgMembershipStatus.Accepted+ },+ { tx }+ );memberships.forEach((membership) => {if (membership.actorUserId) activeOrgUserIds.add(membership.actorUserId);});@@ -52,7 +58,8 @@ export const resolvePrincipalsInScope = async (orgId,projectId,userIds: [...activeOrgUserIds],- groupIds+ groupIds,+ tx});return { userIds: new Set(effectiveUserIds), groupIds: new Set(effectiveGroupIds) };}@@ -61,6 +68,6 @@ export const resolvePrincipalsInScope = async (if (!groupDAL || groupIds.length === 0) return { userIds: inScopeUserIds, groupIds: new Set(groupIds) };- const orgGroups = await groupDAL.find({ $in: { id: groupIds }, orgId });+ const orgGroups = await groupDAL.find({ $in: { id: groupIds }, orgId }, { tx });return { userIds: inScopeUserIds, groupIds: new Set(orgGroups.map((group) => group.id)) };};diff --git a/backend/src/services/alert/alert-recipient-resolver.ts b/backend/src/services/alert/alert-recipient-resolver.tsindex 89b0031dff..6cc01b1e89 100644--- a/backend/src/services/alert/alert-recipient-resolver.ts+++ b/backend/src/services/alert/alert-recipient-resolver.ts@@ -64,6 +64,7 @@ export const alertRecipientResolverFactory = ({const result = new Map<string, TAlertRecipient[]>();for (const [channelId, rows] of rowsByChannel.entries()) {const userIds = new Set<string>();+ const emails = new Set<string>();for (const recipient of rows) {switch (recipient.principalType) {@@ -75,6 +76,9 @@ export const alertRecipientResolverFactory = ({(groupMembers.get(recipient.principalId) ?? []).forEach((userId) => userIds.add(userId));}break;+ case AlertPrincipalType.EMAIL:+ emails.add(recipient.principalId.toLowerCase());+ break;default:logger.warn(`Unknown alert recipient principal type '${recipient.principalType}'`);}@@ -88,6 +92,10 @@ export const alertRecipientResolverFactory = ({resolved.push({ userId: user.id, email: user.email, firstName: user.firstName });}});+ const userEmails = new Set(resolved.map((recipient) => recipient.email.toLowerCase()));+ emails.forEach((email) => {+ if (!userEmails.has(email)) resolved.push({ email });+ });result.set(channelId, resolved);}diff --git a/backend/src/services/alert/alert-service-types.ts b/backend/src/services/alert/alert-service-types.tsindex 154288c471..acc1f55c5c 100644--- a/backend/src/services/alert/alert-service-types.ts+++ b/backend/src/services/alert/alert-service-types.ts@@ -2,6 +2,7 @@ import { TGenericPermission } from "@app/lib/types";import { TAlertChannelEmbedded, TAlertChannelInput, TChannelRecipientInput } from "./alert-channel-service-types";import { AlertChannelType } from "./alert-channel-types";+import { AlertRunStatus } from "./alert-types";export type TCreateAlertDTO = TGenericPermission & {name: string;@@ -65,7 +66,14 @@ export type TAlertResponse = {enabled: boolean;orgId: string;projectId: string | null;+ resourceName: string | null;channels: TAlertChannelEmbedded[];+ lastRun: TAlertLastRun | null;createdAt: Date;updatedAt: Date;};++export type TAlertLastRun = {+ timestamp: Date;+ status: AlertRunStatus;+};diff --git a/backend/src/services/alert/alert-service.test.ts b/backend/src/services/alert/alert-service.test.tsindex e73d72a16c..864dfa06a1 100644--- a/backend/src/services/alert/alert-service.test.ts+++ b/backend/src/services/alert/alert-service.test.ts@@ -1,5 +1,7 @@import { z } from "zod";+import { ForbiddenRequestError } from "@app/lib/errors";+import { TAlertChannelInput } from "./alert-channel-service-types";import { AlertChannelType, TAlertPayload } from "./alert-channel-types";import { alertProviderRegistryFactory } from "./alert-provider-registry";@@ -24,11 +26,13 @@ const buildService = (opts?: {assertPermission?: (input: TAlertPermissionInput) => Promise<void>;resourceScopeThrows?: boolean;duplicateExists?: boolean;+ resolvedProjectId?: string;// Runs right after a find() has taken its snapshot, to stand in for a concurrent transaction// committing between two statements of ours.afterFindAlerts?: (alerts: Map<string, Record<string, unknown>>) => void;}) => {const permissionCalls: TAlertPermissionInput[] = [];+ const gatedChannelTypeCalls: string[][] = [];const provider: IResourceAlertProvider = {resourceType: RESOURCE_TYPE,events: [@@ -54,7 +58,11 @@ const buildService = (opts?: {},assertResourceInScope: async (input) => {if (input.resourceId && opts?.resourceScopeThrows) throw new Error("resource out of scope");- }+ },+ assertChannelTypesAllowed: async ({ channelTypes }) => {+ gatedChannelTypeCalls.push(channelTypes);+ },+ ...(opts?.resolvedProjectId ? { resolveProjectId: async () => opts.resolvedProjectId as string } : {})};const registry = alertProviderRegistryFactory();registry.register(provider);@@ -75,6 +83,7 @@ const buildService = (opts?: {};const service = alertServiceFactory({+ alertHistoryDAL: { findLatestByAlertIds: async () => [] },alertDAL: {transaction: async (cb: (tx: unknown) => unknown) => cb({}),create: async (data: Record<string, unknown>) => {@@ -210,7 +219,7 @@ const buildService = (opts?: {alertProviderRegistry: registry} as unknown as TAlertServiceFactoryDep);- return { service, permissionCalls, alerts, memberships, channels, findFilters };+ return { service, permissionCalls, gatedChannelTypeCalls, alerts, memberships, channels, findFilters };};const actor = {@@ -380,6 +389,17 @@ describe("alert service", () => {expect(findFilters[0]).toMatchObject({ projectId: null });});+ test("create and list resolve the project from the resource when projectId is omitted", async () => {+ const { service, permissionCalls, findFilters } = buildService({ resolvedProjectId: "proj-resolved" });++ const created = await service.createAlert(validCreate);+ expect(created.projectId).toBe("proj-resolved");++ await service.listAlerts({ resourceType: RESOURCE_TYPE, resourceId: "resource-1", ...actor });+ expect(findFilters.at(-1)).toMatchObject({ projectId: "proj-resolved" });+ expect(permissionCalls.every((call) => call.projectId === "proj-resolved")).toBe(true);+ });+test("project-scoped list filters to the requested project", async () => {const { service, alerts, findFilters } = buildService();alerts.set("org-alert", { id: "org-alert", name: "org", projectId: null, ...listBase });@@ -391,6 +411,33 @@ describe("alert service", () => {expect(findFilters[0]).toMatchObject({ projectId: "proj-x" });});+ test("a list without a resource hides alerts on resources the actor cannot read", async () => {+ const { service, alerts } = buildService({+ assertPermission: async (input) => {+ if (input.resourceId === "hidden-resource") throw new ForbiddenRequestError({ message: "forbidden" });+ }+ });+ alerts.set("unbound", { id: "unbound", name: "unbound", projectId: "proj-x", ...listBase });+ alerts.set("visible", {+ id: "visible",+ name: "visible",+ projectId: "proj-x",+ ...listBase,+ resourceId: "visible-resource"+ });+ alerts.set("hidden", {+ id: "hidden",+ name: "hidden",+ projectId: "proj-x",+ ...listBase,+ resourceId: "hidden-resource"+ });++ const result = await service.listAlerts({ resourceType: RESOURCE_TYPE, projectId: "proj-x", ...actor });++ expect(result.map((a) => a.id).sort()).toEqual(["unbound", "visible"]);+ });+test("update reconciles channels: keeps the referenced ones, deletes the rest, adds new", async () => {const { service, memberships } = buildService();const created = await service.createAlert(validCreate);@@ -414,6 +461,40 @@ describe("alert service", () => {expect(memberships.get("alert-1")).toHaveLength(2);});+ test("update gates every new channel, even when the alert already has one of that type", async () => {+ const { service, gatedChannelTypeCalls } = buildService();+ const created = await service.createAlert(validCreate);+ const existingWebhook = created.channels.find((c) => c.channelType === AlertChannelType.WEBHOOK)!;++ await service.updateAlert({+ alertId: "alert-1",+ channels: [+ { id: existingWebhook.id, name: existingWebhook.name, channelType: AlertChannelType.WEBHOOK },+ { name: "second-webhook", channelType: AlertChannelType.WEBHOOK, config: { url: "https://example.com/2" } }+ ],+ ...actor+ });++ expect(gatedChannelTypeCalls.at(-1)).toEqual([AlertChannelType.WEBHOOK]);+ });++ test("update does not gate channels the alert already has", async () => {+ const { service, gatedChannelTypeCalls } = buildService();+ const created = await service.createAlert(validCreate);++ await service.updateAlert({+ alertId: "alert-1",+ channels: created.channels.map((c) => ({+ id: c.id,+ name: c.name,+ channelType: c.channelType as AlertChannelType+ })),+ ...actor+ });++ expect(gatedChannelTypeCalls.at(-1)).toEqual([]);+ });+test("update rejects a channel id that does not belong to the alert", async () => {const { service } = buildService();await service.createAlert(validCreate);diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.tsindex 4a3225935f..7a1bacfd91 100644--- a/backend/src/services/alert/alert-service.ts+++ b/backend/src/services/alert/alert-service.ts@@ -1,8 +1,9 @@+import { ForbiddenError } from "@casl/ability";import { Knex } from "knex";import { z } from "zod";import { TAlertChannels, TAlerts } from "@app/db/schemas";-import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { TGenericPermission } from "@app/lib/types";import { TKmsServiceFactory } from "@app/services/kms/kms-service";@@ -12,8 +13,10 @@ import { TAlertChannelMembershipDALFactory } from "./alert-channel-membership-daimport { TAlertChannelServiceFactory } from "./alert-channel-service";import { TAlertChannelEmbedded, TAlertChannelInput } from "./alert-channel-service-types";import { TAlertDALFactory } from "./alert-dal";+import { TAlertHistoryDALFactory } from "./alert-history-dal";import { TAlertProviderRegistry } from "./alert-provider-registry";import {+ TAlertLastRun,TAlertResponse,TCreateAlertDTO,TDeleteAlertDTO,@@ -21,7 +24,15 @@ import {TListAlertsDTO,TUpdateAlertDTO} from "./alert-service-types";-import { AlertPermissionAction, IResourceAlertProvider, TAlertEventDefinition, toAlertActor } from "./alert-types";+import {+ AlertPermissionAction,+ AlertRunStatus,+ AlertTelemetryAction,+ IResourceAlertProvider,+ resolveAlertProjectId,+ TAlertEventDefinition,+ toAlertActor+} from "./alert-types";export type TAlertServiceFactoryDep = {alertDAL: TAlertDALFactory;@@ -33,6 +44,7 @@ export type TAlertServiceFactoryDep = {>;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;alertProviderRegistry: TAlertProviderRegistry;+ alertHistoryDAL: Pick<TAlertHistoryDALFactory, "findLatestByAlertIds">;};export type TAlertServiceFactory = ReturnType<typeof alertServiceFactory>;@@ -43,7 +55,8 @@ export const alertServiceFactory = ({alertChannelMembershipDAL,alertChannelService,kmsService,- alertProviderRegistry+ alertProviderRegistry,+ alertHistoryDAL}: TAlertServiceFactoryDep) => {const $getProvider = (resourceType: string): IResourceAlertProvider => {const provider = alertProviderRegistry.get(resourceType);@@ -67,6 +80,53 @@ export const alertServiceFactory = ({actor: toAlertActor(dto)});+ const $isAllowed = async (+ provider: IResourceAlertProvider,+ action: AlertPermissionAction,+ scope: { orgId: string; projectId?: string | null; resourceId?: string | null },+ dto: TGenericPermission+ ) => {+ try {+ await $assertAlertPermission(provider, action, scope, dto);+ return true;+ } catch (error) {+ if (error instanceof ForbiddenError || error instanceof ForbiddenRequestError) return false;+ throw error;+ }+ };++ const $findAllowedResourceIds = async (+ provider: IResourceAlertProvider,+ action: AlertPermissionAction,+ resourceIds: (string | null)[],+ projectId: string | null,+ dto: TListAlertsDTO+ ) => {+ const allowed = await Promise.all(+ resourceIds.map((resourceId) =>+ $isAllowed(provider, action, { orgId: dto.actorOrgId, projectId, resourceId }, dto)+ )+ );+ return new Set(resourceIds.filter((_, index) => allowed[index]));+ };++ const $filterReadableAlerts = async (+ provider: IResourceAlertProvider,+ alerts: TAlerts[],+ projectId: string | null,+ dto: TListAlertsDTO+ ) => {+ const resourceIds = [...new Set(alerts.map((alert) => alert.resourceId).filter((id): id is string => Boolean(id)))];+ const readableResourceIds = await $findAllowedResourceIds(+ provider,+ AlertPermissionAction.Read,+ resourceIds,+ projectId,+ dto+ );+ return alerts.filter((alert) => !alert.resourceId || readableResourceIds.has(alert.resourceId));+ };+const $getEvent = (provider: IResourceAlertProvider, eventType: string): TAlertEventDefinition => {const event = provider.events.find((candidate) => candidate.key === eventType);if (!event) {@@ -86,7 +146,33 @@ export const alertServiceFactory = ({}};- const $assembleResponse = (alert: TAlerts, channels: TAlertChannelEmbedded[]): TAlertResponse => ({+ const $getResourceNames = async (+ provider: IResourceAlertProvider,+ orgId: string,+ resourceIds: (string | null | undefined)[]+ ): Promise<Map<string, string>> => {+ const ids = [...new Set(resourceIds.filter((id): id is string => Boolean(id)))];+ if (!ids.length || !provider.getResourceNames) return new Map();+ return provider.getResourceNames({ orgId, resourceIds: ids });+ };++ const $getResourceName = async (provider: IResourceAlertProvider, alert: Pick<TAlerts, "orgId" | "resourceId">) =>+ (await $getResourceNames(provider, alert.orgId, [alert.resourceId])).get(alert.resourceId ?? "") ?? null;++ const $getLastRuns = async (alertIds: string[]): Promise<Map<string, TAlertLastRun>> => {+ const runs = await alertHistoryDAL.findLatestByAlertIds(alertIds);+ return new Map(+ runs+ .filter((run) => run.triggeredAt)+ .map((run) => [run.alertId, { timestamp: run.triggeredAt as Date, status: run.status as AlertRunStatus }])+ );+ };++ const $assembleResponse = (+ alert: TAlerts,+ channels: TAlertChannelEmbedded[],+ extras: { resourceName: string | null; lastRun: TAlertLastRun | null }+ ): TAlertResponse => ({id: alert.id,name: alert.name,description: alert.description ?? null,@@ -98,7 +184,9 @@ export const alertServiceFactory = ({enabled: alert.enabled,orgId: alert.orgId,projectId: alert.projectId ?? null,+ resourceName: extras.resourceName,channels,+ lastRun: extras.lastRun,createdAt: alert.createdAt,updatedAt: alert.updatedAt});@@ -112,25 +200,31 @@ export const alertServiceFactory = ({}const provider = $getProvider(dto.resourceType);+ const projectId = await resolveAlertProjectId(provider, {+ orgId: dto.actorOrgId,+ projectId: dto.projectId,+ resourceId: dto.resourceId+ });+const event = $getEvent(provider, dto.eventType);$validateCondition(event, dto.condition);await $assertAlertPermission(provider,AlertPermissionAction.Create,- { orgId: dto.actorOrgId, projectId: dto.projectId, resourceId: dto.resourceId },+ { orgId: dto.actorOrgId, projectId, resourceId: dto.resourceId },dto);await provider.assertResourceInScope({orgId: dto.actorOrgId,- projectId: dto.projectId,+ projectId,resourceId: dto.resourceId});const duplicate = await alertDAL.findScopedDuplicate({orgId: dto.actorOrgId,- projectId: dto.projectId,+ projectId,resourceType: dto.resourceType,resourceId: dto.resourceId,eventType: dto.eventType@@ -147,7 +241,12 @@ export const alertServiceFactory = ({throw new BadRequestError({ message: "At least one channel is required" });}- const scope = { orgId: dto.actorOrgId, projectId: dto.projectId ?? null };+ await provider.assertChannelTypesAllowed?.({+ orgId: dto.actorOrgId,+ channelTypes: dto.channels.map((channel) => channel.channelType)+ });++ const scope = { orgId: dto.actorOrgId, projectId: projectId ?? null };const cipher = await getAlertChannelCipher(kmsService, scope);const { created, channels } = await alertDAL.transaction(async (tx) => {@@ -162,7 +261,7 @@ export const alertServiceFactory = ({condition: dto.condition != null ? JSON.stringify(dto.condition) : null,enabled: dto.enabled ?? true,orgId: dto.actorOrgId,- projectId: dto.projectId,+ projectId,createdByActorId: dto.actorId,createdByActorType: dto.actor},@@ -179,7 +278,7 @@ export const alertServiceFactory = ({enabled: channelInput.enabled,recipients: channelInput.recipients,orgId: dto.actorOrgId,- projectId: dto.projectId ?? null,+ projectId: projectId ?? null,createdByActorId: dto.actorId,createdByActorType: dto.actor},@@ -195,7 +294,10 @@ export const alertServiceFactory = ({return { created: createdAlert, channels: details };});- return $assembleResponse(created, channels);+ return $assembleResponse(created, channels, {+ resourceName: await $getResourceName(provider, created),+ lastRun: null+ });};const getAlertById = async (dto: TGetAlertDTO): Promise<TAlertResponse> => {@@ -213,31 +315,49 @@ export const alertServiceFactory = ({const channels = await alertChannelDAL.findByAlertId(alert.id);const cipher = await getAlertChannelCipher(kmsService, { orgId: alert.orgId, projectId: alert.projectId });const details = await alertChannelService.getDetailsForChannels(channels, cipher);- return $assembleResponse(alert, details);+ const lastRuns = await $getLastRuns([alert.id]);+ return $assembleResponse(alert, details, {+ resourceName: await $getResourceName(provider, alert),+ lastRun: lastRuns.get(alert.id) ?? null+ });};const listAlerts = async (dto: TListAlertsDTO): Promise<TAlertResponse[]> => {const provider = $getProvider(dto.resourceType);+ const projectId = await resolveAlertProjectId(provider, {+ orgId: dto.actorOrgId,+ projectId: dto.projectId,+ resourceId: dto.resourceId+ });await $assertAlertPermission(provider,AlertPermissionAction.Read,- { orgId: dto.actorOrgId, projectId: dto.projectId, resourceId: dto.resourceId },+ { orgId: dto.actorOrgId, projectId, resourceId: dto.resourceId },dto);- const alerts = await alertDAL.findActiveByScope({+ const scopedAlerts = await alertDAL.findActiveByScope({orgId: dto.actorOrgId,resourceType: dto.resourceType,...(dto.resourceId !== undefined ? { resourceId: dto.resourceId } : {}),- projectId: dto.projectId ?? null,+ projectId,...(dto.enabled !== undefined ? { enabled: dto.enabled } : {})});+ const alerts =+ dto.resourceId !== undefined ? scopedAlerts : await $filterReadableAlerts(provider, scopedAlerts, projectId, dto);if (alerts.length === 0) return [];const channels = await alertChannelDAL.findByAlertIds(alerts.map((alert) => alert.id));- const cipher = await getAlertChannelCipher(kmsService, { orgId: dto.actorOrgId, projectId: dto.projectId ?? null });+ const cipher = await getAlertChannelCipher(kmsService, { orgId: dto.actorOrgId, projectId });const details = await alertChannelService.getDetailsForChannels(channels, cipher);+ const lastRuns = await $getLastRuns(alerts.map((alert) => alert.id));+ const resourceNames = await $getResourceNames(+ provider,+ dto.actorOrgId,+ alerts.map((alert) => alert.resourceId)+ );+const detailById = new Map(details.map((detail) => [detail.id, detail]));const channelIdsByAlert = new Map<string, string[]>();channels.forEach((channel) => {@@ -251,7 +371,11 @@ export const alertServiceFactory = ({alert,(channelIdsByAlert.get(alert.id) ?? []).map((id) => detailById.get(id))- .filter((detail): detail is TAlertChannelEmbedded => Boolean(detail))+ .filter((detail): detail is TAlertChannelEmbedded => Boolean(detail)),+ {+ resourceName: (alert.resourceId && resourceNames.get(alert.resourceId)) || null,+ lastRun: lastRuns.get(alert.id) ?? null+ }));};@@ -335,6 +459,18 @@ export const alertServiceFactory = ({throw new BadRequestError({ message: "At least one channel is required" });}+ if (dto.channels && provider.assertChannelTypesAllowed) {+ const existingTypeById = new Map(+ (await alertChannelDAL.findByAlertId(alert.id)).map((channel) => [channel.id, channel.channelType])+ );+ await provider.assertChannelTypesAllowed({+ orgId: alert.orgId,+ channelTypes: dto.channels+ .filter((channel) => !channel.id || existingTypeById.get(channel.id) !== channel.channelType)+ .map((channel) => channel.channelType)+ });+ }+const scope = { orgId: alert.orgId, projectId: alert.projectId };const cipher = await getAlertChannelCipher(kmsService, scope);@@ -359,7 +495,11 @@ export const alertServiceFactory = ({return { updated: updatedAlert, channels: details };});- return $assembleResponse(updated, channels);+ const lastRuns = await $getLastRuns([alert.id]);+ return $assembleResponse(updated, channels, {+ resourceName: await $getResourceName(provider, alert),+ lastRun: lastRuns.get(alert.id) ?? null+ });};const $deleteAlertsByFilter = async (filter: Parameters<typeof alertDAL.delete>[0], tx: Knex): Promise<number> => {@@ -382,6 +522,8 @@ export const alertServiceFactory = ({id: string;name: string;resourceType: string;+ resourceId: string | null;+ resourceName: string | null;eventType: string;orgId: string;projectId: string | null;@@ -397,12 +539,15 @@ export const alertServiceFactory = ({dto);+ const resourceName = await $getResourceName(provider, alert);await alertDAL.transaction((tx) => $deleteAlertsByFilter({ id: alert.id }, tx));return {id: alert.id,name: alert.name,resourceType: alert.resourceType,+ resourceId: alert.resourceId ?? null,+ resourceName,eventType: alert.eventType,orgId: alert.orgId,projectId: alert.projectId ?? null@@ -433,7 +578,26 @@ export const alertServiceFactory = ({tx?: Knex): Promise<number> => $reapAlerts({ resourceType, resourceId }, tx);+ const getTelemetryEvent = (+ action: AlertTelemetryAction,+ alert: {+ resourceType: string;+ orgId: string;+ projectId: string | null;+ resourceId: string | null;+ eventType: string;+ }+ ) =>+ alertProviderRegistry.get(alert.resourceType)?.getTelemetryEvent?.({+ action,+ orgId: alert.orgId,+ projectId: alert.projectId,+ resourceId: alert.resourceId,+ eventType: alert.eventType+ });+return {+ getTelemetryEvent,createAlert,getAlertById,listAlerts,diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.tsindex 3f66d795b1..0546ddc77c 100644--- a/backend/src/services/alert/alert-types.ts+++ b/backend/src/services/alert/alert-types.ts@@ -1,12 +1,14 @@import { z } from "zod";import { TGenericPermission } from "@app/lib/types";+import { TPostHogEvent } from "@app/services/telemetry/telemetry-types";import { TAlertPayload } from "./alert-channel-types";export enum AlertPrincipalType {USER = "user",- GROUP = "group"+ GROUP = "group",+ EMAIL = "email"}export enum AlertTriggerType {@@ -48,6 +50,14 @@ export const toAlertActor = (dto: TGenericPermission): TGenericPermission => ({actorOrgId: dto.actorOrgId});+export const resolveAlertProjectId = async (+ provider: IResourceAlertProvider,+ { orgId, projectId, resourceId }: { orgId: string; projectId?: string | null; resourceId?: string | null }+): Promise<string | null> => {+ if (projectId || !resourceId || !provider.resolveProjectId) return projectId ?? null;+ return provider.resolveProjectId({ orgId, resourceId });+};+export const DEFAULT_DEDUP_WINDOW_HOURS = 24;// Providers scan this many days ahead of `alertBefore` so alerts fire at LEAST `alertBefore` before@@ -100,6 +110,26 @@ export type IScheduledAlertProvider<TTarget = unknown> = IResourceAlertProvider<export type IEventAlertProvider<TTarget = unknown> = IResourceAlertProvider<TTarget> &Required<Pick<IResourceAlertProvider<TTarget>, "findTargetsByIds">>;+export enum AlertTelemetryAction {+ Create = "create",+ Update = "update",+ Delete = "delete"+}++export type TAlertTelemetryInput = {+ action: AlertTelemetryAction;+ orgId: string;+ projectId: string | null;+ resourceId: string | null;+ eventType: string;+};++type TPostHogEventBody<T> = T extends unknown+ ? Omit<T, "distinctId" | "organizationId" | "organizationName" | "anonymous" | "dedup">+ : never;++export type TAlertTelemetryEvent = TPostHogEventBody<TPostHogEvent>;+export interface IResourceAlertProvider<TTarget = unknown> {// Dot-namespaced, e.g. "pki.certificate", "identity.ua-secret".resourceType: string;@@ -139,6 +169,14 @@ export interface IResourceAlertProvider<TTarget = unknown> {// existing permissions (e.g. PKI reuses the `pki-alerts` subject, project- or application-scoped).assertPermission(input: TAlertPermissionInput): Promise<void>;+ assertChannelTypesAllowed?(input: { orgId: string; channelTypes: string[] }): Promise<void>;++ getResourceNames?(input: { orgId: string; resourceIds: string[] }): Promise<Map<string, string>>;++ resolveProjectId?(input: { orgId: string; resourceId: string }): Promise<string>;++ getTelemetryEvent?(input: TAlertTelemetryInput): TAlertTelemetryEvent | undefined;+// Assert that a resource-bound alert's resource belongs to the alert's scope (org, and project// when project-scoped). Called at create. Throws if the resource is out of scope, so an alert// cannot be bound to a foreign/out-of-scope resource. When there is no resourceId (a filter-baseddiff --git a/backend/src/services/alert/channels/alert-channel-pagerduty-fns.ts b/backend/src/services/alert/channels/alert-channel-pagerduty-fns.tsindex 17e14e79d8..bf0fac4ffb 100644--- a/backend/src/services/alert/channels/alert-channel-pagerduty-fns.ts+++ b/backend/src/services/alert/channels/alert-channel-pagerduty-fns.ts@@ -49,8 +49,8 @@ export const buildPagerDutyEvent = (event_action: "trigger",dedup_key: `${payload.alert.id}:${item.id}`,payload: {- summary: `${payload.summary} — ${item.title}`.slice(0, PAGERDUTY_SUMMARY_MAX_LENGTH),- severity: payload.severity,+ summary: (item.summary ?? `${payload.summary} — ${item.title}`).slice(0, PAGERDUTY_SUMMARY_MAX_LENGTH),+ severity: item.severity ?? payload.severity,source: `infisical-${payload.alert.resourceType}`,timestamp: new Date().toISOString(),component: payload.resourceKind,diff --git a/backend/src/services/alert/channels/alert-channels.test.ts b/backend/src/services/alert/channels/alert-channels.test.tsindex bd95aae73b..bceb08b7ab 100644--- a/backend/src/services/alert/channels/alert-channels.test.ts+++ b/backend/src/services/alert/channels/alert-channels.test.ts@@ -166,6 +166,27 @@ describe("buildPagerDutyEvent", () => {expect(pd.payload.custom_details.identifier).toBe("4B:3E:2F:A1");expect(pd.payload.custom_details.fields.Expires).toBe("2025-11-12");});++ test("uses the target's own summary and severity when the provider sets them", () => {+ const payload = samplePayload();+ const item = {+ ...payload.items[1],+ summary: "Certificate 'web.example.com' expires on November 10, 2025",+ severity: "info" as const+ };+ const pd = buildPagerDutyEvent(payload, item, "a".repeat(32));++ expect(pd.payload.summary).toBe("Certificate 'web.example.com' expires on November 10, 2025");+ expect(pd.payload.severity).toBe("info");+ });++ test("falls back to the alert summary and severity for targets without their own", () => {+ const payload = samplePayload();+ const pd = buildPagerDutyEvent(payload, payload.items[0], "a".repeat(32));++ expect(pd.payload.summary).toBe("2 certificates expiring within 30d — api.prod.example.com");+ expect(pd.payload.severity).toBe("warning");+ });});describe("SlackChannelConfigSchema webhook allowlist", () => {diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-dal.test.ts b/backend/src/services/alert/providers/cert-manager-application-alert-dal.test.tsnew file mode 100644index 0000000000..16473a4ba9--- /dev/null+++ b/backend/src/services/alert/providers/cert-manager-application-alert-dal.test.ts@@ -0,0 +1,88 @@+import knex, { Knex } from "knex";++import { TDbClient } from "@app/db";++import { certManagerApplicationAlertDALFactory } from "./cert-manager-application-alert-dal";++const PROJECT_ID = "3f2d7a4e-1b6c-4d8e-9a0f-5c7b2e1d4a6b";+const APPLICATION_ID = "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90";++const buildDAL = () => {+ const builder = knex({ client: "pg" });+ const queries: { sql: string; bindings: readonly unknown[] }[] = [];++ const reader = ((table: string) => {+ const query = builder(table);+ Object.assign(query, {+ then: (resolve: (rows: unknown[]) => void) => {+ const { sql, bindings } = query.toSQL();+ queries.push({ sql, bindings });+ resolve([]);+ }+ });+ return query;+ }) as unknown as Knex;++ const db = Object.assign(reader, { replicaNode: () => reader }) as unknown as TDbClient;+ return { dal: certManagerApplicationAlertDALFactory(db), queries };+};++describe("cert manager application alert DAL", () => {+ test("findExpiringCertificates only scans live certificates of the alert's application inside the window", async () => {+ const { dal, queries } = buildDAL();+ const asOf = new Date("2026-01-01T00:00:00Z");++ await dal.findExpiringCertificates({+ projectId: PROJECT_ID,+ applicationId: APPLICATION_ID,+ alertBeforeInterval: "30 days",+ leadInterval: "1 hour",+ asOf+ });++ const [{ sql, bindings }] = queries;+ expect(sql).toContain('"certificates"."projectId" = ?');+ expect(sql).toContain('"certificates"."applicationId" = ?');+ expect(sql).toContain('not "certificates"."status" = ?');+ expect(sql).toContain('"certificates"."renewedByCertificateId" is null');+ expect(sql).toContain('"certificates"."notAfter" > ?::timestamptz');+ expect(sql).toContain('"certificates"."notAfter" <= ?::timestamptz + ?::interval + ?::interval');+ expect(sql).toContain('order by "certificates"."notAfter" asc');+ expect(bindings).toEqual(+ expect.arrayContaining([PROJECT_ID, APPLICATION_ID, "revoked", asOf, "30 days", "1 hour"])+ );+ });++ test("findCertificatesByIds keeps event targets inside the alert's project and application", async () => {+ const { dal, queries } = buildDAL();++ await dal.findCertificatesByIds({+ projectId: PROJECT_ID,+ applicationId: APPLICATION_ID,+ certificateIds: ["cert-1", "cert-2"]+ });++ const [{ sql, bindings }] = queries;+ expect(sql).toContain('"certificates"."projectId" = ?');+ expect(sql).toContain('"certificates"."applicationId" = ?');+ expect(sql).toContain('"certificates"."id" in (?, ?)');+ expect(bindings).toEqual(expect.arrayContaining([PROJECT_ID, APPLICATION_ID, "cert-1", "cert-2"]));+ });++ test("findApplicationById skips applications in a project pending deletion", async () => {+ const { dal, queries } = buildDAL();++ await dal.findApplicationById(APPLICATION_ID);++ expect(queries[0].sql).toContain('"projects"."deleteAfter" is null');+ });++ test("findApplicationNamesByIds scopes the lookup to the caller's org", async () => {+ const { dal, queries } = buildDAL();++ await dal.findApplicationNamesByIds([APPLICATION_ID], "org-1");++ expect(queries[0].sql).toContain('"projects"."orgId" = ?');+ expect(queries[0].bindings).toEqual(expect.arrayContaining([APPLICATION_ID, "org-1"]));+ });+});diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts b/backend/src/services/alert/providers/cert-manager-application-alert-dal.tsnew file mode 100644index 0000000000..a11f4fd055--- /dev/null+++ b/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts@@ -0,0 +1,136 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { CertStatus } from "@app/services/certificate/certificate-types";++export type TCertManagerApplicationAlertDALFactory = ReturnType<typeof certManagerApplicationAlertDALFactory>;++export type TApplicationAlertCertificate = {+ id: string;+ serialNumber: string;+ commonName: string;+ altNames: string | null;+ profileName: string | null;+ notAfter: Date;+ revocationReason: number | null;+ applicationName: string | null;+};++type TCertificateScope = {+ projectId: string;+ applicationId: string;+};++const MAX_EXPIRING_CERTIFICATES_PER_RUN = 1000;++export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {+ const $selectCertificates = (reader: Knex, { projectId, applicationId }: TCertificateScope) =>+ reader(TableName.Certificate)+ .leftJoin(`${TableName.PkiCertificateProfile} as profile`, `${TableName.Certificate}.profileId`, "profile.id")+ .leftJoin(TableName.PkiApplication, `${TableName.Certificate}.applicationId`, `${TableName.PkiApplication}.id`)+ .where(`${TableName.Certificate}.projectId`, projectId)+ .where(`${TableName.Certificate}.applicationId`, applicationId)+ .select(+ `${TableName.Certificate}.id`,+ `${TableName.Certificate}.serialNumber`,+ `${TableName.Certificate}.commonName`,+ `${TableName.Certificate}.altNames`,+ `${TableName.Certificate}.notAfter`,+ `${TableName.Certificate}.revocationReason`,+ "profile.slug as profileName",+ `${TableName.PkiApplication}.name as applicationName`+ );++ const findExpiringCertificates = async (+ scope: TCertificateScope & { alertBeforeInterval: string; leadInterval: string; asOf: Date },+ tx?: Knex+ ): Promise<TApplicationAlertCertificate[]> => {+ try {+ const certificates = (await $selectCertificates(tx || db.replicaNode(), scope)+ .whereNot(`${TableName.Certificate}.status`, CertStatus.REVOKED)+ .whereNull(`${TableName.Certificate}.renewedByCertificateId`)+ .whereRaw(`"${TableName.Certificate}"."notAfter" > ?::timestamptz`, [scope.asOf])+ .whereRaw(`"${TableName.Certificate}"."notAfter" <= ?::timestamptz + ?::interval + ?::interval`, [+ scope.asOf,+ scope.alertBeforeInterval,+ scope.leadInterval+ ])+ .orderBy(`${TableName.Certificate}.notAfter`, "asc")+ .limit(MAX_EXPIRING_CERTIFICATES_PER_RUN)) as TApplicationAlertCertificate[];++ return certificates;+ } catch (error) {+ throw new DatabaseError({ error, name: "FindExpiringCertificates" });+ }+ };++ const findCertificatesByIds = async (+ scope: TCertificateScope & { certificateIds: string[] },+ tx?: Knex+ ): Promise<TApplicationAlertCertificate[]> => {+ try {+ const certificates = (await $selectCertificates(tx || db, scope).whereIn(+ `${TableName.Certificate}.id`,+ scope.certificateIds+ )) as TApplicationAlertCertificate[];++ return certificates;+ } catch (error) {+ throw new DatabaseError({ error, name: "FindCertificatesByIds" });+ }+ };++ const findApplicationById = async (+ applicationId: string,+ tx?: Knex+ ): Promise<{ id: string; name: string; projectId: string; orgId: string } | undefined> => {+ try {+ const application = (await (tx || db.replicaNode())(TableName.PkiApplication)+ .join(TableName.Project, `${TableName.PkiApplication}.projectId`, `${TableName.Project}.id`)+ .where(`${TableName.PkiApplication}.id`, applicationId)+ .whereNull(`${TableName.Project}.deleteAfter`)+ .select(+ `${TableName.PkiApplication}.id`,+ `${TableName.PkiApplication}.name`,+ `${TableName.PkiApplication}.projectId`,+ `${TableName.Project}.orgId`+ )+ .first()) as { id: string; name: string; projectId: string; orgId: string } | undefined;++ return application;+ } catch (error) {+ throw new DatabaseError({ error, name: "FindApplicationById" });+ }+ };++ const findApplicationNamesByIds = async (+ applicationIds: string[],+ orgId: string,+ tx?: Knex+ ): Promise<{ id: string; name: string }[]> => {+ if (applicationIds.length === 0) return [];+ try {+ const applications = (await (tx || db.replicaNode())(TableName.PkiApplication)+ .join(TableName.Project, `${TableName.PkiApplication}.projectId`, `${TableName.Project}.id`)+ .whereIn(`${TableName.PkiApplication}.id`, applicationIds)+ .where(`${TableName.Project}.orgId`, orgId)+ .select(`${TableName.PkiApplication}.id`, `${TableName.PkiApplication}.name`)) as {+ id: string;+ name: string;+ }[];++ return applications;+ } catch (error) {+ throw new DatabaseError({ error, name: "FindApplicationNamesByIds" });+ }+ };++ return {+ findExpiringCertificates,+ findCertificatesByIds,+ findApplicationById,+ findApplicationNamesByIds+ };+};diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-provider.test.ts b/backend/src/services/alert/providers/cert-manager-application-alert-provider.test.tsnew file mode 100644index 0000000000..c56e0b67e0--- /dev/null+++ b/backend/src/services/alert/providers/cert-manager-application-alert-provider.test.ts@@ -0,0 +1,377 @@+import { createMongoAbility } from "@casl/ability";+import { vi } from "vitest";++import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";++import { AlertChannelType } from "../alert-channel-types";+import { AlertPermissionAction, AlertTelemetryAction, TAlertContext } from "../alert-types";+import { TApplicationAlertCertificate } from "./cert-manager-application-alert-dal";+import {+ certManagerApplicationAlertProviderFactory,+ TCertManagerApplicationAlertProviderDep+} from "./cert-manager-application-alert-provider";++vi.mock("@app/lib/config/env", () => ({+ getConfig: () => ({ SITE_URL: "https://app.infisical.com" })+}));++const RESOURCE_TYPE = "cert-manager.application";+const EXPIRY_EVENT = "cert-manager.application.certificate.expiry";+const ISSUANCE_EVENT = "cert-manager.application.certificate.issuance";+const REVOCATION_EVENT = "cert-manager.application.certificate.revocation";++const futureDate = (days: number) => new Date(Date.now() + days * 24 * 60 * 60 * 1000);++const sampleCertificate = (overrides: Partial<TApplicationAlertCertificate> = {}): TApplicationAlertCertificate => ({+ id: "cert-1",+ serialNumber: "105d3b4c",+ commonName: "api.example.com",+ altNames: "api.example.com, www.api.example.com",+ profileName: "tls-server",+ notAfter: futureDate(5),+ revocationReason: null,+ applicationName: "payments-api",+ ...overrides+});++const alertContext = (overrides: Partial<TAlertContext> = {}): TAlertContext => ({+ id: "alert-1",+ name: "tls-expiry",+ orgId: "org-1",+ projectId: "proj-1",+ resourceType: RESOURCE_TYPE,+ resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",+ eventType: EXPIRY_EVENT,+ condition: { alertBefore: "30d" },+ ...overrides+});++const buildProvider = (opts?: {+ application?: { id: string; name: string; projectId: string; orgId: string };+ certificates?: TApplicationAlertCertificate[];+ onFindExpiring?: (args: Record<string, unknown>) => void;+ onFindByIds?: (args: Record<string, unknown>) => void;+ onFindNames?: (ids: string[], orgId: string) => void;+ abilityRules?: { action: string; subject: string }[];+ pkiEnterpriseAlerting?: boolean;+}) => {+ const application = opts?.application ?? {+ id: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",+ name: "payments-api",+ projectId: "proj-1",+ orgId: "org-1"+ };+ const dal = {+ findApplicationById: async (id: string) => (id === application.id ? application : undefined),+ findApplicationNamesByIds: async (ids: string[], orgId: string) => {+ opts?.onFindNames?.(ids, orgId);+ return ids.includes(application.id) && orgId === application.orgId+ ? [{ id: application.id, name: application.name }]+ : [];+ },+ findExpiringCertificates: async (args: Record<string, unknown>) => {+ opts?.onFindExpiring?.(args);+ return opts?.certificates ?? [];+ },+ findCertificatesByIds: async (args: Record<string, unknown>) => {+ opts?.onFindByIds?.(args);+ return opts?.certificates ?? [];+ }+ };+ const ability = () => createMongoAbility(opts?.abilityRules ?? [{ action: "read", subject: "pki-alerts" }]);+ const permissionService = {+ getProjectPermission: vi.fn(async () => ({ permission: ability() })),+ getResourcePermission: vi.fn(async () => ({ permission: ability() }))+ };+ const licenseService = {+ getPlan: async () => ({ pkiEnterpriseAlerting: opts?.pkiEnterpriseAlerting ?? false })+ };+ const provider = certManagerApplicationAlertProviderFactory({+ certManagerApplicationAlertDAL: dal,+ permissionService,+ licenseService+ } as unknown as TCertManagerApplicationAlertProviderDep);+ return { provider, permissionService };+};++const actor = { actor: "user", actorId: "u1", actorAuthMethod: null, actorOrgId: "org-1" } as never;++const expiryConditionSchema = (provider: ReturnType<typeof buildProvider>["provider"]) =>+ provider.events.find((event) => event.key === EXPIRY_EVENT)!.conditionSchema;++describe("cert manager application alert provider", () => {+ test("expiry condition accepts 1 to 365 days in any unit and rejects everything else", () => {+ const schema = expiryConditionSchema(buildProvider().provider);+ ["1d", "30d", "2w", "12m", "1y", "365d"].forEach((alertBefore) =>+ expect(schema.safeParse({ alertBefore }).success).toBe(true)+ );+ ["0d", "366d", "2y", "13m", "30", "d", "30h", "12345d"].forEach((alertBefore) =>+ expect(schema.safeParse({ alertBefore }).success).toBe(false)+ );+ expect(schema.safeParse({ alertBefore: "30d", filters: [] }).success).toBe(false);+ });++ test("issuance, renewal and revocation are event-triggered and take no condition", () => {+ const { provider } = buildProvider();+ const eventKeys = provider.events.filter((event) => event.key !== EXPIRY_EVENT).map((event) => event.key);+ expect(eventKeys).toEqual([ISSUANCE_EVENT, "cert-manager.application.certificate.renewal", REVOCATION_EVENT]);+ provider.events+ .filter((event) => event.key !== EXPIRY_EVENT)+ .forEach((event) => {+ expect(event.conditionSchema.safeParse(null).success).toBe(true);+ expect(event.conditionSchema.safeParse({ alertBefore: "30d" }).success).toBe(false);+ });+ });++ test("findDueTargets converts alertBefore to days and scopes the scan to the alert's application", async () => {+ let args: Record<string, unknown> | undefined;+ const { provider } = buildProvider({+ onFindExpiring: (value) => {+ args = value;+ }+ });+ await provider.findDueTargets({+ orgId: "org-1",+ projectId: "proj-1",+ resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",+ eventType: EXPIRY_EVENT,+ condition: { alertBefore: "2w" },+ asOf: new Date()+ });+ expect(args).toMatchObject({+ projectId: "proj-1",+ applicationId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",+ alertBeforeInterval: "14 days"+ });+ });++ test("findDueTargets and findTargetsByIds return nothing for an alert with no application", async () => {+ const { provider } = buildProvider({ certificates: [sampleCertificate()] });+ await expect(+ provider.findDueTargets({+ orgId: "org-1",+ projectId: "proj-1",+ eventType: EXPIRY_EVENT,+ condition: { alertBefore: "30d" },+ asOf: new Date()+ })+ ).resolves.toEqual([]);+ await expect(+ provider.findTargetsByIds({+ orgId: "org-1",+ projectId: "proj-1",+ eventType: ISSUANCE_EVENT,+ condition: null,+ targetIds: ["cert-1"]+ } as never)+ ).resolves.toEqual([]);+ });++ test("dedup window tightens as the lead time shrinks and a daily reminder forces 24h", () => {+ const { provider } = buildProvider();+ expect(provider.dedupWindowHours?.({ alertBefore: "7d" })).toBe(20);+ expect(provider.dedupWindowHours?.({ alertBefore: "30d" })).toBe(44);+ expect(provider.dedupWindowHours?.({ alertBefore: "12w" })).toBe(164);+ expect(provider.dedupWindowHours?.({ alertBefore: "1y" })).toBe(716);+ expect(provider.dedupWindowHours?.({ alertBefore: "1y", dailyReminder: true })).toBe(20);+ });++ test("buildPayload summarises expiring certificates with the lead time and singular wording", async () => {+ const { provider } = buildProvider();+ const payload = provider.buildPayload(+ alertContext({ condition: { alertBefore: "1d" } }),+ [sampleCertificate()],+ "https://app.infisical.com/view"+ );+ expect(payload.summary).toBe("1 certificate in application 'payments-api' expiring within 1 day");+ expect(payload.alert.condition).toBe("1d");+ expect(payload.webhookType).toBe(`com.infisical.${EXPIRY_EVENT}`);+ expect(payload.severity).toBe("critical");+ expect(payload.items[0]).toMatchObject({ id: "cert-1", title: "api.example.com", identifier: "105d3b4c" });+ expect(payload.items[0].fields?.map((field) => field.label)).toEqual(["SANs", "Profile", "Expires"]);+ });++ test("buildPayload for a revocation names the certificate and adds the revocation reason", async () => {+ const { provider } = buildProvider();+ const payload = provider.buildPayload(+ alertContext({ eventType: REVOCATION_EVENT, condition: null }),+ [sampleCertificate({ revocationReason: 1, altNames: null, profileName: null })],+ "https://app.infisical.com/view"+ );+ expect(payload.summary).toBe("Certificate 'api.example.com' was revoked in application 'payments-api'");+ expect(payload.severity).toBe("warning");+ expect(payload.alert.condition).toBeUndefined();+ expect(payload.items[0].fields).toEqual([+ { label: "Expires", value: expect.any(String) as string },+ { label: "Revocation Reason", value: "Key Compromise" }+ ]);+ });++ test("buildViewUrl deep-links to the application and falls back to the applications list", async () => {+ const { provider } = buildProvider();+ await expect(provider.buildViewUrl(alertContext())).resolves.toBe(+ "https://app.infisical.com/organizations/org-1/projects/cert-manager/proj-1/applications/payments-api"+ );+ await expect(provider.buildViewUrl(alertContext({ resourceId: "missing" }))).resolves.toBe(+ "https://app.infisical.com/organizations/org-1/projects/cert-manager/proj-1/applications"+ );+ });++ test("assertPermission checks the application's resource permission when the alert is bound to one", async () => {+ const { provider, permissionService } = buildProvider();+ await expect(+ provider.assertPermission({+ action: AlertPermissionAction.Read,+ orgId: "org-1",+ projectId: "proj-1",+ resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",+ actor+ })+ ).resolves.toBeUndefined();+ await expect(+ provider.assertPermission({+ action: AlertPermissionAction.Create,+ orgId: "org-1",+ projectId: "proj-1",+ resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",+ actor+ })+ ).rejects.toThrow();+ expect(permissionService.getResourcePermission).toHaveBeenCalled();+ expect(permissionService.getProjectPermission).not.toHaveBeenCalled();+ });++ test("assertPermission falls back to the project permission without an application and requires a project", async () => {+ const { provider, permissionService } = buildProvider();+ await expect(+ provider.assertPermission({ action: AlertPermissionAction.Read, orgId: "org-1", projectId: "proj-1", actor })+ ).resolves.toBeUndefined();+ expect(permissionService.getProjectPermission).toHaveBeenCalled();+ await expect(+ provider.assertPermission({ action: AlertPermissionAction.Read, orgId: "org-1", actor })+ ).rejects.toThrow("Certificate alerts must be created in Certificate Manager");+ });++ test("assertResourceInScope rejects an application from another project or org", async () => {+ const { provider } = buildProvider();+ await expect(+ provider.assertResourceInScope({+ orgId: "org-1",+ projectId: "proj-1",+ resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90"+ })+ ).resolves.toBeUndefined();+ await expect(+ provider.assertResourceInScope({+ orgId: "org-1",+ projectId: "proj-2",+ resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90"+ })+ ).rejects.toThrow("Application with ID '7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90' not found in Certificate Manager");+ await expect(+ provider.assertResourceInScope({+ orgId: "org-2",+ projectId: "proj-1",+ resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90"+ })+ ).rejects.toThrow();+ await expect(provider.assertResourceInScope({ orgId: "org-1", projectId: "proj-1" })).resolves.toBeUndefined();+ });++ test("resolveProjectId returns the application's project and hides applications from other orgs", async () => {+ const { provider } = buildProvider();+ await expect(+ provider.resolveProjectId?.({ orgId: "org-1", resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90" })+ ).resolves.toBe("proj-1");+ await expect(+ provider.resolveProjectId?.({ orgId: "org-2", resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90" })+ ).rejects.toThrow("Application with ID '7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90' not found");+ });++ test("rejects a malformed application ID with a bad request before any lookup", async () => {+ const { provider, permissionService } = buildProvider();+ const expected = "Invalid application ID 'not-a-uuid': must be a UUID";+ await expect(+ provider.assertPermission({+ action: AlertPermissionAction.Read,+ orgId: "org-1",+ projectId: "proj-1",+ resourceId: "not-a-uuid",+ actor+ })+ ).rejects.toThrow(expected);+ await expect(+ provider.assertResourceInScope({ orgId: "org-1", projectId: "proj-1", resourceId: "not-a-uuid" })+ ).rejects.toThrow(expected);+ await expect(provider.resolveProjectId?.({ orgId: "org-1", resourceId: "not-a-uuid" })).rejects.toThrow(expected);+ expect(permissionService.getResourcePermission).not.toHaveBeenCalled();+ });++ test("assertChannelTypesAllowed lets email through and gates other channels on the plan", async () => {+ await expect(+ buildProvider().provider.assertChannelTypesAllowed?.({ orgId: "org-1", channelTypes: [AlertChannelType.EMAIL] })+ ).resolves.toBeUndefined();+ await expect(+ buildProvider().provider.assertChannelTypesAllowed?.({+ orgId: "org-1",+ channelTypes: [AlertChannelType.EMAIL, AlertChannelType.SLACK]+ })+ ).rejects.toThrow("plan restriction");+ await expect(+ buildProvider({ pkiEnterpriseAlerting: true }).provider.assertChannelTypesAllowed?.({+ orgId: "org-1",+ channelTypes: [AlertChannelType.SLACK]+ })+ ).resolves.toBeUndefined();+ });++ test("getResourceNames scopes the lookup to the caller's org", async () => {+ let lookup: { ids: string[]; orgId: string } | undefined;+ const { provider } = buildProvider({+ onFindNames: (ids, orgId) => {+ lookup = { ids, orgId };+ }+ });+ const names = await provider.getResourceNames?.({+ orgId: "org-1",+ resourceIds: ["7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90"]+ });+ expect(lookup).toEqual({ ids: ["7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90"], orgId: "org-1" });+ expect(names?.get("7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90")).toBe("payments-api");+ const foreign = await provider.getResourceNames?.({+ orgId: "org-2",+ resourceIds: ["7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90"]+ });+ expect(foreign?.size).toBe(0);+ });++ test("telemetry reports the same alertType values as the deprecated application routes", () => {+ const { provider } = buildProvider();+ expect(+ provider.getTelemetryEvent?.({+ action: AlertTelemetryAction.Create,+ orgId: "org-1",+ projectId: "proj-1",+ resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",+ eventType: EXPIRY_EVENT+ })+ ).toEqual({+ event: PostHogEventTypes.PkiAlertCreated,+ properties: {+ orgId: "org-1",+ projectId: "proj-1",+ applicationId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",+ alertType: "expiration"+ }+ });+ expect(+ provider.getTelemetryEvent?.({+ action: AlertTelemetryAction.Delete,+ orgId: "org-1",+ projectId: "proj-1",+ resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",+ eventType: ISSUANCE_EVENT+ })?.event+ ).toBe(PostHogEventTypes.PkiAlertDeleted);+ });+});diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-provider.ts b/backend/src/services/alert/providers/cert-manager-application-alert-provider.tsnew file mode 100644index 0000000000..45a8ef9795--- /dev/null+++ b/backend/src/services/alert/providers/cert-manager-application-alert-provider.ts@@ -0,0 +1,369 @@+import { ForbiddenError } from "@casl/ability";+import { z } from "zod";++import { ActionProjectType, ResourceType } from "@app/db/schemas";+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";+import { ResourcePermissionSub } from "@app/ee/services/permission/resource-permission";+import { getConfig } from "@app/lib/config/env";+import { BadRequestError, NotFoundError } from "@app/lib/errors";+import {+ CERT_MANAGER_APPLICATION_RESOURCE_TYPE,+ CertificateAlertEvent+} from "@app/services/certificate/certificate-alert-events";+import { getRevocationReasonLabel } from "@app/services/pki-alert-v2/pki-alert-v2-types";+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";++import { AlertChannelType, TAlertPayload, TAlertSeverity } from "../alert-channel-types";+import { durationToDays, expirySeverity, formatUtcDate, humanizeDays } from "../alert-format-fns";+import {+ ALERT_SCAN_LEAD_INTERVAL,+ AlertPermissionAction,+ AlertTelemetryAction,+ AlertTriggerType,+ DEFAULT_DEDUP_WINDOW_HOURS,+ IEventAlertProvider,+ IScheduledAlertProvider,+ TAlertContext,+ TAlertPermissionInput,+ TAlertTelemetryEvent,+ TAlertTelemetryInput,+ TFindDueTargetsInput,+ TFindTargetsByIdsInput+} from "../alert-types";+import {+ TApplicationAlertCertificate,+ TCertManagerApplicationAlertDALFactory+} from "./cert-manager-application-alert-dal";++const TELEMETRY_ALERT_TYPE_BY_EVENT: Record<CertificateAlertEvent, string> = {+ [CertificateAlertEvent.Expiry]: "expiration",+ [CertificateAlertEvent.Issuance]: "issuance",+ [CertificateAlertEvent.Renewal]: "renewal",+ [CertificateAlertEvent.Revocation]: "revocation"+};++const MIN_CERTIFICATE_ALERT_BEFORE_DAYS = 1;+const MAX_CERTIFICATE_ALERT_BEFORE_DAYS = 365;++const isValidAlertBefore = (alertBefore: string): boolean => {+ const days = durationToDays(alertBefore);+ return days >= MIN_CERTIFICATE_ALERT_BEFORE_DAYS && days <= MAX_CERTIFICATE_ALERT_BEFORE_DAYS;+};++const ExpirationConditionSchema = z+ .object({+ alertBefore: z+ .string()+ .refine(+ isValidAlertBefore,+ `Must be a number of days, weeks, months or years adding up to ${MIN_CERTIFICATE_ALERT_BEFORE_DAYS} to ${MAX_CERTIFICATE_ALERT_BEFORE_DAYS} days, e.g. '30d' or '2w'`+ ),+ dailyReminder: z.boolean().optional()+ })+ .strict();++const EventConditionSchema = z.object({}).strict().nullish();++const assertValidApplicationId = (applicationId: string) => {+ if (!z.string().uuid().safeParse(applicationId).success) {+ throw new BadRequestError({ message: `Invalid application ID '${applicationId}': must be a UUID` });+ }+};++const EVENT_LABELS: Record<CertificateAlertEvent, string> = {+ [CertificateAlertEvent.Expiry]: "Expiration",+ [CertificateAlertEvent.Issuance]: "Issuance",+ [CertificateAlertEvent.Renewal]: "Renewal",+ [CertificateAlertEvent.Revocation]: "Revocation"+};++const EVENT_VERBS: Record<CertificateAlertEvent, string> = {+ [CertificateAlertEvent.Expiry]: "is expiring",+ [CertificateAlertEvent.Issuance]: "was issued",+ [CertificateAlertEvent.Renewal]: "was renewed",+ [CertificateAlertEvent.Revocation]: "was revoked"+};++const PERMISSION_ACTIONS: Record<AlertPermissionAction, ProjectPermissionActions> = {+ [AlertPermissionAction.Read]: ProjectPermissionActions.Read,+ [AlertPermissionAction.Create]: ProjectPermissionActions.Create,+ [AlertPermissionAction.Edit]: ProjectPermissionActions.Edit,+ [AlertPermissionAction.Delete]: ProjectPermissionActions.Delete+};++const eventSeverity = (eventType: CertificateAlertEvent, targets: TApplicationAlertCertificate[]): TAlertSeverity => {+ if (eventType === CertificateAlertEvent.Expiry) return expirySeverity(targets.map((target) => target.notAfter));+ if (eventType === CertificateAlertEvent.Revocation) return "warning";+ return "info";+};++const formatAltNames = (altNames: string | null): string =>+ (altNames ?? "")+ .split(",")+ .map((name) => name.trim())+ .filter(Boolean)+ .join(", ");++const buildSummary = (+ eventType: CertificateAlertEvent,+ targets: TApplicationAlertCertificate[],+ alertBefore?: string+): string => {+ const applicationName = targets[0]?.applicationName;+ const inApplication = applicationName ? ` in application '${applicationName}'` : "";+ if (alertBefore) {+ const certificates = `${targets.length} certificate${targets.length === 1 ? "" : "s"}`;+ return `${certificates}${inApplication} expiring within ${humanizeDays(durationToDays(alertBefore))}`;+ }+ if (targets.length === 1) return `Certificate '${targets[0].commonName}' ${EVENT_VERBS[eventType]}${inApplication}`;+ return `${targets.length} certificates ${EVENT_VERBS[eventType]}${inApplication}`;+};++const buildItemSummary = (eventType: CertificateAlertEvent, certificate: TApplicationAlertCertificate): string => {+ const inApplication = certificate.applicationName ? ` in application '${certificate.applicationName}'` : "";+ if (eventType === CertificateAlertEvent.Expiry) {+ return `Certificate '${certificate.commonName}'${inApplication} expires on ${formatUtcDate(certificate.notAfter)}`;+ }+ return `Certificate '${certificate.commonName}' ${EVENT_VERBS[eventType]}${inApplication}`;+};++const DAILY_SCAN_DEDUP_MARGIN_HOURS = 4;++const dayMultipleDedupWindowHours = (days: number): number => days * 24 - DAILY_SCAN_DEDUP_MARGIN_HOURS;++const expirationDedupWindowHours = (days: number, dailyReminder?: boolean): number => {+ if (dailyReminder || days <= 7) return dayMultipleDedupWindowHours(1);+ if (days <= 30) return dayMultipleDedupWindowHours(2);+ if (days <= 90) return dayMultipleDedupWindowHours(7);+ return dayMultipleDedupWindowHours(30);+};++export type TCertManagerApplicationAlertProviderDep = {+ certManagerApplicationAlertDAL: TCertManagerApplicationAlertDALFactory;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;+};++export const certManagerApplicationAlertProviderFactory = ({+ certManagerApplicationAlertDAL,+ permissionService,+ licenseService+}: TCertManagerApplicationAlertProviderDep): IScheduledAlertProvider<TApplicationAlertCertificate> &+ IEventAlertProvider<TApplicationAlertCertificate> => {+ const buildViewUrl = async (alert: TAlertContext): Promise<string> => {+ const base = `${getConfig().SITE_URL}/organizations/${alert.orgId}/projects/cert-manager/${alert.projectId}`;+ const application = alert.resourceId+ ? await certManagerApplicationAlertDAL.findApplicationById(alert.resourceId)+ : undefined;+ return application ? `${base}/applications/${encodeURIComponent(application.name)}` : `${base}/applications`;+ };++ const findDueTargets = async (input: TFindDueTargetsInput): Promise<TApplicationAlertCertificate[]> => {+ if (!input.projectId || !input.resourceId) return [];+ const { alertBefore } = ExpirationConditionSchema.parse(input.condition);++ return certManagerApplicationAlertDAL.findExpiringCertificates({+ projectId: input.projectId,+ applicationId: input.resourceId,+ alertBeforeInterval: `${durationToDays(alertBefore)} days`,+ leadInterval: ALERT_SCAN_LEAD_INTERVAL,+ asOf: input.asOf+ });+ };++ const findTargetsByIds = async (input: TFindTargetsByIdsInput): Promise<TApplicationAlertCertificate[]> => {+ if (!input.projectId || !input.resourceId) return [];+ EventConditionSchema.parse(input.condition);++ return certManagerApplicationAlertDAL.findCertificatesByIds({+ projectId: input.projectId,+ applicationId: input.resourceId,+ certificateIds: input.targetIds+ });+ };++ const getTelemetryEvent = ({+ action,+ orgId,+ projectId,+ resourceId,+ eventType+ }: TAlertTelemetryInput): TAlertTelemetryEvent | undefined => {+ if (!projectId || !resourceId) return undefined;+ const properties = { orgId, projectId, applicationId: resourceId };+ switch (action) {+ case AlertTelemetryAction.Create:+ return {+ event: PostHogEventTypes.PkiAlertCreated,+ properties: {+ ...properties,+ alertType: TELEMETRY_ALERT_TYPE_BY_EVENT[eventType as CertificateAlertEvent]+ }+ };+ case AlertTelemetryAction.Update:+ return { event: PostHogEventTypes.PkiAlertUpdated, properties };+ default:+ return { event: PostHogEventTypes.PkiAlertDeleted, properties };+ }+ };++ const buildPayload = (+ alert: TAlertContext,+ targets: TApplicationAlertCertificate[],+ viewUrl: string+ ): TAlertPayload => {+ const eventType = alert.eventType as CertificateAlertEvent;+ const isExpiration = eventType === CertificateAlertEvent.Expiry;+ const alertBefore = isExpiration ? (alert.condition as { alertBefore?: string } | null)?.alertBefore : undefined;++ return {+ alert: {+ id: alert.id,+ name: alert.name,+ orgId: alert.orgId,+ ...(alert.projectId ? { projectId: alert.projectId } : {}),+ resourceType: alert.resourceType,+ ...(alertBefore ? { condition: alertBefore } : {}),+ viewUrl+ },+ eventKey: eventType,+ eventLabel: EVENT_LABELS[eventType],+ webhookType: `com.infisical.${eventType}`,+ resourceKind: "Certificate",+ resourceOwnerKind: "Application",+ severity: eventSeverity(eventType, targets),+ summary: buildSummary(eventType, targets, alertBefore),+ items: targets.map((certificate) => {+ const revocationReason =+ eventType === CertificateAlertEvent.Revocation+ ? getRevocationReasonLabel(certificate.revocationReason)+ : undefined;+ return {+ id: certificate.id,+ title: certificate.commonName,+ identifier: certificate.serialNumber,+ summary: buildItemSummary(eventType, certificate),+ severity: eventSeverity(eventType, [certificate]),+ fields: [+ ...(formatAltNames(certificate.altNames)+ ? [{ label: "SANs", value: formatAltNames(certificate.altNames) }]+ : []),+ ...(certificate.profileName ? [{ label: "Profile", value: certificate.profileName }] : []),+ { label: "Expires", value: formatUtcDate(certificate.notAfter) },+ ...(revocationReason ? [{ label: "Revocation Reason", value: revocationReason }] : [])+ ]+ };+ })+ };+ };++ const assertPermission = async ({ action, projectId, resourceId, actor }: TAlertPermissionInput): Promise<void> => {+ if (!projectId) {+ throw new BadRequestError({ message: "Certificate alerts must be created in Certificate Manager" });+ }++ if (!resourceId) {+ const { permission } = await permissionService.getProjectPermission({+ actor: actor.actor,+ actorId: actor.actorId,+ projectId,+ actorAuthMethod: actor.actorAuthMethod,+ actorOrgId: actor.actorOrgId,+ actionProjectType: ActionProjectType.CertificateManager+ });+ ForbiddenError.from(permission).throwUnlessCan(PERMISSION_ACTIONS[action], ProjectPermissionSub.PkiAlerts);+ return;+ }++ assertValidApplicationId(resourceId);+ const { permission } = await permissionService.getResourcePermission({+ actor: actor.actor,+ actorId: actor.actorId,+ projectId,+ resourceType: ResourceType.CertificateApplication,+ resourceId,+ actorAuthMethod: actor.actorAuthMethod,+ actorOrgId: actor.actorOrgId+ });+ ForbiddenError.from(permission).throwUnlessCan(PERMISSION_ACTIONS[action], ResourcePermissionSub.PkiAlerts);+ };++ const assertResourceInScope = async (input: {+ orgId: string;+ projectId?: string | null;+ resourceId?: string | null;+ }): Promise<void> => {+ if (!input.resourceId) return;+ assertValidApplicationId(input.resourceId);++ const application = await certManagerApplicationAlertDAL.findApplicationById(input.resourceId);+ if (!application || application.orgId !== input.orgId || application.projectId !== input.projectId) {+ throw new NotFoundError({+ message: `Application with ID '${input.resourceId}' not found in Certificate Manager`+ });+ }+ };++ const resolveProjectId = async ({ orgId, resourceId }: { orgId: string; resourceId: string }) => {+ assertValidApplicationId(resourceId);+ const application = await certManagerApplicationAlertDAL.findApplicationById(resourceId);+ if (!application || application.orgId !== orgId) {+ throw new NotFoundError({ message: `Application with ID '${resourceId}' not found` });+ }+ return application.projectId;+ };++ const assertChannelTypesAllowed = async ({ orgId, channelTypes }: { orgId: string; channelTypes: string[] }) => {+ const gatedType = channelTypes.find((channelType) => channelType !== AlertChannelType.EMAIL);+ if (!gatedType) return;++ const plan = await licenseService.getPlan(orgId);+ if (!plan.pkiEnterpriseAlerting) {+ throw new BadRequestError({+ message: `Failed to add a ${gatedType} channel due to plan restriction. Upgrade plan to alert on channels other than email.`+ });+ }+ };++ return {+ resourceType: CERT_MANAGER_APPLICATION_RESOURCE_TYPE,+ events: [+ {+ key: CertificateAlertEvent.Expiry,+ triggerType: AlertTriggerType.Scheduled,+ conditionSchema: ExpirationConditionSchema+ },+ ...[CertificateAlertEvent.Issuance, CertificateAlertEvent.Renewal, CertificateAlertEvent.Revocation].map(+ (key) => ({+ key,+ triggerType: AlertTriggerType.Event,+ conditionSchema: EventConditionSchema+ })+ )+ ],+ findDueTargets,+ findTargetsByIds,+ buildViewUrl,+ buildPayload,+ getTelemetryEvent,+ targetId: (certificate) => certificate.id,+ dedupWindowHours: (condition) => {+ const parsed = ExpirationConditionSchema.safeParse(condition);+ if (!parsed.success) return DEFAULT_DEDUP_WINDOW_HOURS;+ return expirationDedupWindowHours(durationToDays(parsed.data.alertBefore), parsed.data.dailyReminder);+ },+ assertPermission,+ assertResourceInScope,+ assertChannelTypesAllowed,+ resolveProjectId,+ getResourceNames: async ({ orgId, resourceIds }) =>+ new Map(+ (await certManagerApplicationAlertDAL.findApplicationNamesByIds(resourceIds, orgId)).map((app) => [+ app.id,+ app.name+ ])+ )+ };+};diff --git a/backend/src/services/certificate-authority/certificate-authority-service.ts b/backend/src/services/certificate-authority/certificate-authority-service.tsindex a11448d646..8a4d820c39 100644--- a/backend/src/services/certificate-authority/certificate-authority-service.ts+++ b/backend/src/services/certificate-authority/certificate-authority-service.ts@@ -19,6 +19,7 @@ import { CertKeySource } from "@app/services/signer/signer-enums";import { TAppConnectionDALFactory } from "../app-connection/app-connection-dal";import { TAppConnectionServiceFactory } from "../app-connection/app-connection-service";+import { TCertificateAlertEventEmitter } from "../certificate/certificate-alert-events";import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";import { TCertificateDALFactory } from "../certificate/certificate-dal";import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-dal";@@ -170,6 +171,7 @@ type TCertificateAuthorityServiceFactoryDep = {certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;+ certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "notify">;};export type TCertificateAuthorityServiceFactory = ReturnType<typeof certificateAuthorityServiceFactory>;@@ -201,7 +203,8 @@ export const certificateAuthorityServiceFactory = ({hsmConnectorService,certificateAuthoritySecretDAL,licenseService,- pkiAlertV2Queue+ pkiAlertV2Queue,+ certificateAlertEventEmitter}: TCertificateAuthorityServiceFactoryDep) => {const acmeFns = AcmeCertificateAuthorityFns({appConnectionDAL,@@ -1487,7 +1490,8 @@ export const certificateAuthorityServiceFactory = ({godaddyFns,projectDAL,telemetryService,- pkiAlertV2Queue+ pkiAlertV2Queue,+ certificateAlertEventEmitter},certificateRequest)@@ -1502,7 +1506,8 @@ export const certificateAuthorityServiceFactory = ({digicertFns,projectDAL,telemetryService,- pkiAlertV2Queue+ pkiAlertV2Queue,+ certificateAlertEventEmitter},certificateRequest);diff --git a/backend/src/services/certificate-authority/certificate-issuance-queue.ts b/backend/src/services/certificate-authority/certificate-issuance-queue.tsindex 658ac8146e..3a7032f2d6 100644--- a/backend/src/services/certificate-authority/certificate-issuance-queue.ts+++ b/backend/src/services/certificate-authority/certificate-issuance-queue.ts@@ -8,6 +8,10 @@ import { crypto } from "@app/lib/crypto/cryptography";import { NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";+import {+ getIssuanceAlertEvent,+ TCertificateAlertEventEmitter+} from "@app/services/certificate/certificate-alert-events";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";import {CertExtendedKeyUsage,@@ -188,6 +192,7 @@ type TCertificateIssuanceQueueFactoryDep = {>;resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find" | "insertMany">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;+ certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "notify">;pkiApplicationProfileDAL?: Pick<TPkiApplicationProfileDALFactory, "findOneByApplicationAndProfile">;apiEnrollmentConfigDAL?: Pick<TApiEnrollmentConfigDALFactory, "findById">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;@@ -218,6 +223,7 @@ export const certificateIssuanceQueueFactory = ({certificateRequestDAL,resourceMetadataDAL,pkiAlertV2Queue,+ certificateAlertEventEmitter,pkiApplicationProfileDAL,apiEnrollmentConfigDAL,gatewayV2Service,@@ -1203,6 +1209,15 @@ export const certificateIssuanceQueueFactory = ({logger.debug("Failed to queue PKI alert event for async certificate issuance");}+ if (certificateExistsAfterThisJob && issuedCertificateId) {+ await certificateAlertEventEmitter.notify({+ certificateId: issuedCertificateId,+ projectId: ca.projectId,+ eventType: getIssuanceAlertEvent(isRenewal),+ applicationId: scopedApplicationId+ });+ }+if (certificateExistsAfterThisJob) {const telemetryProfile = profileId ? await certificateProfileDAL?.findById(profileId) : undefined;diff --git a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.ts b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.tsindex 31876c9571..ca6d30fe87 100644--- a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.ts+++ b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.ts@@ -5,6 +5,10 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enumsimport { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";import { getDigiCertApiBaseUrl } from "@app/services/app-connection/digicert/digicert-connection-fns";import { TDigiCertConnection } from "@app/services/app-connection/digicert/digicert-connection-types";+import {+ getIssuanceAlertEvent,+ TCertificateAlertEventEmitter+} from "@app/services/certificate/certificate-alert-events";import { EnrollmentType } from "@app/services/certificate-profile/certificate-profile-types";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TProjectDALFactory } from "@app/services/project/project-dal";@@ -66,6 +70,7 @@ export type TProcessDigiCertRequestDeps = {projectDAL: Pick<TProjectDALFactory, "findById">;telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;+ certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "notify">;};export type TProcessDigiCertRequestResult =@@ -215,6 +220,13 @@ export const processDigiCertPendingValidationRequest = async ();}+ await deps.certificateAlertEventEmitter.notify({+ certificateId,+ projectId: request.projectId,+ eventType: getIssuanceAlertEvent(parsed.digicert.isRenewal),+ applicationId: request.applicationId+ });+return { status: CertificateRequestStatus.ISSUED, certificateId, orderStatus };}diff --git a/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts b/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.tsindex 823fdb6f06..c69dc1f47b 100644--- a/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts+++ b/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts@@ -6,6 +6,10 @@ import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";import { logger } from "@app/lib/logger";import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";import { ActorType } from "@app/services/auth/auth-type";+import {+ CertificateAlertEvent,+ TCertificateAlertEventEmitter+} from "@app/services/certificate/certificate-alert-events";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";import { revocationReasonToCrlCode } from "@app/services/certificate/certificate-fns";import { CertStatus, CrlReason } from "@app/services/certificate/certificate-types";@@ -35,6 +39,7 @@ type TDigiCertRevocationSyncQueueFactoryDep = {kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;+ certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "notify">;};export type TDigiCertRevocationSyncQueueFactory = ReturnType<typeof digicertRevocationSyncQueueFactory>;@@ -46,7 +51,8 @@ export const digicertRevocationSyncQueueFactory = ({appConnectionDAL,kmsService,auditLogService,- pkiAlertV2Queue+ pkiAlertV2Queue,+ certificateAlertEventEmitter}: TDigiCertRevocationSyncQueueFactoryDep) => {const appCfg = getConfig();@@ -87,6 +93,13 @@ export const digicertRevocationSyncQueueFactory = ({} catch {logger.debug(`digicert-revocation-sync: failed to queue PKI revocation alert event [certId=${cert.id}]`);}++ await certificateAlertEventEmitter.notify({+ certificateId: cert.id,+ projectId: cert.projectId,+ eventType: CertificateAlertEvent.Revocation,+ applicationId: cert.applicationId ?? null+ });};const syncRevocationsForCertificateAuthority = async (diff --git a/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-processor.ts b/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-processor.tsindex 05f9565db4..4775a0d6b2 100644--- a/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-processor.ts+++ b/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-processor.ts@@ -6,6 +6,10 @@ import { decryptAppConnectionCredentials } from "@app/services/app-connection/apimport { buildGoDaddySsoKeyHeader } from "@app/services/app-connection/godaddy/godaddy-connection-constants";import { getGoDaddyApiBaseUrl } from "@app/services/app-connection/godaddy/godaddy-connection-fns";import { TGoDaddyConnection } from "@app/services/app-connection/godaddy/godaddy-connection-types";+import {+ getIssuanceAlertEvent,+ TCertificateAlertEventEmitter+} from "@app/services/certificate/certificate-alert-events";import { EnrollmentType } from "@app/services/certificate-profile/certificate-profile-types";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TProjectDALFactory } from "@app/services/project/project-dal";@@ -66,6 +70,7 @@ export type TProcessGoDaddyRequestDeps = {projectDAL: Pick<TProjectDALFactory, "findById">;telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;+ certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "notify">;};export type TProcessGoDaddyRequestResult =@@ -209,6 +214,13 @@ export const processGoDaddyPendingValidationRequest = async ();}+ await deps.certificateAlertEventEmitter.notify({+ certificateId,+ projectId: request.projectId,+ eventType: getIssuanceAlertEvent(parsed.godaddy.isRenewal),+ applicationId: request.applicationId+ });+return { status: CertificateRequestStatus.ISSUED, certificateId, orderStatus };} catch (error) {// A renewal can report ISSUED/CURRENT while GoDaddy is still serving the previous certificatediff --git a/backend/src/services/certificate-v3/certificate-approval-fns.ts b/backend/src/services/certificate-v3/certificate-approval-fns.tsindex 6e55088b47..07617738e1 100644--- a/backend/src/services/certificate-v3/certificate-approval-fns.ts+++ b/backend/src/services/certificate-v3/certificate-approval-fns.ts@@ -1,5 +1,6 @@import { ForbiddenError, subject } from "@casl/ability";import { randomUUID } from "crypto";+import { Knex } from "knex";import { ActionProjectType } from "@app/db/schemas";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";@@ -13,6 +14,11 @@ import { TKeyStoreFactory } from "@app/keystore/keystore";import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";+import {+ CertificateAlertEvent,+ TCertificateAlertEventEmitter,+ TCertificateAlertEventInput+} from "@app/services/certificate/certificate-alert-events";import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";@@ -111,6 +117,7 @@ export type TIssueCertificateFromApprovedRequestDeps = {>;keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;+ certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "emit">;};export type TCertificateApprovalService = {@@ -226,9 +233,13 @@ export const certificateApprovalServiceFactory = (pkiApplicationProfileDAL,apiEnrollmentConfigDAL,pkiSyncQueue,- pkiAlertV2Queue+ pkiAlertV2Queue,+ certificateAlertEventEmitter} = deps;+ const $emitIssuanceAlert = (input: Omit<TCertificateAlertEventInput, "eventType">, tx: Knex) =>+ certificateAlertEventEmitter.emit({ ...input, eventType: CertificateAlertEvent.Issuance }, tx);+const $queueIssuanceAlert = async (certificateId: string, projectId: string, applicationId?: string | null) => {try {await pkiAlertV2Queue?.queueCertificateEvent({@@ -681,6 +692,16 @@ export const certificateApprovalServiceFactory = (certificateId: newCert.id,tx});++ await $emitIssuanceAlert(+ {+ certificateId: newCert.id,+ projectId: profile.projectId,+ orgId: profile.project?.orgId,+ applicationId: certRequest.applicationId+ },+ tx+ );}});@@ -938,6 +959,16 @@ export const certificateApprovalServiceFactory = (await certificateDAL.updateById(processResult.certificateData.id, { applicationId }, tx);}+ await $emitIssuanceAlert(+ {+ certificateId: processResult.certificateData.id,+ projectId: profile.projectId,+ orgId: profile.project?.orgId,+ applicationId+ },+ tx+ );+return processResult;});@@ -1097,6 +1128,16 @@ export const certificateApprovalServiceFactory = (tx});+ await $emitIssuanceAlert(+ {+ certificateId: certificateRecord.id,+ projectId: profile.projectId,+ orgId: profile.project?.orgId,+ applicationId+ },+ tx+ );+return { ...certResult, cert: certificateRecord };});diff --git a/backend/src/services/certificate-v3/certificate-renewal-service.ts b/backend/src/services/certificate-v3/certificate-renewal-service.tsindex 7fc24bffe8..e73988435c 100644--- a/backend/src/services/certificate-v3/certificate-renewal-service.ts+++ b/backend/src/services/certificate-v3/certificate-renewal-service.ts@@ -14,6 +14,10 @@ import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/import { logger } from "@app/lib/logger";import { ms } from "@app/lib/ms";import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";+import {+ CertificateAlertEvent,+ TCertificateAlertEventEmitter+} from "@app/services/certificate/certificate-alert-events";import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";import { TCertificateDALFactory, TOriginatingCertificateRequest } from "@app/services/certificate/certificate-dal";import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";@@ -162,6 +166,7 @@ type TCertificateRenewalServiceFactoryDep = {certificateRequestDAL: Pick<TCertificateRequestDALFactory, "attachCertificate" | "transitionFromPending">;resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete" | "find">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;+ certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "emit">;pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory,@@ -230,6 +235,7 @@ export const certificateRenewalServiceFactory = ({certificateRequestDAL,resourceMetadataDAL,pkiAlertV2Queue,+ certificateAlertEventEmitter,pkiApplicationDAL,pkiApplicationProfileDAL,apiEnrollmentConfigDAL,@@ -257,7 +263,7 @@ export const certificateRenewalServiceFactory = ({certificateRequestCreatedAt: Date;orgId: string;},- tx: Parameters<TCertificateDALFactory["updateById"]>[2]+ tx: Knex) => {const renewalUpdate: {profileId?: string | null;@@ -288,6 +294,17 @@ export const certificateRenewalServiceFactory = ({orgId,tx});++ await certificateAlertEventEmitter.emit(+ {+ certificateId: newCert.id,+ projectId: originalCert.projectId,+ orgId,+ eventType: CertificateAlertEvent.Renewal,+ applicationId: originalCert.applicationId ?? null+ },+ tx+ );};const $finalizeRenewal = async ({diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.tsindex 78d7b6dfe6..d78eac3279 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts@@ -316,6 +316,7 @@ describe("CertificateV3Service", () => {});service = certificateV3ServiceFactory({+ certificateAlertEventEmitter: { emit: vi.fn() },certificateDAL: mockCertificateDAL,certificateSecretDAL: mockCertificateSecretDAL,certificateAuthorityDAL: mockCertificateAuthorityDAL,diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.tsindex f80fcfb826..1fd8abe929 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts@@ -1,5 +1,6 @@import { ForbiddenError, subject } from "@casl/ability";import { randomUUID } from "crypto";+import { Knex } from "knex";import { ActionProjectType, ResourceType } from "@app/db/schemas";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";@@ -29,6 +30,11 @@ import {TCertRequestRequestData} from "@app/services/approval-policy/cert-request/cert-request-policy-types";import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";+import {+ CertificateAlertEvent,+ TCertificateAlertEventEmitter,+ TCertificateAlertEventInput+} from "@app/services/certificate/certificate-alert-events";import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";@@ -180,6 +186,7 @@ type TCertificateV3ServiceFactoryDep = {approvalPolicyService: Pick<TApprovalPolicyServiceFactory, "createRequestFromPolicy">;resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete" | "find">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;+ certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "emit">;pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory,"findAllByProfileId" | "findOneByApplicationAndProfile"@@ -349,6 +356,7 @@ export const certificateV3ServiceFactory = ({approvalPolicyService,resourceMetadataDAL,pkiAlertV2Queue,+ certificateAlertEventEmitter,pkiApplicationProfileDAL,pkiApplicationDAL,apiEnrollmentConfigDAL,@@ -359,6 +367,9 @@ export const certificateV3ServiceFactory = ({}: TCertificateV3ServiceFactoryDep) => {const $quotaDeps = { projectDAL, licenseService, usageCounterDAL, keyStore };+ const $emitIssuanceAlert = (input: Omit<TCertificateAlertEventInput, "eventType">, tx: Knex) =>+ certificateAlertEventEmitter.emit({ ...input, eventType: CertificateAlertEvent.Issuance }, tx);+// Called once the certificate row exists, never at the check.const $recordQuotaUsage = async (usage?: { orgId: string; isNewQuotaKey: boolean; isWildcard: boolean }) => {if (usage?.isNewQuotaKey) await recordNewCertificateQuotaKey(usage.orgId, { keyStore }, usage.isWildcard);@@ -929,6 +940,16 @@ export const certificateV3ServiceFactory = ({await certificateDAL.updateById(processResult.certificateData.id, { applicationId }, tx);}+ await $emitIssuanceAlert(+ {+ certificateId: processResult.certificateData.id,+ projectId: profile.projectId,+ orgId: profile.project?.orgId,+ applicationId+ },+ tx+ );+return { ...processResult, certificateRequestId: certRequestResult.id };});@@ -1173,6 +1194,16 @@ export const certificateV3ServiceFactory = ({});}+ await $emitIssuanceAlert(+ {+ certificateId: certResult.certificateId,+ projectId: profile.projectId,+ orgId: profile.project?.orgId,+ applicationId+ },+ tx+ );+return { ...certResult, cert: certificateRecord, certificateRequestId: certRequestResult.id };});@@ -1671,6 +1702,16 @@ export const certificateV3ServiceFactory = ({tx);+ await $emitIssuanceAlert(+ {+ certificateId: newCert.id,+ projectId: profile.projectId,+ orgId: profile.project?.orgId,+ applicationId+ },+ tx+ );+if (metadata && metadata.length > 0) {await insertMetadataForCertificate(resourceMetadataDAL, {metadata,@@ -2281,6 +2322,7 @@ export const certificateV3ServiceFactory = ({certificateRequestDAL,resourceMetadataDAL,pkiAlertV2Queue,+ certificateAlertEventEmitter,pkiApplicationProfileDAL,pkiApplicationDAL,apiEnrollmentConfigDAL,diff --git a/backend/src/services/certificate/certificate-alert-events.ts b/backend/src/services/certificate/certificate-alert-events.tsnew file mode 100644index 0000000000..6a0cfe91ce--- /dev/null+++ b/backend/src/services/certificate/certificate-alert-events.ts@@ -0,0 +1,70 @@+import { Knex } from "knex";++import { logger } from "@app/lib/logger";+import { TEventEmitter } from "@app/services/event-outbox/event-outbox-types";+import { TProjectDALFactory } from "@app/services/project/project-dal";++export const CERT_MANAGER_APPLICATION_RESOURCE_TYPE = "cert-manager.application";++export enum CertificateAlertEvent {+ Expiry = "cert-manager.application.certificate.expiry",+ Issuance = "cert-manager.application.certificate.issuance",+ Renewal = "cert-manager.application.certificate.renewal",+ Revocation = "cert-manager.application.certificate.revocation"+}++export const getIssuanceAlertEvent = (isRenewal?: boolean) =>+ isRenewal ? CertificateAlertEvent.Renewal : CertificateAlertEvent.Issuance;++export type TCertificateAlertEventInput = {+ certificateId: string;+ projectId: string;+ orgId?: string;+ applicationId?: string | null;+ eventType: CertificateAlertEvent;+};++type TCertificateAlertEventEmitterDep = {+ eventEmitter: TEventEmitter;+ projectDAL: Pick<TProjectDALFactory, "findById" | "transaction">;+};++export type TCertificateAlertEventEmitter = ReturnType<typeof certificateAlertEventEmitterFactory>;++export const certificateAlertEventEmitterFactory = ({ eventEmitter, projectDAL }: TCertificateAlertEventEmitterDep) => {+ const emit = async (+ { certificateId, projectId, orgId, applicationId, eventType }: TCertificateAlertEventInput,+ tx: Knex+ ) => {+ if (!applicationId) return;++ const resolvedOrgId = orgId ?? (await projectDAL.findById(projectId, tx))?.orgId;+ if (!resolvedOrgId) return;++ const event = {+ eventType,+ payload: {+ orgId: resolvedOrgId,+ projectId,+ resourceType: CERT_MANAGER_APPLICATION_RESOURCE_TYPE,+ resourceId: applicationId,+ targetIds: [certificateId]+ }+ };++ await eventEmitter.emit(event, tx);+ };++ const notify = async (input: TCertificateAlertEventInput) => {+ try {+ await projectDAL.transaction((tx) => emit(input, tx));+ } catch (error) {+ logger.warn(+ error,+ `Failed to emit certificate alert event [certificateId=${input.certificateId}] [eventType=${input.eventType}]`+ );+ }+ };++ return { emit, notify };+};diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.tsindex b5c04ddea0..03fd385c37 100644--- a/backend/src/services/certificate/certificate-service.ts+++ b/backend/src/services/certificate/certificate-service.ts@@ -21,6 +21,10 @@ import { TKeyStoreFactory } from "@app/keystore/keystore";import { crypto } from "@app/lib/crypto/cryptography";import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";+import {+ CertificateAlertEvent,+ TCertificateAlertEventEmitter+} from "@app/services/certificate/certificate-alert-events";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";@@ -154,6 +158,7 @@ type TCertificateServiceFactoryDep = {certificateAuthorityService: Pick<TCertificateAuthorityServiceFactory, "revokeCertificate">;resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;+ certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "emit">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;usageCounterDAL: Pick<TUsageCounterDALFactory,@@ -187,6 +192,7 @@ export const certificateServiceFactory = ({certificateAuthorityService,resourceMetadataDAL,pkiAlertV2Queue,+ certificateAlertEventEmitter,pkiApplicationDAL,certificateProfileDAL,pkiApplicationProfileDAL,@@ -746,6 +752,7 @@ export const certificateServiceFactory = ({const revokedAt = new Date();const revokedCertId = cert.id;+ const revokedCertApplicationId = cert.applicationId ?? null;await certificateDAL.transaction(async (tx) => {await certificateDAL.update({@@ -762,6 +769,17 @@ export const certificateServiceFactory = ({if (!ca.externalCa?.id) {await internalCertificateAuthorityDAL.update({ caId: ca.id }, { $incr: { ocspGeneration: 1 } }, tx);}++ await certificateAlertEventEmitter.emit(+ {+ certificateId: revokedCertId,+ projectId: ca.projectId,+ orgId: actorOrgId,+ eventType: CertificateAlertEvent.Revocation,+ applicationId: revokedCertApplicationId+ },+ tx+ );});usageMeteringService.emitForProject(ca.projectId, ActiveCerts.key);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.tsindex c1ac4185e4..cf6ad882da 100644--- a/backend/src/services/pki-alert-v2/pki-alert-v2-constants.ts+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-constants.ts@@ -1 +1,3 @@export const PKI_ALERT_RETRY_CONFIG = { maxRetries: 3, delayMs: 3000 };++export const LEGACY_ALERT_WRITES_BLOCKED = true;diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-service.test.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-service.test.tsnew file mode 100644index 0000000000..f0688d3f58--- /dev/null+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-service.test.ts@@ -0,0 +1,145 @@+import { createMongoAbility } from "@casl/ability";++import { BadRequestError, NotFoundError } from "@app/lib/errors";++import { TAlertWithChannels } from "./pki-alert-v2-dal";+import { pkiAlertV2ServiceFactory } from "./pki-alert-v2-service";+import { PkiAlertChannelType, PkiAlertEventType } from "./pki-alert-v2-types";++const PROJECT_ID = "project-1";+const APPLICATION_ID = "application-1";+const ALERT_ID = "alert-1";++const actor = {+ actor: "user",+ actorId: "actor-1",+ actorAuthMethod: undefined,+ actorOrgId: "org-1"+} as unknown as { actor: never; actorId: string; actorAuthMethod: never; actorOrgId: string };++const legacyApplicationAlert: TAlertWithChannels = {+ id: ALERT_ID,+ projectId: PROJECT_ID,+ applicationId: APPLICATION_ID,+ name: "expiring-certs",+ description: null,+ eventType: PkiAlertEventType.EXPIRATION,+ alertBefore: "30d",+ filters: [],+ enabled: true,+ notificationConfig: null,+ createdAt: new Date(),+ updatedAt: new Date(),+ channels: [+ {+ id: "channel-1",+ channelType: PkiAlertChannelType.EMAIL,+ config: { recipients: ["[email protected]"] },+ encryptedConfig: null,+ enabled: true,+ createdAt: new Date(),+ updatedAt: new Date()+ }+ ],+ lastRunData: null+} as unknown as TAlertWithChannels;++const buildService = () => {+ const allowAll = createMongoAbility([{ action: "manage", subject: "all" }]);+ const pkiAlertV2DAL = {+ findById: vi.fn(async () => legacyApplicationAlert),+ findByIdWithChannels: vi.fn(async () => legacyApplicationAlert),+ create: vi.fn(),+ updateById: vi.fn(),+ deleteById: vi.fn(async () => legacyApplicationAlert),+ transaction: vi.fn()+ };+ const permissionService = {+ getProjectPermission: vi.fn(async () => ({ permission: allowAll })),+ getResourcePermission: vi.fn(async () => ({ permission: allowAll }))+ };+ const service = pkiAlertV2ServiceFactory({+ pkiAlertV2DAL,+ pkiAlertChannelDAL: {},+ pkiAlertHistoryDAL: {},+ permissionService,+ licenseService: {},+ smtpService: {},+ kmsService: {+ createCipherPairWithDataKey: vi.fn(async () => ({+ encryptor: () => ({ cipherTextBlob: Buffer.from("") }),+ decryptor: () => Buffer.from("")+ }))+ },+ notificationService: {},+ projectMembershipDAL: {},+ projectDAL: {},+ pkiApplicationDAL: {}+ } as unknown as Parameters<typeof pkiAlertV2ServiceFactory>[0]);++ return { service, pkiAlertV2DAL, permissionService };+};++describe("pkiAlertV2Service legacy alerts", () => {+ test("rejects creating a legacy alert and points to the alerts API", async () => {+ const { service, pkiAlertV2DAL, permissionService } = buildService();++ const error = await service+ .createAlert({+ ...actor,+ projectId: PROJECT_ID,+ applicationId: APPLICATION_ID,+ name: "new-alert",+ eventType: PkiAlertEventType.ISSUANCE,+ enabled: true,+ filters: [],+ channels: []+ })+ .catch((err: unknown) => err);++ expect(error).toBeInstanceOf(BadRequestError);+ expect((error as BadRequestError).message).toContain("/api/v1/alerts");+ expect(permissionService.getResourcePermission).not.toHaveBeenCalled();+ expect(pkiAlertV2DAL.create).not.toHaveBeenCalled();+ });++ test("rejects editing a legacy alert, including enabling or disabling it", async () => {+ const { service, pkiAlertV2DAL } = buildService();++ await expect(service.updateAlert({ ...actor, alertId: ALERT_ID, enabled: false })).rejects.toBeInstanceOf(+ BadRequestError+ );+ expect(pkiAlertV2DAL.findById).not.toHaveBeenCalled();+ expect(pkiAlertV2DAL.updateById).not.toHaveBeenCalled();+ });++ test("reads an application-scoped legacy alert with the application's permissions", async () => {+ const { service, permissionService } = buildService();++ const alert = await service.getAlertById({ ...actor, alertId: ALERT_ID, applicationId: APPLICATION_ID });++ expect(alert.applicationId).toBe(APPLICATION_ID);+ expect(alert.channels).toHaveLength(1);+ expect(permissionService.getResourcePermission).toHaveBeenCalledWith(+ expect.objectContaining({ resourceId: APPLICATION_ID, projectId: PROJECT_ID })+ );+ });++ test("deletes an application-scoped legacy alert", async () => {+ const { service, pkiAlertV2DAL } = buildService();++ const alert = await service.deleteAlert({ ...actor, alertId: ALERT_ID, applicationId: APPLICATION_ID });++ expect(alert.id).toBe(ALERT_ID);+ expect(pkiAlertV2DAL.deleteById).toHaveBeenCalledWith(ALERT_ID);+ });++ test("does not delete a legacy alert through another application", async () => {+ const { service, pkiAlertV2DAL } = buildService();++ await expect(+ service.deleteAlert({ ...actor, alertId: ALERT_ID, applicationId: "application-2" })+ ).rejects.toBeInstanceOf(NotFoundError);+ expect(pkiAlertV2DAL.deleteById).not.toHaveBeenCalled();+ });+});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.tsindex 007a5c536e..4aa87052f4 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@@ -25,6 +25,7 @@ import { sendEmailNotificationWithRetry } from "./pki-alert-v2-channel-email-fnsimport { sendPagerDutyNotificationWithRetry } from "./pki-alert-v2-channel-pagerduty-fns";import { sendSlackNotificationWithRetry, validateSlackWebhookUrl } from "./pki-alert-v2-channel-slack-fns";import { sendWebhookNotification } from "./pki-alert-v2-channel-webhook-fns";+import { LEGACY_ALERT_WRITES_BLOCKED } from "./pki-alert-v2-constants";import { TAlertWithChannels, TPkiAlertV2DALFactory } from "./pki-alert-v2-dal";import { parseTimeToDays, parseTimeToPostgresInterval } from "./pki-alert-v2-filter-utils";import {@@ -97,6 +98,15 @@ export const pkiAlertV2ServiceFactory = ({projectDAL,pkiApplicationDAL}: TPkiAlertV2ServiceFactoryDep) => {+ const $assertLegacyAlertWritesAllowed = () => {+ if (LEGACY_ALERT_WRITES_BLOCKED) {+ throw new BadRequestError({+ message:+ "Legacy PKI alerts can no longer be created or edited. Use the alerts API (/api/v1/alerts) or the Alerting section of an application instead. Existing legacy alerts can still be viewed and deleted."+ });+ }+ };+const $assertCanActOnAlert = async (action: ProjectPermissionActions,projectId: string,@@ -227,6 +237,8 @@ export const pkiAlertV2ServiceFactory = ({actor,actorOrgId}: TCreateAlertV2DTO): Promise<TAlertV2Response> => {+ $assertLegacyAlertWritesAllowed();+if (!applicationId) {throw new BadRequestError({message: "Alerts must be created inside an Application. Open the Application's Alerts tab and click Add Alert."@@ -398,6 +410,8 @@ export const pkiAlertV2ServiceFactory = ({actor,actorOrgId}: TUpdateAlertV2DTO): Promise<TAlertV2Response> => {+ $assertLegacyAlertWritesAllowed();+let alert = await pkiAlertV2DAL.findById(alertId);if (!alert) throw new NotFoundError({ message: `Alert with ID '${alertId}' not found` });if (applicationId && alert.applicationId !== applicationId) {diff --git a/backend/src/services/pki-application/pki-application-service.ts b/backend/src/services/pki-application/pki-application-service.tsindex df25a51033..2d4f517fe8 100644--- a/backend/src/services/pki-application/pki-application-service.ts+++ b/backend/src/services/pki-application/pki-application-service.ts@@ -20,10 +20,12 @@ import {} from "@app/ee/services/permission/resource-permission";import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";+import { TAlertServiceFactory } from "../alert/alert-service";import { TApprovalPolicyDALFactory } from "../approval-policy/approval-policy-dal";import { ApprovalPolicyScope } from "../approval-policy/approval-policy-enums";import { TApprovalRequestDALFactory } from "../approval-policy/approval-request-dal";import { ActorType } from "../auth/auth-type";+import { CERT_MANAGER_APPLICATION_RESOURCE_TYPE } from "../certificate/certificate-alert-events";import { TMembershipDALFactory } from "../membership/membership-dal";import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";import { TPkiSyncDALFactory } from "../pki-sync/pki-sync-dal";@@ -64,6 +66,7 @@ type TPkiApplicationServiceFactoryDep = {approvalRequestDAL: Pick<TApprovalRequestDALFactory, "delete">;pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;+ alertService: Pick<TAlertServiceFactory, "deleteAlertsForDeletedResource">;};export type TPkiApplicationServiceFactory = ReturnType<typeof pkiApplicationServiceFactory>;@@ -76,7 +79,8 @@ export const pkiApplicationServiceFactory = ({approvalPolicyDAL,approvalRequestDAL,pkiSyncDAL,- permissionService+ permissionService,+ alertService}: TPkiApplicationServiceFactoryDep) => {const $loadProjectPermission = (projectId: string,@@ -397,6 +401,10 @@ export const pkiApplicationServiceFactory = ({}await approvalRequestDAL.delete({ scopeType: ApprovalPolicyScope.PkiApplication, scopeId: applicationId }, tx);await approvalPolicyDAL.delete({ scopeType: ApprovalPolicyScope.PkiApplication, scopeId: applicationId }, tx);+ await alertService.deleteAlertsForDeletedResource(+ { resourceType: CERT_MANAGER_APPLICATION_RESOURCE_TYPE, resourceId: applicationId },+ tx+ );await pkiApplicationDAL.deleteById(applicationId, tx);});diff --git a/docs/documentation/platform/pki/applications/alerting/overview.mdx b/docs/documentation/platform/pki/applications/alerting/overview.mdxindex 6babd4e5c4..f641b939fc 100644--- a/docs/documentation/platform/pki/applications/alerting/overview.mdx+++ b/docs/documentation/platform/pki/applications/alerting/overview.mdx@@ -1,81 +1,102 @@---title: "Alerting"sidebarTitle: "Overview"-description: "Get notified when certificates expire, are issued, renewed, or revoked."+description: "Get notified when certificates in an application expire, are issued, renewed, or revoked."----Certificate alerting keeps your team informed about critical lifecycle events. Alerts are configured per Application and apply to all certificates within that Application.+Certificate alerting tells your team about certificate lifecycle events in an [Application](/documentation/platform/pki/applications/overview). You create alerts in the application, and each alert watches every certificate in the application for one event.-## Alert types+## Alert events<CardGroup cols={2}><Card title="Expiration" icon="clock">- Notifies when certificates approach expiration. Configure how far in advance (e.g., 30 days).+ Notifies a set number of days before a certificate expires.</Card><Card title="Issuance" icon="award">Notifies immediately when a new certificate is issued.</Card><Card title="Renewal" icon="rotate-cw">- Notifies immediately when a certificate is renewed.+ Notifies when a certificate is renewed.</Card><Card title="Revocation" icon="ban">- Notifies immediately when a certificate is revoked.+ Notifies when a certificate is revoked.</Card></CardGroup>-## Create an alert+Infisical checks expiration alerts once a day. Issuance, renewal, and revocation alerts are sent within seconds of the event. Importing a certificate into the application doesn't trigger an Issuance alert, but expiration and revocation alerts still cover imported certificates.-In your Application, go to the **Settings** tab and find the **Alerting** section. Select **Create Alert**.+## Prerequisites-| Field | Description |-|-------|-------------|-| **Name** | A slug-friendly name like `expiry-alert` |-| **Alert Type** | Expiration, Issuance, Renewal, or Revocation |-| **Description** | Optional context about this alert |+- For email alerts, recipients who are members of Certificate Manager, or addresses on one of your organization's [verified email domains](/documentation/platform/email-domain)-For expiration alerts, you'll also configure:+## Create an alert-| Field | Description |-|-------|-------------|-| **Alert Before** | How far before expiration to notify (e.g., `30d`, `2w`, `1m`) |-| **Daily Alerts** | If enabled, sends daily reminders until the certificate expires or is renewed |+<Steps>+ <Step>+ Go to **Certificate Manager** > **Applications** and select your application.+ </Step>+ <Step>+ Select the **Settings** tab, then select **Create Alert** in the **Alerting** section.+ </Step>+ <Step>+ Choose the **Alert Type**, then enter an **Alert Name** and an optional **Description**.+ </Step>+ <Step>+ For an expiration alert, enter **Alert Before** as a number and a unit, for example `30d` or `2w`, up to 365 days. Turn on **Repeat daily until expiry** to get a reminder every day. See [how often expiration alerts repeat](#faq). Select **Continue**.+ </Step>+ <Step>+ Select **Add Channel** and choose where to send notifications. You can add up to 10 channels. See [Notification channels](#notification-channels). To check a channel, select **Send test** on it. Select **Continue**.+ </Step>+ <Step>+ Check the summary on the **Review** step, then select **Create Alert**.+ </Step>+</Steps>-## Notification channels+An application can have one alert of each type. To notify more places about the same event, add more channels to that alert.-Add one or more channels to receive alerts (up to 10 per alert):+## Notification channels-| Channel | Description |-|---------|-------------|-| **Email** | Send to a list of email addresses |-| **[Slack](/documentation/platform/pki/applications/alerting/slack-alerts)** | Post to a Slack channel via Incoming Webhook |-| **[PagerDuty](/documentation/platform/pki/applications/alerting/pagerduty-alerts)** | Create incidents via Events API v2 |-| **[Webhook](/documentation/platform/pki/applications/alerting/webhook-alerts)** | POST to any HTTPS endpoint with optional signature verification |+| Channel | Sends to |+|---------|----------|+| **Email** | Certificate Manager members, or any address on one of your organization's verified email domains |+| **[Slack](/documentation/platform/pki/applications/alerting/slack-alerts)** | A Slack channel through an Incoming Webhook |+| **[PagerDuty](/documentation/platform/pki/applications/alerting/pagerduty-alerts)** | A PagerDuty service through Events API v2 |+| **[Webhook](/documentation/platform/pki/applications/alerting/webhook-alerts)** | Any HTTPS endpoint, with an optional signature |## FAQ<AccordionGroup>- <Accordion title="Do alerts apply to all certificates in the Application?">- Yes. When you create an alert on an Application, it monitors all certificates issued within that Application. The Application itself is the scope.+ <Accordion title="Who receives email alerts?">+ The addresses you enter on the email channel. An address that belongs to a Certificate Manager member only receives alerts while that person is still a member. Any other address has to be on one of your organization's [verified email domains](/documentation/platform/email-domain) when you add it.</Accordion>- <Accordion title="When do expiration alerts run?">- Expiration alerts are checked on a daily schedule. Event-driven alerts (Issuance, Renewal, Revocation) fire in real-time.+ <Accordion title="How often does an expiration alert notify about the same certificate?">+ The alert repeats until the certificate is renewed or expires. How often it repeats depends on how many days before expiry the alert starts:++ | Days before expiry | Repeats every |+ |--------------------|---------------|+ | 7 or fewer | Day |+ | 8 to 30 | 2 days |+ | 31 to 90 | 7 days |+ | More than 90 | 30 days |++ If you turn on **Repeat daily until expiry**, the alert repeats every day.</Accordion>- <Accordion title="Can I have multiple alerts on one Application?">- Yes. You can create multiple alerts with different types and notification channels. For example, an expiration alert to Slack and an issuance alert to a webhook for audit logging.+ <Accordion title="What happens to an alert when I delete its application?">+ Infisical deletes the application's alerts and their channels along with the application.</Accordion></AccordionGroup>## What's next?<CardGroup cols={2}>- <Card title="Slack Alerts" icon="slack" iconType="brands" href="/documentation/platform/pki/applications/alerting/slack-alerts">- Set up Slack Incoming Webhook integration.+ <Card title="Slack" icon="slack" iconType="brands" href="/documentation/platform/pki/applications/alerting/slack-alerts">+ Set up a Slack Incoming Webhook.</Card>- <Card title="PagerDuty Alerts" icon="radio-tower" href="/documentation/platform/pki/applications/alerting/pagerduty-alerts">- Configure PagerDuty Events API integration.+ <Card title="PagerDuty" icon="radio-tower" href="/documentation/platform/pki/applications/alerting/pagerduty-alerts">+ Create incidents with the PagerDuty Events API.</Card>- <Card title="Webhook Alerts" icon="webhook" href="/documentation/platform/pki/applications/alerting/webhook-alerts">- Send alerts to custom endpoints.+ <Card title="Webhook" icon="webhook" href="/documentation/platform/pki/applications/alerting/webhook-alerts">+ Send alerts to your own endpoint.</Card><Card title="Certificates" icon="award" href="/documentation/platform/pki/applications/certificates">View and manage your certificate inventory.diff --git a/docs/documentation/platform/pki/applications/alerting/pagerduty-alerts.mdx b/docs/documentation/platform/pki/applications/alerting/pagerduty-alerts.mdxindex cf36009848..9cae6e7492 100644--- a/docs/documentation/platform/pki/applications/alerting/pagerduty-alerts.mdx+++ b/docs/documentation/platform/pki/applications/alerting/pagerduty-alerts.mdx@@ -4,88 +4,87 @@ sidebarTitle: "PagerDuty"description: "Create PagerDuty incidents for certificate alerts."----Create PagerDuty incidents when certificate events occur using the [Events API v2](https://developer.pagerduty.com/docs/events-api-v2-overview). Get paged when certificates are about to expire or are revoked.+A PagerDuty channel on a certificate [alert](/documentation/platform/pki/applications/alerting/overview) creates PagerDuty incidents through the [Events API v2](https://developer.pagerduty.com/docs/events-api-v2-overview), so your on-call team gets paged when certificates are about to expire or are revoked.-<Info>- Alerts are configured per Application and apply to all certificates within that Application.-</Info>--## Create a PagerDuty alert+## Step 1: Get a PagerDuty integration key<Steps>- <Step title="Create a PagerDuty Service">- 1. Go to **PagerDuty → Services → Service Directory → New Service**- 2. Name the service (e.g., "Infisical PKI Alerts")- 3. Select **Events API v2** as the integration- 4. Select **Create Service**-+ <Step>+ In PagerDuty, go to **Services** > **Service Directory** and select **New Service**.+ </Step>+ <Step>+ Name the service, for example `Infisical PKI Alerts`, choose **Events API v2** as the integration, and select **Create Service**.+<Note>- To use an existing service, go to **Integrations → Add an Integration → Events API v2**.+ To use an existing service, open the service and go to **Integrations** > **Add an Integration** > **Events API v2**.</Note></Step>- <Step title="Copy the Integration Key">- After creating the service, copy the 32-character **Integration Key** from the **Integrations** tab.-+ <Step>+ Copy the 32-character **Integration Key** from the service's **Integrations** tab.+<Note>- Keep your integration key secure. Anyone with access can send events to your PagerDuty service.+ Anyone with the integration key can send events to your PagerDuty service, so store it like a secret.</Note></Step>- <Step title="Navigate to your Application">- Go to **Certificate Manager → Applications** and select your Application.+</Steps>++## Step 2: Add the PagerDuty channel to an alert++<Steps>+ <Step>+ [Create an alert](/documentation/platform/pki/applications/alerting/overview#create-an-alert) in your application, or edit an existing one.+ </Step>+ <Step>+ Select **Add Channel** > **PagerDuty** and paste the integration key.</Step>- <Step title="Create an alert">- Go to the **Settings** tab and find the **Alerting** section. Select **Create Alert**.-- | Setting | Description |- |---------|-------------|- | **Alert Type** | Certificate Expiration, Issuance, Renewal, or Revocation |- | **Alert Name** | A slug-friendly name like `tls-expiry-alert` |- | **Description** | Optional context about this alert |- | **Alert Before** | *(Expiration only)* Time before expiry to trigger, e.g., `30d` |+ <Step>+ Optionally, select **Send test** to send a test notification to the channel.</Step>- <Step title="Add a PagerDuty channel">- Add a **PagerDuty** notification channel and paste the integration key.+ <Step>+ Select **Continue**, check the **Review** step, and select **Create Alert**.</Step></Steps>## Severity mapping-Infisical automatically maps alert types to PagerDuty severity levels.+Infisical sets each incident's PagerDuty severity from the alert's event. For expiration alerts, each certificate gets its own incident, and that incident's severity comes from how close the certificate is to expiry.### Expiration alerts-| Time Until Expiry | PagerDuty Severity |+| Time until expiry | PagerDuty severity ||-------------------|-------------------|-| ≤ 7 days | `critical` |-| ≤ 14 days | `error` |-| ≤ 30 days | `warning` |-| > 30 days | `info` |+| 7 days or less | `critical` |+| 8 to 14 days | `error` |+| 15 to 30 days | `warning` |+| More than 30 days | `info` |-### Other alert types+### Other alert events-| Alert Type | PagerDuty Severity |-|------------|-------------------|-| Certificate Issuance | `info` |-| Certificate Renewal | `info` |-| Certificate Revocation | `warning` |+| Event | PagerDuty severity |+|-------|-------------------|+| Issuance | `info` |+| Renewal | `info` |+| Revocation | `warning` |## Incident grouping-Alerts with the same alert ID are grouped into the same PagerDuty incident via `dedup_key`. Repeated triggers update the existing incident rather than creating duplicates.+Infisical opens one incident per certificate. If the same alert fires again for the same certificate, PagerDuty updates the existing incident instead of opening a new one.++Each PagerDuty channel opens at most 10 incidents per run. If more than 10 certificates are due for an expiration alert, Infisical sends the certificates closest to expiry first and sends the rest on the next daily run.## What's next?<CardGroup cols={2}>- <Card title="Webhook Alerts" icon="webhook" href="/documentation/platform/pki/applications/alerting/webhook-alerts">- Send alerts to custom HTTP endpoints.+ <Card title="Webhook" icon="webhook" href="/documentation/platform/pki/applications/alerting/webhook-alerts">+ Send alerts to your own endpoint.</Card>- <Card title="Slack Alerts" icon="slack" iconType="brands" href="/documentation/platform/pki/applications/alerting/slack-alerts">+ <Card title="Slack" icon="slack" iconType="brands" href="/documentation/platform/pki/applications/alerting/slack-alerts">Send alerts to a Slack channel.</Card>- <Card title="Certificate Syncs" icon="refresh-cw" href="/documentation/platform/pki/applications/certificate-syncs/overview">+ <Card title="Certificate syncs" icon="refresh-cw" href="/documentation/platform/pki/applications/certificate-syncs/overview">Push certificates to cloud destinations.</Card>- <Card title="Managing Certificates" icon="list" href="/documentation/platform/pki/applications/certificates">+ <Card title="Certificates" icon="list" href="/documentation/platform/pki/applications/certificates">View and manage certificates.</Card></CardGroup>diff --git a/docs/documentation/platform/pki/applications/alerting/slack-alerts.mdx b/docs/documentation/platform/pki/applications/alerting/slack-alerts.mdxindex 7eb57ea6a2..18844f0edb 100644--- a/docs/documentation/platform/pki/applications/alerting/slack-alerts.mdx+++ b/docs/documentation/platform/pki/applications/alerting/slack-alerts.mdx@@ -4,76 +4,72 @@ sidebarTitle: "Slack"description: "Send certificate alert notifications to a Slack channel."----Send certificate alert notifications to a Slack channel using [Incoming Webhooks](https://api.slack.com/messaging/webhooks). Get notified when certificates expire, are issued, renewed, or revoked.+A Slack channel on a certificate [alert](/documentation/platform/pki/applications/alerting/overview) posts to a Slack channel through an [Incoming Webhook](https://api.slack.com/messaging/webhooks) whenever the alert fires.-<Info>- Alerts are configured per Application and apply to all certificates within that Application.-</Info>--## Create a Slack alert+## Step 1: Create a Slack incoming webhook<Steps>- <Step title="Create a Slack App">- 1. Go to the [Slack API Apps page](https://api.slack.com/apps) and select **Create New App**- 2. Select **From scratch**- 3. Name your app (e.g., "Infisical PKI Alerts") and select your workspace- 4. Select **Create App**+ <Step>+ Go to the [Slack API Apps page](https://api.slack.com/apps), select **Create New App**, then select **From scratch**.+ </Step>+ <Step>+ Name the app, for example `Infisical PKI Alerts`, pick your workspace, and select **Create App**.+ </Step>+ <Step>+ In the app settings, go to **Incoming Webhooks** and turn on **Activate Incoming Webhooks**.</Step>- <Step title="Enable Incoming Webhooks">- 1. In your app settings, go to **Incoming Webhooks** under "Features"- 2. Toggle **Activate Incoming Webhooks** to **On**- 3. Select **Add New Webhook to Workspace**- 4. Select the channel for alerts and select **Allow**- 5. Copy the **Webhook URL**-+ <Step>+ Select **Add New Webhook to Workspace**, pick the Slack channel for alerts, and select **Allow**.+ </Step>+ <Step>+ Copy the **Webhook URL**.+<Note>- Keep your webhook URL secure. Anyone with access can post to your channel.+ Anyone with the webhook URL can post to your Slack channel, so store it like a secret.</Note></Step>- <Step title="Navigate to your Application">- Go to **Certificate Manager → Applications** and select your Application.+</Steps>++## Step 2: Add the Slack channel to an alert++<Steps>+ <Step>+ [Create an alert](/documentation/platform/pki/applications/alerting/overview#create-an-alert) in your application, or edit an existing one.</Step>- <Step title="Create an alert">- Go to the **Settings** tab and find the **Alerting** section. Select **Create Alert**.-- | Setting | Description |- |---------|-------------|- | **Alert Type** | Certificate Expiration, Issuance, Renewal, or Revocation |- | **Alert Name** | A slug-friendly name like `tls-expiry-alert` |- | **Description** | Optional context about this alert |- | **Alert Before** | *(Expiration only)* Time before expiry to trigger, e.g., `30d` |+ <Step>+ Select **Add Channel** > **Slack** and paste the webhook URL. The URL must start with `https://hooks.slack.com`.</Step>- <Step title="Add a Slack channel">- Add a **Slack** notification channel and paste the webhook URL from Slack.+ <Step>+ Optionally, select **Send test** to send a test notification to the channel.+ </Step>+ <Step>+ Select **Continue**, check the **Review** step, and select **Create Alert**.</Step></Steps>## Message format-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:+Each Slack message includes the alert's summary, up to two certificates, and a link to the application in Infisical. The message color shows the alert's severity:-| Event Type | Color |-|------------|-------|-| Certificate Expiration | Amber |-| Certificate Issuance | Green |-| Certificate Renewal | Blue |-| Certificate Revocation | Red |+| Color | Severity | When |+|-------|----------|------|+| Red | Critical or error | A certificate expires within 14 days |+| Amber | Warning | A certificate expires within 15 to 30 days, or a certificate was revoked |+| Blue | Info | A certificate expires in more than 30 days, or a certificate was issued or renewed |## What's next?<CardGroup cols={2}>- <Card title="Webhook Alerts" icon="webhook" href="/documentation/platform/pki/applications/alerting/webhook-alerts">- Send alerts to custom HTTP endpoints.+ <Card title="Webhook" icon="webhook" href="/documentation/platform/pki/applications/alerting/webhook-alerts">+ Send alerts to your own endpoint.</Card>- <Card title="PagerDuty Alerts" icon="radio-tower" href="/documentation/platform/pki/applications/alerting/pagerduty-alerts">+ <Card title="PagerDuty" icon="radio-tower" href="/documentation/platform/pki/applications/alerting/pagerduty-alerts">Create incidents in PagerDuty.</Card>- <Card title="Certificate Syncs" icon="refresh-cw" href="/documentation/platform/pki/applications/certificate-syncs/overview">+ <Card title="Certificate syncs" icon="refresh-cw" href="/documentation/platform/pki/applications/certificate-syncs/overview">Push certificates to cloud destinations.</Card>- <Card title="Managing Certificates" icon="list" href="/documentation/platform/pki/applications/certificates">+ <Card title="Certificates" icon="list" href="/documentation/platform/pki/applications/certificates">View and manage certificates.</Card></CardGroup>diff --git a/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx b/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdxindex eb69377d90..1269c45275 100644--- a/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx+++ b/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx@@ -4,133 +4,122 @@ sidebarTitle: "Webhook"description: "Send certificate alert notifications to a webhook URL."----Send certificate alert notifications to any HTTP endpoint. Webhook alerts let you integrate Infisical with your own systems, automation tools, or services that aren't directly supported.+A webhook channel on a certificate [alert](/documentation/platform/pki/applications/alerting/overview) sends an HTTP POST request to your endpoint whenever the alert fires. Use a webhook to connect certificate alerts to your own systems or to services Infisical doesn't support directly.-<Info>- Alerts are configured per Application and apply to all certificates within that Application.-</Info>--## Create a webhook alert+## Add a webhook channel to an alert<Steps>- <Step title="Navigate to your Application">- Go to **Certificate Manager → Applications** and select your Application.+ <Step>+ [Create an alert](/documentation/platform/pki/applications/alerting/overview#create-an-alert) in your application, or edit an existing one.+ </Step>+ <Step>+ Select **Add Channel** > **Webhook** and enter the **URL** of your endpoint. The URL must use HTTPS.</Step>- <Step title="Create an alert">- Go to the **Settings** tab and find the **Alerting** section. Select **Create Alert**.+ <Step>+ Optionally, enter a **Signing Secret** so your endpoint can [verify the signature](#verify-the-signature) of each request.</Step>- <Step title="Configure alert settings">- | Setting | Description |- |---------|-------------|- | **Alert Type** | Certificate Expiration, Issuance, Renewal, or Revocation |- | **Alert Name** | A slug-friendly name like `tls-expiry-alert` |- | **Description** | Optional context about this alert |- | **Alert Before** | *(Expiration only)* Time before expiry to trigger, e.g., `30d` |+ <Step>+ Optionally, select **Send test** to send a test notification to the channel.</Step>- <Step title="Add a webhook channel">- Add a **Webhook** notification channel:-- | Setting | Description |- |---------|-------------|- | **URL** | The HTTPS endpoint to receive notifications |- | **Signing Secret** | *(Optional)* Secret to verify webhook authenticity |-- <Note>- The webhook URL must use HTTPS.- </Note>+ <Step>+ Select **Continue**, check the **Review** step, and select **Create Alert**.</Step></Steps>## Webhook event types-Each alert type maps to a corresponding CloudEvents event type:+Each request is a [CloudEvents](https://cloudevents.io/) JSON payload. The `type` and `subject` fields name the event:-| 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` |+| Event | `type` | `subject` |+|-------|--------|-----------|+| Expiration | `com.infisical.cert-manager.application.certificate.expiry` | `cert-manager.application.certificate.expiry` |+| Issuance | `com.infisical.cert-manager.application.certificate.issuance` | `cert-manager.application.certificate.issuance` |+| Renewal | `com.infisical.cert-manager.application.certificate.renewal` | `cert-manager.application.certificate.renewal` |+| Revocation | `com.infisical.cert-manager.application.certificate.revocation` | `cert-manager.application.certificate.revocation` |## Webhook payload format-Webhook notifications are sent as HTTP POST requests with a [CloudEvents](https://cloudevents.io/) compliant JSON payload.+`data.items` lists the certificates the alert fired for. Each item has the certificate's ID, its common name as `title`, its serial number as `identifier`, a one-line `summary`, a `severity`, and a list of display `fields`. An expiration request can include several certificates, and `data.alert.condition` holds the alert's lead time as you entered it, such as `30d` or `2w`. Issuance, renewal, and revocation requests include the one certificate the event was about.++<Note>+ Only alerts created in an application send this payload. Alerts created before certificate alerts moved to applications keep sending the older `com.infisical.pki.certificate.*` event types with a `data.certificates` list. If one endpoint receives both, check the `type` field to tell them apart.+</Note><Tabs>- <Tab title="Expiration Alert">+ <Tab title="Expiration">```json{"specversion": "1.0",- "type": "com.infisical.pki.certificate.expiration",- "source": "/applications/<application-id>/alerts/<alert-id>",+ "type": "com.infisical.cert-manager.application.certificate.expiry",+ "source": "/projects/<project-id>/alerts/<alert-id>","id": "<unique-event-id>",- "time": "2024-01-15T10:30:00.000Z",+ "time": "2026-09-24T00:00:09.664Z","datacontenttype": "application/json",- "subject": "certificate-expiration-alert",+ "subject": "cert-manager.application.certificate.expiry","data": {"alert": {"id": "<alert-id>","name": "tls-expiry-alert",- "alertBefore": "30d",- "applicationId": "<application-id>"+ "resourceType": "cert-manager.application",+ "condition": "30d"},- "certificates": [+ "items": [{"id": "<certificate-id>",- "serialNumber": "1234567890",- "commonName": "api.example.com",- "san": ["api.example.com", "www.api.example.com"],- "profileName": "TLS Server",- "notBefore": "2024-01-01T00:00:00.000Z",- "notAfter": "2024-12-31T23:59:59.000Z",- "status": "active",- "daysUntilExpiry": 30+ "title": "api.example.com",+ "identifier": "105d3b4c28132774ab17e350c0e8229ba1bef40d",+ "summary": "Certificate 'api.example.com' in application 'payments-api' expires on October 4, 2026 at 11:59 PM UTC",+ "severity": "error",+ "fields": [+ { "label": "SANs", "value": "api.example.com, www.api.example.com" },+ { "label": "Profile", "value": "tls-server" },+ { "label": "Expires", "value": "October 4, 2026 at 11:59 PM UTC" }+ ]}],"metadata": {- "totalCertificates": 1,- "viewUrl": "https://app.infisical.com/cert-manager/applications/<application-id>/certificates"+ "totalItems": 1,+ "viewUrl": "https://app.infisical.com/organizations/<org-id>/projects/cert-manager/<project-id>/applications/<application-name>"}}}```</Tab>- <Tab title="Issuance/Renewal/Revocation">- These alerts are sent in real time when the certificate event occurs. Each notification contains a single certificate. The `alertBefore` field is omitted.-- For revocation alerts, the certificate object also includes `revokedAt` and `revocationReason`.-+ <Tab title="Revocation">+ Revocation items also include a **Revocation Reason** field. Issuance and renewal requests have the same shape without that field.+```json{"specversion": "1.0",- "type": "com.infisical.pki.certificate.issuance",- "source": "/applications/<application-id>/alerts/<alert-id>",+ "type": "com.infisical.cert-manager.application.certificate.revocation",+ "source": "/projects/<project-id>/alerts/<alert-id>","id": "<unique-event-id>",- "time": "2024-06-15T14:22:00.000Z",+ "time": "2026-09-24T14:22:00.000Z","datacontenttype": "application/json",- "subject": "certificate-issuance-alert",+ "subject": "cert-manager.application.certificate.revocation","data": {"alert": {"id": "<alert-id>",- "name": "prod-issuance-notify",- "applicationId": "<application-id>"+ "name": "prod-revocation-notify",+ "resourceType": "cert-manager.application"},- "certificates": [+ "items": [{"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+ "title": "api.example.com",+ "identifier": "105d3b4c28132774ab17e350c0e8229ba1bef40d",+ "summary": "Certificate 'api.example.com' was revoked in application 'payments-api'",+ "severity": "warning",+ "fields": [+ { "label": "Profile", "value": "tls-server" },+ { "label": "Expires", "value": "October 4, 2026 at 11:59 PM UTC" },+ { "label": "Revocation Reason", "value": "Key Compromise" }+ ]}],"metadata": {- "totalCertificates": 1,- "viewUrl": "https://app.infisical.com/cert-manager/applications/<application-id>/certificates"+ "totalItems": 1,+ "viewUrl": "https://app.infisical.com/organizations/<org-id>/projects/cert-manager/<project-id>/applications/<application-name>"}}}@@ -140,7 +129,7 @@ Webhook notifications are sent as HTTP POST requests with a [CloudEvents](https:## Webhook signature verification-If you configure a signing secret, Infisical includes an `x-infisical-signature` header with each request:+If you set a signing secret, Infisical adds an `x-infisical-signature` header to each request:```x-infisical-signature: t=<timestamp>,v1=<signature>@@ -148,15 +137,15 @@ x-infisical-signature: t=<timestamp>,v1=<signature>| Component | Description ||-----------|-------------|-| `t=<timestamp>` | Unix timestamp (milliseconds) when signed |-| `v1=<signature>` | HMAC SHA256 signature |+| `t=<timestamp>` | Unix timestamp in milliseconds when Infisical signed the request |+| `v1=<signature>` | Hex-encoded HMAC SHA256 signature |### Verify the signature-1. Extract timestamp and signature from the header-2. Concatenate: `{timestamp}.{raw-body}`-3. Compute HMAC SHA256 with your signing secret-4. Compare with the header signature+1. Read the timestamp and the signature from the header+2. Join the timestamp and the raw request body with a dot: `{timestamp}.{raw-body}`+3. Compute the HMAC SHA256 of that string with your signing secret+4. Compare the result with the signature from the header```javascriptconst crypto = require('crypto');@@ -182,16 +171,16 @@ function verifyWebhookSignature(header, body, secret) {## What's next?<CardGroup cols={2}>- <Card title="Slack Alerts" icon="slack" iconType="brands" href="/documentation/platform/pki/applications/alerting/slack-alerts">+ <Card title="Slack" icon="slack" iconType="brands" href="/documentation/platform/pki/applications/alerting/slack-alerts">Send alerts to a Slack channel.</Card>- <Card title="PagerDuty Alerts" icon="radio-tower" href="/documentation/platform/pki/applications/alerting/pagerduty-alerts">+ <Card title="PagerDuty" icon="radio-tower" href="/documentation/platform/pki/applications/alerting/pagerduty-alerts">Create incidents in PagerDuty.</Card>- <Card title="Certificate Syncs" icon="refresh-cw" href="/documentation/platform/pki/applications/certificate-syncs/overview">+ <Card title="Certificate syncs" icon="refresh-cw" href="/documentation/platform/pki/applications/certificate-syncs/overview">Push certificates to cloud destinations.</Card>- <Card title="Managing Certificates" icon="list" href="/documentation/platform/pki/applications/certificates">+ <Card title="Certificates" icon="list" href="/documentation/platform/pki/applications/certificates">View and manage certificates.</Card></CardGroup>diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.tsindex 182344fcab..9d3de11e1d 100644--- a/frontend/src/hooks/api/alerts/types.ts+++ b/frontend/src/hooks/api/alerts/types.ts@@ -18,11 +18,30 @@ export enum AlertChannelType {export enum AlertPrincipalType {User = "user",- Group = "group"+ Group = "group",+ Email = "email"+}++export enum AlertRunStatus {+ Success = "success",+ Partial = "partial",+ Failed = "failed"+}++export enum CertificateAlertResourceType {+ Application = "cert-manager.application"+}++export enum CertificateAlertEventType {+ Expiry = "cert-manager.application.certificate.expiry",+ Issuance = "cert-manager.application.certificate.issuance",+ Renewal = "cert-manager.application.certificate.renewal",+ Revocation = "cert-manager.application.certificate.revocation"}export const MIN_ALERT_BEFORE_DAYS = 1;export const MAX_ALERT_BEFORE_DAYS = 90;+export const MAX_CERTIFICATE_ALERT_BEFORE_DAYS = 365;export const ALERT_RESOURCE_TYPE_LABELS: Record<AlertResourceType, string> = {[AlertResourceType.IdentityAuthentication]: "Machine Identity Authentication"@@ -72,7 +91,9 @@ export type TAlert = {enabled: boolean;orgId: string;projectId: string | null;+ resourceName: string | null;channels: TAlertChannelEmbedded[];+ lastRun: { timestamp: string; status: AlertRunStatus } | null;createdAt: string;updatedAt: string;};diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex fa7793a6c0..43c2786fb3 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -116,6 +116,10 @@ export const eventToNameMap: { [K in EventType]: string } = {[EventType.GET_PKI_ALERT]: "Get PKI alert",[EventType.UPDATE_PKI_ALERT]: "Update PKI alert",[EventType.DELETE_PKI_ALERT]: "Delete PKI alert",+ [EventType.CREATE_ALERT]: "Create alert",+ [EventType.UPDATE_ALERT]: "Update alert",+ [EventType.DELETE_ALERT]: "Delete alert",+ [EventType.TEST_ALERT_CHANNEL]: "Test alert channel",[EventType.CREATE_PKI_COLLECTION]: "Create PKI collection",[EventType.GET_PKI_COLLECTION]: "Get PKI collection",[EventType.UPDATE_PKI_COLLECTION]: "Update PKI collection",diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsxindex e7aee8583a..83fe5f4869 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -132,6 +132,10 @@ export enum EventType {GET_PKI_ALERT = "get-pki-alert",UPDATE_PKI_ALERT = "update-pki-alert",DELETE_PKI_ALERT = "delete-pki-alert",+ CREATE_ALERT = "create-alert",+ UPDATE_ALERT = "update-alert",+ DELETE_ALERT = "delete-alert",+ TEST_ALERT_CHANNEL = "test-alert-channel",CREATE_PKI_COLLECTION = "create-pki-collection",GET_PKI_COLLECTION = "get-pki-collection",UPDATE_PKI_COLLECTION = "update-pki-collection",diff --git a/frontend/src/hooks/api/pkiAlertsV2/index.ts b/frontend/src/hooks/api/pkiAlertsV2/index.tsindex 227496462c..240e04ef3a 100644--- a/frontend/src/hooks/api/pkiAlertsV2/index.ts+++ b/frontend/src/hooks/api/pkiAlertsV2/index.ts@@ -1,9 +1,4 @@-export {- useCreatePkiAlertV2,- useDeletePkiAlertV2,- useTestPkiWebhookConfigV2,- useUpdatePkiAlertV2-} from "./mutations";+export { useDeletePkiAlertV2 } from "./mutations";export {pkiAlertsV2Keys,useGetPkiAlertsV2,@@ -12,7 +7,6 @@ export {useGetPkiAlertV2MatchingCertificates} from "./queries";export type {- TCreatePkiAlertV2,TDeletePkiAlertV2,TGetPkiAlertsV2,TGetPkiAlertV2ById,@@ -26,15 +20,11 @@ export type {TPkiAlertChannelConfigWebhookResponse,TPkiAlertChannelV2,TPkiAlertV2,- TPkiFilterRuleV2,- TUpdatePkiAlertV2+ TPkiFilterRuleV2} from "./types";export {- createPkiAlertV2Schema,PkiAlertChannelTypeV2,PkiAlertEventTypeV2,PkiFilterFieldV2,- PkiFilterOperatorV2,- SECRET_MASK,- updatePkiAlertV2Schema+ PkiFilterOperatorV2} from "./types";diff --git a/frontend/src/hooks/api/pkiAlertsV2/mutations.ts b/frontend/src/hooks/api/pkiAlertsV2/mutations.tsindex 6043d3fec7..5710c0bbcc 100644--- a/frontend/src/hooks/api/pkiAlertsV2/mutations.ts+++ b/frontend/src/hooks/api/pkiAlertsV2/mutations.ts@@ -3,65 +3,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";import { pkiAlertsV2Keys } from "./queries";-import { TCreatePkiAlertV2, TDeletePkiAlertV2, TPkiAlertV2, TUpdatePkiAlertV2 } from "./types";--export const useCreatePkiAlertV2 = () => {- const queryClient = useQueryClient();-- return useMutation<TPkiAlertV2, unknown, TCreatePkiAlertV2>({- mutationFn: async (data) => {- if (data.applicationId) {- const { applicationId, ...rest } = data;- const { data: response } = await apiRequest.post<{ alert: TPkiAlertV2 }>(- `/api/v1/cert-manager/applications/${applicationId}/alerts`,- rest- );- return response.alert;- }- const { data: response } = await apiRequest.post<{ alert: TPkiAlertV2 }>(- "/api/v1/cert-manager/alerts",- data- );- return response.alert;- },- onSuccess: (_, variables) => {- queryClient.invalidateQueries({- queryKey: pkiAlertsV2Keys.allPkiAlertsV2({- applicationId: variables.applicationId- })- });- }- });-};--export const useUpdatePkiAlertV2 = () => {- const queryClient = useQueryClient();-- return useMutation<TPkiAlertV2, unknown, TUpdatePkiAlertV2 & { applicationId?: string }>({- mutationFn: async ({ alertId, applicationId, ...data }) => {- if (applicationId) {- const { data: response } = await apiRequest.patch<{ alert: TPkiAlertV2 }>(- `/api/v1/cert-manager/applications/${applicationId}/alerts/${alertId}`,- data- );- return response.alert;- }- const { data: response } = await apiRequest.patch<{ alert: TPkiAlertV2 }>(- `/api/v1/cert-manager/alerts/${alertId}`,- data- );- return response.alert;- },- onSuccess: (_, variables) => {- queryClient.invalidateQueries({- queryKey: pkiAlertsV2Keys.specificPkiAlertV2(variables.alertId)- });- queryClient.invalidateQueries({- queryKey: pkiAlertsV2Keys.all- });- }- });-};+import { TDeletePkiAlertV2, TPkiAlertV2 } from "./types";export const useDeletePkiAlertV2 = () => {const queryClient = useQueryClient();@@ -89,26 +31,3 @@ export const useDeletePkiAlertV2 = () => {}});};--export interface TTestPkiWebhookConfigV2 {- url: string;- signingSecret?: string;- applicationId?: string;-}--export interface TTestPkiWebhookConfigV2Response {- success: boolean;- error?: string;-}--export const useTestPkiWebhookConfigV2 = () => {- return useMutation<TTestPkiWebhookConfigV2Response, unknown, TTestPkiWebhookConfigV2>({- mutationFn: async ({ url, signingSecret, applicationId }) => {- const { data } = await apiRequest.post<TTestPkiWebhookConfigV2Response>(- "/api/v2/pki/alerts/test-webhook",- { url, signingSecret, ...(applicationId ? { applicationId } : {}) }- );- return data;- }- });-};diff --git a/frontend/src/hooks/api/pkiAlertsV2/types.ts b/frontend/src/hooks/api/pkiAlertsV2/types.tsindex 22c2ab880f..9d44b1068e 100644--- a/frontend/src/hooks/api/pkiAlertsV2/types.ts+++ b/frontend/src/hooks/api/pkiAlertsV2/types.ts@@ -1,8 +1,3 @@-import { z } from "zod";--// Sentinel value for masked secrets in edit mode (signing secret, integration key, etc.)-export const SECRET_MASK = "*****";-export enum PkiAlertEventTypeV2 {EXPIRATION = "expiration",RENEWAL = "renewal",@@ -76,10 +71,6 @@ export interface TPkiAlertChannelV2 {updatedAt: string;}-export type TPkiAlertChannelInput = Omit<TPkiAlertChannelV2, "createdAt" | "updatedAt" | "id"> & {- id?: string;-};-export interface TLastRun {timestamp: string;status: "success" | "failed";@@ -133,30 +124,6 @@ export interface TGetPkiAlertV2ById {alertId: string;}-export interface TCreatePkiAlertV2 {- applicationId?: string;- name: string;- description?: string;- eventType: PkiAlertEventTypeV2;- alertBefore?: string;- filters: TPkiFilterRuleV2[];- enabled?: boolean;- notificationConfig?: { enableDailyNotification: boolean } | null;- channels: TPkiAlertChannelInput[];-}--export interface TUpdatePkiAlertV2 {- alertId: string;- name?: string;- description?: string;- eventType?: PkiAlertEventTypeV2;- alertBefore?: string;- filters?: TPkiFilterRuleV2[];- enabled?: boolean;- notificationConfig?: { enableDailyNotification: boolean } | null;- channels?: TPkiAlertChannelInput[];-}-export interface TDeletePkiAlertV2 {alertId: string;}@@ -187,130 +154,3 @@ export interface TGetPkiAlertV2CurrentMatchingCertificatesResponse {limit: number;offset: number;}--export const pkiFilterRuleV2Schema = z.object({- field: z.nativeEnum(PkiFilterFieldV2),- operator: z.nativeEnum(PkiFilterOperatorV2),- value: z.union([z.string(), z.array(z.string()), z.boolean()])-});--const emailChannelConfigSchema = z.object({- recipients: z- .array(z.string())- .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"- )-});--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)-});--const slackChannelConfigSchema = z.object({- webhookUrl: z- .string()- .url("Must be a valid URL")- .refine((url) => url.startsWith("https://"), "Slack webhook URL must use HTTPS")- .refine((url) => {- try {- const parsed = new URL(url);- return parsed.hostname === "hooks.slack.com";- } catch {- return false;- }- }, "Slack webhook URL must be from hooks.slack.com")-});--const slackChannelSchema = z.object({- id: z.string().uuid().optional(),- channelType: z.literal(PkiAlertChannelTypeV2.SLACK),- config: slackChannelConfigSchema,- enabled: z.boolean().default(true)-});--const pagerdutyChannelConfigSchema = z.object({- integrationKey: z- .string()- .refine(- (val) => /^[a-f0-9]{32}$/i.test(val),- "Integration key must be a 32-character hex string"- )-});--const pagerdutyChannelSchema = z.object({- id: z.string().uuid().optional(),- channelType: z.literal(PkiAlertChannelTypeV2.PAGERDUTY),- config: pagerdutyChannelConfigSchema,- enabled: z.boolean().default(true)-});--export const pkiAlertChannelV2Schema = z.discriminatedUnion("channelType", [- emailChannelSchema,- webhookChannelSchema,- slackChannelSchema,- pagerdutyChannelSchema-]);--const basePkiAlertV2Schema = z.object({- applicationId: z.string().uuid().optional(),- name: z- .string()- .min(1)- .max(255)- .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Must be a valid name (lowercase, numbers, hyphens only)"),- description: z.string().max(1000).optional(),- eventType: z.nativeEnum(PkiAlertEventTypeV2),- alertBefore: z- .string()- .regex(/^\d+[dwmy]$/, "Must be in format like '30d', '1w', '3m', '1y'")- .refine((val) => val.length <= 32, "Alert timing too long")- .optional(),- filters: z.array(pkiFilterRuleV2Schema),- enabled: z.boolean().default(true),- notificationConfig: z.object({ enableDailyNotification: z.boolean() }).nullable().optional(),- 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 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();diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsxnew file mode 100644index 0000000000..e3a55b51c6--- /dev/null+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx@@ -0,0 +1,340 @@+import { useState } from "react";+import {+ BellIcon,+ CircleStopIcon,+ EyeIcon,+ InfoIcon,+ MoreHorizontalIcon,+ PencilIcon,+ PlayIcon,+ PlusIcon,+ Trash2Icon+} from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Badge,+ Button,+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ DeleteConfirmDialog,+ DocumentationLinkBadge,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ Empty,+ EmptyDescription,+ EmptyMedia,+ IconButton,+ Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import {+ AlertRunStatus,+ CertificateAlertEventType,+ CertificateAlertResourceType,+ TAlert,+ useDeleteAlert,+ useListAlerts,+ useUpdateAlert+} from "@app/hooks/api/alerts";++import { PkiDocsUrls } from "../../../pki-docs-urls";+import { CertificateAlertSheet } from "./CertificateAlertSheet";+import { CERTIFICATE_ALERT_EVENT_LABELS, formatAlertBefore } from "./types";++const LAST_RUN_BADGES: Record<+ AlertRunStatus,+ { label: string; variant: "success" | "warning" | "danger" }+> = {+ [AlertRunStatus.Success]: { label: "Success", variant: "success" },+ [AlertRunStatus.Partial]: { label: "Partial", variant: "warning" },+ [AlertRunStatus.Failed]: { label: "Failed", variant: "danger" }+};++type AlertRowProps = {+ alert: TAlert;+ onView: () => void;+ onEdit: () => void;+ onDelete: () => void;+ canEdit: boolean;+ canDelete: boolean;+};++const AlertRow = ({ alert, onView, onEdit, onDelete, canEdit, canDelete }: AlertRowProps) => {+ const { mutate: updateAlert } = useUpdateAlert();++ const handleToggleAlert = () =>+ updateAlert(+ { alertId: alert.id, enabled: !alert.enabled },+ {+ onSuccess: () =>+ createNotification({+ text: `Alert "${alert.name}" ${alert.enabled ? "disabled" : "enabled"}`,+ type: "success"+ })+ }+ );++ return (+ <TableRow>+ <TableCell isTruncatable>+ <div className="flex items-center gap-2">+ <span className="font-medium text-foreground">{alert.name}</span>+ {alert.description ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <InfoIcon className="size-3.5 shrink-0 text-accent" />+ </TooltipTrigger>+ <TooltipContent side="right" className="max-w-xs">+ {alert.description}+ </TooltipContent>+ </Tooltip>+ ) : null}+ </div>+ </TableCell>+ <TableCell className="whitespace-nowrap text-accent">+ {CERTIFICATE_ALERT_EVENT_LABELS[alert.eventType as CertificateAlertEventType] ??+ alert.eventType}+ </TableCell>+ <TableCell className="whitespace-nowrap">+ <Badge variant={alert.enabled ? "success" : "neutral"}>+ {alert.enabled ? "Enabled" : "Disabled"}+ </Badge>+ </TableCell>+ <TableCell className="whitespace-nowrap text-accent">+ {alert.condition?.alertBefore ? (+ formatAlertBefore(alert.condition.alertBefore)+ ) : (+ <span className="text-surface-selected">—</span>+ )}+ </TableCell>+ <TableCell className="whitespace-nowrap">+ {alert.lastRun ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant={LAST_RUN_BADGES[alert.lastRun.status].variant}>+ {LAST_RUN_BADGES[alert.lastRun.status].label}+ </Badge>+ </TooltipTrigger>+ <TooltipContent side="left" className="max-w-sm">+ <div className="text-xs text-label">+ {new Date(alert.lastRun.timestamp)+ .toISOString()+ .replace("T", " ")+ .replace("Z", " UTC")}+ </div>+ </TooltipContent>+ </Tooltip>+ ) : (+ <span className="text-surface-selected">—</span>+ )}+ </TableCell>+ <TableCell className="text-right">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton variant="ghost" size="xs" aria-label="Alert actions">+ <MoreHorizontalIcon />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent className="min-w-44" align="end" sideOffset={2}>+ {!canEdit && (+ <DropdownMenuItem onClick={onView}>+ <EyeIcon />+ View details+ </DropdownMenuItem>+ )}+ <DropdownMenuItem isDisabled={!canEdit} onClick={onEdit}>+ <PencilIcon />+ Edit alert+ </DropdownMenuItem>+ <DropdownMenuItem isDisabled={!canEdit} onClick={handleToggleAlert}>+ {alert.enabled ? <CircleStopIcon /> : <PlayIcon />}+ {alert.enabled ? "Disable" : "Enable"} alert+ </DropdownMenuItem>+ <DropdownMenuItem variant="danger" isDisabled={!canDelete} onClick={onDelete}>+ <Trash2Icon />+ Delete alert+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </TableCell>+ </TableRow>+ );+};++type Props = {+ projectId: string;+ applicationId: string;+ applicationName: string;+ canCreate: boolean;+ canEdit: boolean;+ canDelete: boolean;+};++export const ApplicationAlertsCard = ({+ projectId,+ applicationId,+ applicationName,+ canCreate,+ canEdit,+ canDelete+}: Props) => {+ const { data: alerts = [], isLoading: isAlertsLoading } = useListAlerts({+ resourceType: CertificateAlertResourceType.Application,+ projectId,+ resourceId: applicationId+ });+ const [alertModal, setAlertModal] = useState<{+ isOpen: boolean;+ alertId?: string;+ isReadOnly?: boolean;+ }>({+ isOpen: false+ });+ const [deleteAlertModal, setDeleteAlertModal] = useState<{+ isOpen: boolean;+ alertId?: string;+ name?: string;+ }>({ isOpen: false });+ const { mutateAsync: deleteAlert } = useDeleteAlert();++ const usedEventTypes = alerts.map((a) => a.eventType as CertificateAlertEventType);+ const hasAllEventTypes = Object.values(CertificateAlertEventType).every((event) =>+ usedEventTypes.includes(event)+ );++ const handleDeleteAlert = async () => {+ if (!deleteAlertModal.alertId) return;+ await deleteAlert({ alertId: deleteAlertModal.alertId });+ setDeleteAlertModal({ isOpen: false });+ createNotification({ type: "success", text: `Alert "${deleteAlertModal.name}" deleted` });+ };++ return (+ <>+ <Card>+ <CardHeader>+ <CardTitle>+ Alerting+ <DocumentationLinkBadge href={PkiDocsUrls.applications.alerting.overview} />+ </CardTitle>+ <CardDescription>Get notified about certificate events.</CardDescription>+ <CardAction>+ <Tooltip>+ <TooltipTrigger asChild>+ {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- focusable wrapper required so the tooltip surfaces on keyboard focus despite the inner button being disabled */}+ <span tabIndex={0}>+ <Button+ variant="outline"+ onClick={() => setAlertModal({ isOpen: true })}+ isDisabled={!canCreate || hasAllEventTypes}+ >+ <PlusIcon />+ Create Alert+ </Button>+ </span>+ </TooltipTrigger>+ {!canCreate && (+ <TooltipContent side="left">+ You don't have permission to create alerts+ </TooltipContent>+ )}+ {canCreate && hasAllEventTypes && (+ <TooltipContent side="left">+ This application already has an alert for every alert type+ </TooltipContent>+ )}+ </Tooltip>+ </CardAction>+ </CardHeader>+ <CardContent>+ {!isAlertsLoading && alerts.length === 0 ? (+ <Empty className="border">+ <EmptyMedia variant="icon">+ <BellIcon />+ </EmptyMedia>+ <EmptyDescription>+ No alerts configured. Create one to get notified about certificate events for this+ application.+ </EmptyDescription>+ </Empty>+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-1/3">Name</TableHead>+ <TableHead className="whitespace-nowrap">Alert Type</TableHead>+ <TableHead className="whitespace-nowrap">Status</TableHead>+ <TableHead className="whitespace-nowrap">Alert Before</TableHead>+ <TableHead className="whitespace-nowrap">Last Run</TableHead>+ <TableHead className="w-5 text-right">Actions</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {isAlertsLoading &&+ Array.from({ length: 3 }, (_, idx) => (+ <TableRow key={`alert-skeleton-${idx + 1}`}>+ {Array.from({ length: 6 }, (__, cellIdx) => (+ <TableCell key={`alert-skeleton-cell-${cellIdx + 1}`}>+ <Skeleton className="h-4 w-24" />+ </TableCell>+ ))}+ </TableRow>+ ))}+ {!isAlertsLoading &&+ alerts.map((a) => (+ <AlertRow+ key={a.id}+ alert={a}+ onView={() =>+ setAlertModal({ isOpen: true, alertId: a.id, isReadOnly: true })+ }+ onEdit={() => setAlertModal({ isOpen: true, alertId: a.id })}+ onDelete={() =>+ setDeleteAlertModal({ isOpen: true, alertId: a.id, name: a.name })+ }+ canEdit={canEdit}+ canDelete={canDelete}+ />+ ))}+ </TableBody>+ </Table>+ )}+ </CardContent>+ </Card>+ <CertificateAlertSheet+ isOpen={alertModal.isOpen}+ onOpenChange={(isOpen) => setAlertModal({ isOpen, alertId: undefined })}+ projectId={projectId}+ applicationId={applicationId}+ applicationName={applicationName}+ alert={alerts.find((a) => a.id === alertModal.alertId)}+ isReadOnly={alertModal.isReadOnly}+ usedEventTypes={usedEventTypes}+ />+ <DeleteConfirmDialog+ isOpen={deleteAlertModal.isOpen}+ confirmKey="delete"+ title={`Delete Alert "${deleteAlertModal.name ?? ""}"?`}+ onOpenChange={(isOpen) =>+ setDeleteAlertModal({ isOpen, alertId: undefined, name: undefined })+ }+ onConfirm={handleDeleteAlert}+ />+ </>+ );+};diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsxnew file mode 100644index 0000000000..ccdfeafe25--- /dev/null+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx@@ -0,0 +1,286 @@+import { useMemo, useState } from "react";+import { FormProvider, useFieldArray, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { BellIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetHeader,+ SheetTitle,+ Spinner,+ Stepper,+ StepperList,+ StepperStep+} from "@app/components/v3";+import { useGetWorkspaceUsers } from "@app/hooks/api";+import {+ AlertChannelType,+ CertificateAlertEventType,+ CertificateAlertResourceType,+ TAlert,+ toChannelInput,+ useCreateAlert,+ useUpdateAlert+} from "@app/hooks/api/alerts";+import { buildNewChannel, getNextChannelName } from "@app/views/Alerts";++import { CertificateAlertAddChannelMenu, ChannelsStep } from "./ChannelsStep";+import { DetailsStep } from "./DetailsStep";+import { ReviewStep } from "./ReviewStep";+import {+ certificateAlertFormSchema,+ emptyCertificateAlertForm,+ STEP_FIELDS,+ STEPS,+ TCertificateAlertForm,+ toCertificateAlertForm,+ toCondition,+ TProjectMemberEmails+} from "./types";++type Props = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+ projectId: string;+ applicationId: string;+ applicationName: string;+ alert?: TAlert;+ isReadOnly?: boolean;+ usedEventTypes: CertificateAlertEventType[];+};++type WizardProps = Omit<Props, "isOpen"> & { members: TProjectMemberEmails };++const CertificateAlertWizard = ({+ onOpenChange,+ projectId,+ applicationId,+ applicationName,+ alert,+ isReadOnly = false,+ usedEventTypes,+ members+}: WizardProps) => {+ const isEditing = Boolean(alert);+ const [step, setStep] = useState(isReadOnly ? STEPS.length - 1 : 0);+ const createAlert = useCreateAlert();+ const updateAlert = useUpdateAlert();++ const form = useForm<TCertificateAlertForm>({+ resolver: zodResolver(certificateAlertFormSchema),+ mode: "onChange",+ defaultValues: alert+ ? toCertificateAlertForm(alert, members)+ : emptyCertificateAlertForm(+ Object.values(CertificateAlertEventType).find((event) => !usedEventTypes.includes(event))+ )+ });+ const { fields, append, remove } = useFieldArray({ control: form.control, name: "channels" });++ const onSubmit = async (values: TCertificateAlertForm) => {+ const channels = values.channels.map(toChannelInput);+ const condition = toCondition(values);++ try {+ if (alert) {+ await updateAlert.mutateAsync({+ alertId: alert.id,+ name: values.name,+ description: values.description || null,+ enabled: values.enabled,+ condition,+ channels+ });+ createNotification({ type: "success", text: `Alert "${values.name}" updated` });+ } else {+ await createAlert.mutateAsync({+ name: values.name,+ description: values.description || undefined,+ resourceType: CertificateAlertResourceType.Application,+ resourceId: applicationId,+ eventType: values.eventType,+ condition,+ enabled: values.enabled,+ projectId,+ channels+ });+ createNotification({ type: "success", text: `Alert "${values.name}" created` });+ }+ onOpenChange(false);+ } catch {+ // MutationCache reports request errors globally; keep the sheet open for another attempt.+ }+ };++ const addChannel = (channelType: AlertChannelType) => {+ const takenNames = new Set(form.getValues("channels").map((channel) => channel.name));+ append(buildNewChannel(channelType, getNextChannelName(takenNames, channelType)));+ };++ const goNext = async () => {+ if (step < STEP_FIELDS.length) {+ if (await form.trigger(STEP_FIELDS[step])) setStep(step + 1);+ return;+ }+ await form.handleSubmit(onSubmit)();+ };++ const isLast = step === STEPS.length - 1;+ const { isSubmitting } = form.formState;+ const currentStep = STEPS[step];+ const submitLabel = isEditing ? "Update Alert" : "Create Alert";+ let title = isEditing ? "Edit Certificate Alert" : "Create Certificate Alert";+ if (isReadOnly) title = "Certificate Alert Details";++ return (+ <FormProvider {...form}>+ <SheetHeader className="border-b">+ <SheetTitle>+ <div className="flex w-full items-start gap-3">+ <div className="flex h-10 w-10 items-center justify-center rounded-md bg-project/10 text-project">+ <BellIcon className="h-5 w-5" />+ </div>+ <div>+ <div className="text-label">{title}</div>+ <SheetDescription className="leading-4 text-muted">+ Get notified about certificate events in {applicationName}.+ </SheetDescription>+ </div>+ </div>+ </SheetTitle>+ </SheetHeader>++ <div className="flex min-h-0 flex-1 overflow-hidden">+ {!isReadOnly && (+ <aside className="flex w-64 shrink-0 flex-col border-r border-border px-5 py-6">+ <p className="mb-5 text-sm text-muted">Setup Steps</p>+ <Stepper+ activeStep={step}+ orientation="vertical"+ onStepChange={(index) => {+ if (index < step) setStep(index);+ }}+ >+ <StepperList>+ {STEPS.map((item, index) => (+ <StepperStep+ key={item.name}+ index={index}+ title={item.name}+ description={item.shortDescription}+ />+ ))}+ </StepperList>+ </Stepper>+ </aside>+ )}++ <div className="flex min-w-0 flex-1 flex-col overflow-y-auto px-8 py-6">+ <div className="mb-6 flex items-start justify-between gap-4">+ <div>+ <h2 className="text-lg font-semibold text-foreground">{currentStep.title}</h2>+ {!isReadOnly && <p className="mt-1 text-sm text-muted">{currentStep.subtitle}</p>}+ </div>+ {step === 1 && (+ <CertificateAlertAddChannelMenu channelCount={fields.length} onAdd={addChannel} />+ )}+ </div>++ {step === 0 && (+ <DetailsStep form={form} isEditing={isEditing} usedEventTypes={usedEventTypes} />+ )}+ {step === 1 && (+ <ChannelsStep+ form={form}+ fields={fields}+ onRemove={remove}+ projectId={projectId}+ applicationId={applicationId}+ members={members}+ />+ )}+ {step === 2 && <ReviewStep form={form} members={members} />}+ </div>+ </div>++ <div className="flex shrink-0 items-center justify-between gap-3 border-t border-border px-6 py-4">+ {isReadOnly ? (+ <Button variant="outline" className="ml-auto" onClick={() => onOpenChange(false)}>+ Close+ </Button>+ ) : (+ <>+ <span className="text-xs text-muted">+ Step {step + 1} of {STEPS.length}+ </span>+ <div className="flex items-center gap-3">+ {step > 0 && (+ <Button variant="outline" onClick={() => setStep((current) => current - 1)}>+ Back+ </Button>+ )}+ <Button+ variant="project"+ onClick={goNext}+ isPending={isSubmitting}+ isDisabled={isSubmitting}+ >+ {isLast ? submitLabel : "Continue"}+ </Button>+ </div>+ </>+ )}+ </div>+ </FormProvider>+ );+};++export const CertificateAlertSheet = ({ isOpen, onOpenChange, ...props }: Props) => {+ const { data: projectUsers, isPending: isUsersPending } = useGetWorkspaceUsers(+ props.projectId,+ true,+ undefined,+ { enabled: isOpen }+ );++ const members = useMemo((): TProjectMemberEmails => {+ const byUserId = new Map<string, string>();+ const byEmail = new Map<string, string>();+ (projectUsers ?? []).forEach(({ user }) => {+ if (!user.isOrgMembershipActive || user.isOrgMembershipPending) return;+ const email = (user.email || user.username || "").toLowerCase();+ if (!email) return;+ byUserId.set(user.id, email);+ byEmail.set(email, user.id);+ });+ return {+ emailByUserId: byUserId,+ memberIdByEmail: byEmail,+ isAvailable: Boolean(projectUsers)+ };+ }, [projectUsers]);++ return (+ <Sheet open={isOpen} onOpenChange={onOpenChange}>+ <SheetContent size="wide" className="flex h-full max-h-full flex-col gap-y-0">+ {isOpen && isUsersPending && (+ <div className="flex flex-1 items-center justify-center">+ <Spinner />+ </div>+ )}+ {isOpen && !isUsersPending && (+ <CertificateAlertWizard+ key={props.alert?.id ?? "new"}+ onOpenChange={onOpenChange}+ members={members}+ {...props}+ />+ )}+ </SheetContent>+ </Sheet>+ );+};diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsxnew file mode 100644index 0000000000..ab32fa6b7c--- /dev/null+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx@@ -0,0 +1,179 @@+import { useState } from "react";+import { FieldArrayWithId, UseFormReturn } from "react-hook-form";+import { BellIcon } from "lucide-react";++import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";+import {+ Combobox,+ Empty,+ EmptyDescription,+ EmptyMedia,+ FieldDescription,+ FieldError+} from "@app/components/v3";+import { useSubscription } from "@app/context";+import { isValidEmail } from "@app/helpers/email";+import {+ AlertChannelType,+ AlertPrincipalType,+ CertificateAlertResourceType+} from "@app/hooks/api/alerts";+import { AddChannelMenu, ChannelCard, TChannelRecipientsRenderProps } from "@app/views/Alerts";++import {+ MAX_CHANNELS,+ normalizeEmail,+ TCertificateAlertForm,+ toRecipientEmails,+ TProjectMemberEmails+} from "./types";++type TChannelField = FieldArrayWithId<TCertificateAlertForm, "channels">;++const ENTERPRISE_CHANNEL_TYPES = [+ AlertChannelType.Slack,+ AlertChannelType.Webhook,+ AlertChannelType.PagerDuty+];++export const CertificateAlertAddChannelMenu = ({+ channelCount,+ onAdd+}: {+ channelCount: number;+ onAdd: (channelType: AlertChannelType) => void;+}) => {+ const { subscription } = useSubscription();+ const [isUpgradeOpen, setIsUpgradeOpen] = useState(false);+ const isEnterpriseAllowed = Boolean(subscription?.pkiEnterpriseAlerting);++ return (+ <>+ <AddChannelMenu+ onAdd={onAdd}+ isDisabled={channelCount >= MAX_CHANNELS}+ lockedChannelTypes={isEnterpriseAllowed ? [] : ENTERPRISE_CHANNEL_TYPES}+ onLockedSelect={() => setIsUpgradeOpen(true)}+ />+ <UpgradePlanModal+ isOpen={isUpgradeOpen}+ onOpenChange={setIsUpgradeOpen}+ paywallKey="cert-manager.application-alert-channels"+ text="Webhook, Slack, and PagerDuty alert channels are available on the Enterprise plan."+ isEnterpriseFeature+ />+ </>+ );+};++const EmailRecipientsField = ({+ value,+ onChange,+ isError,+ members+}: TChannelRecipientsRenderProps & { members: TProjectMemberEmails }) => {+ const emails = toRecipientEmails(value, members);+ const groups = value.filter((recipient) => recipient.principalType === AlertPrincipalType.Group);+ const unlistedUsers = value.filter(+ (recipient) =>+ recipient.principalType === AlertPrincipalType.User &&+ !members.emailByUserId.has(recipient.principalId)+ );+ const memberEmails = [...members.memberIdByEmail.keys()].sort();++ const setEmails = (nextEmails: string[]) =>+ onChange([+ ...nextEmails.map((email) => {+ const userId = members.memberIdByEmail.get(email);+ return userId+ ? { principalType: AlertPrincipalType.User, principalId: userId }+ : { principalType: AlertPrincipalType.Email, principalId: email };+ }),+ ...unlistedUsers,+ ...groups+ ]);++ return (+ <>+ <Combobox+ multiple+ modal+ includeMissingSelectedOptions+ options={memberEmails}+ value={emails}+ onValueChange={setEmails}+ getOptionValue={(email) => email}+ getOptionLabel={(email) => email}+ placeholder="Select members or type an email..."+ emptyMessage="No matching members. Type a full email to add it."+ isError={isError}+ creation={{+ isValid: (inputValue) => isValidEmail(normalizeEmail(inputValue)),+ isDuplicate: (inputValue, email) => normalizeEmail(inputValue) === email,+ formatLabel: (inputValue) => `Add "${normalizeEmail(inputValue)}"`,+ onCreate: (inputValue) => {+ const email = normalizeEmail(inputValue);+ if (!emails.includes(email)) setEmails([...emails, email]);+ }+ }}+ />+ <FieldDescription>+ Pick Certificate Manager members or type any email address. Other addresses must use one of+ your organization's verified email domains.+ {unlistedUsers.length > 0 && ` Also sent to ${unlistedUsers.length} member(s).`}+ {groups.length > 0 && ` Also sent to ${groups.length} group(s).`}+ </FieldDescription>+ </>+ );+};++export const ChannelsStep = ({+ form,+ fields,+ onRemove,+ projectId,+ applicationId,+ members+}: {+ form: UseFormReturn<TCertificateAlertForm>;+ fields: TChannelField[];+ onRemove: (index: number) => void;+ projectId: string;+ applicationId: string;+ members: TProjectMemberEmails;+}) => {+ const channelsError = form.formState.errors.channels?.root ?? form.formState.errors.channels;++ if (!fields.length) {+ return (+ <div className="flex flex-col gap-2">+ <Empty className="border">+ <EmptyMedia variant="icon">+ <BellIcon />+ </EmptyMedia>+ <EmptyDescription>+ Select "Add Channel" to choose where this alert is sent.+ </EmptyDescription>+ </Empty>+ <FieldError errors={[channelsError as { message?: string } | undefined]} />+ </div>+ );+ }++ return (+ <div className="flex flex-col gap-4">+ {fields.map((field, index) => (+ <ChannelCard+ key={field.id}+ index={index}+ projectId={projectId}+ resourceType={CertificateAlertResourceType.Application}+ resourceId={applicationId}+ canRemove+ onRemove={() => onRemove(index)}+ renderRecipients={(props) => <EmailRecipientsField {...props} members={members} />}+ />+ ))}+ </div>+ );+};diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/DetailsStep.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/DetailsStep.tsxnew file mode 100644index 0000000000..e9f1553b99--- /dev/null+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/DetailsStep.tsx@@ -0,0 +1,149 @@+import { Controller, UseFormReturn, useWatch } from "react-hook-form";++import {+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldGroup,+ FieldLabel,+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ TextArea,+ Toggle+} from "@app/components/v3";+import { CertificateAlertEventType } from "@app/hooks/api/alerts";++import {+ CERTIFICATE_ALERT_EVENT_DESCRIPTIONS,+ CERTIFICATE_ALERT_EVENT_LABELS,+ TCertificateAlertForm+} from "./types";++type Props = {+ form: UseFormReturn<TCertificateAlertForm>;+ isEditing: boolean;+ usedEventTypes: CertificateAlertEventType[];+};++export const DetailsStep = ({ form, isEditing, usedEventTypes }: Props) => {+ const eventType = useWatch({ control: form.control, name: "eventType" });++ return (+ <FieldGroup>+ <Controller+ name="eventType"+ control={form.control}+ render={({ field }) => (+ <Field>+ <FieldLabel>Alert Type</FieldLabel>+ <FieldContent>+ <Select value={field.value} onValueChange={field.onChange} disabled={isEditing}>+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ {Object.values(CertificateAlertEventType).map((event) => (+ <SelectItem+ key={event}+ value={event}+ disabled={!isEditing && usedEventTypes.includes(event)}+ >+ {CERTIFICATE_ALERT_EVENT_LABELS[event]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldDescription>+ {CERTIFICATE_ALERT_EVENT_DESCRIPTIONS[field.value]}+ </FieldDescription>+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ name="name"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Alert Name</FieldLabel>+ <FieldContent>+ <Input+ {...field}+ placeholder="e.g. tls-expiry-alert"+ isError={Boolean(error)}+ autoComplete="off"+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ name="description"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Description (Optional)</FieldLabel>+ <FieldContent>+ <TextArea+ {...field}+ placeholder="Alert description..."+ rows={3}+ isError={Boolean(error)}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ {eventType === CertificateAlertEventType.Expiry && (+ <>+ <Controller+ name="alertBefore"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Alert Before</FieldLabel>+ <FieldContent>+ <Input {...field} placeholder="30d" isError={Boolean(error)} autoComplete="off" />+ <FieldDescription>+ Format: number + unit (d=days, w=weeks, m=months, y=years). Example: 30d+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ name="dailyReminder"+ control={form.control}+ render={({ field }) => (+ <Field orientation="horizontal">+ <FieldContent>+ <FieldLabel htmlFor="certificate-alert-daily-reminder">+ Repeat daily until expiry+ </FieldLabel>+ <FieldDescription>+ Send a reminder every day from the alert threshold until the certificate+ expires.+ </FieldDescription>+ </FieldContent>+ <Toggle+ id="certificate-alert-daily-reminder"+ variant="project"+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </Field>+ )}+ />+ </>+ )}+ </FieldGroup>+ );+};diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/LegacyApplicationAlertsCard.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/LegacyApplicationAlertsCard.tsxnew file mode 100644index 0000000000..f7d2da24ec--- /dev/null+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/LegacyApplicationAlertsCard.tsx@@ -0,0 +1,190 @@+import { useState } from "react";+import { EyeIcon, InfoIcon, MoreHorizontalIcon, Trash2Icon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Badge,+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ DeleteConfirmDialog,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ IconButton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import {+ PkiAlertEventTypeV2,+ TPkiAlertV2,+ useDeletePkiAlertV2,+ useGetPkiAlertsV2+} from "@app/hooks/api/pkiAlertsV2";+import { ViewPkiAlertV2Modal } from "@app/views/PkiAlertsV2Page/components/ViewPkiAlertV2Modal";+import { formatEventType } from "@app/views/PkiAlertsV2Page/utils/pki-alert-formatters";++import { formatAlertBefore } from "./types";++type LegacyAlertRowProps = {+ alert: TPkiAlertV2;+ onView: () => void;+ onDelete: () => void;+ canDelete: boolean;+};++const LegacyAlertRow = ({ alert, onView, onDelete, canDelete }: LegacyAlertRowProps) => (+ <TableRow>+ <TableCell isTruncatable>+ <div className="flex items-center gap-2">+ <span className="font-medium text-foreground">{alert.name}</span>+ {alert.description ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <InfoIcon className="size-3.5 shrink-0 text-accent" />+ </TooltipTrigger>+ <TooltipContent side="right" className="max-w-xs">+ {alert.description}+ </TooltipContent>+ </Tooltip>+ ) : null}+ </div>+ </TableCell>+ <TableCell className="whitespace-nowrap text-accent">+ {formatEventType(alert.eventType)}+ </TableCell>+ <TableCell className="whitespace-nowrap">+ <Badge variant={alert.enabled ? "success" : "neutral"}>+ {alert.enabled ? "Enabled" : "Disabled"}+ </Badge>+ </TableCell>+ <TableCell className="whitespace-nowrap text-accent">+ {alert.eventType === PkiAlertEventTypeV2.EXPIRATION ? (+ formatAlertBefore(alert.alertBefore)+ ) : (+ <span className="text-surface-selected">—</span>+ )}+ </TableCell>+ <TableCell className="whitespace-nowrap">+ {alert.lastRun ? (+ <Badge variant={alert.lastRun.status === "success" ? "success" : "danger"}>+ {alert.lastRun.status === "success" ? "Success" : "Failed"}+ </Badge>+ ) : (+ <span className="text-surface-selected">—</span>+ )}+ </TableCell>+ <TableCell className="text-right">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton variant="ghost" size="xs" aria-label="Legacy alert actions">+ <MoreHorizontalIcon />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent className="min-w-44" align="end" sideOffset={2}>+ <DropdownMenuItem onClick={onView}>+ <EyeIcon />+ View details+ </DropdownMenuItem>+ <DropdownMenuItem variant="danger" isDisabled={!canDelete} onClick={onDelete}>+ <Trash2Icon />+ Delete alert+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </TableCell>+ </TableRow>+);++type Props = {+ applicationId: string;+ canDelete: boolean;+};++export const LegacyApplicationAlertsCard = ({ applicationId, canDelete }: Props) => {+ const { data } = useGetPkiAlertsV2({ applicationId, limit: 100 });+ const legacyAlerts = data?.alerts ?? [];+ const [viewAlertId, setViewAlertId] = useState<string>();+ const [deleteAlert, setDeleteAlert] = useState<{ alertId: string; name: string }>();+ const { mutateAsync: deletePkiAlert } = useDeletePkiAlertV2();++ if (legacyAlerts.length === 0) return null;++ const handleDeleteAlert = async () => {+ if (!deleteAlert) return;+ await deletePkiAlert({ alertId: deleteAlert.alertId, applicationId });+ setDeleteAlert(undefined);+ createNotification({ type: "success", text: `Alert "${deleteAlert.name}" deleted` });+ };++ return (+ <>+ <Card>+ <CardHeader>+ <CardTitle>+ Legacy Alerting+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="rounded bg-surface-active px-2 py-0.5 text-[10px] tracking-wide text-foreground-secondary uppercase">+ Legacy+ </span>+ </TooltipTrigger>+ <TooltipContent side="right" className="max-w-xs">+ Legacy alerts are deprecated. They still send notifications but can no longer be+ created or edited. Recreate them under Alerting above, then delete them here.+ </TooltipContent>+ </Tooltip>+ </CardTitle>+ <CardDescription>Alerts created with the previous alerting system.</CardDescription>+ </CardHeader>+ <CardContent>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-1/3">Name</TableHead>+ <TableHead className="whitespace-nowrap">Event Type</TableHead>+ <TableHead className="whitespace-nowrap">Status</TableHead>+ <TableHead className="whitespace-nowrap">Alert Before</TableHead>+ <TableHead className="whitespace-nowrap">Last Run</TableHead>+ <TableHead className="w-5 text-right">Actions</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {legacyAlerts.map((alert) => (+ <LegacyAlertRow+ key={alert.id}+ alert={alert}+ onView={() => setViewAlertId(alert.id)}+ onDelete={() => setDeleteAlert({ alertId: alert.id, name: alert.name })}+ canDelete={canDelete}+ />+ ))}+ </TableBody>+ </Table>+ </CardContent>+ </Card>+ <ViewPkiAlertV2Modal+ isOpen={Boolean(viewAlertId)}+ onOpenChange={(isOpen) => !isOpen && setViewAlertId(undefined)}+ alertId={viewAlertId}+ />+ <DeleteConfirmDialog+ isOpen={Boolean(deleteAlert)}+ confirmKey="delete"+ title={`Delete Legacy Alert "${deleteAlert?.name ?? ""}"?`}+ onOpenChange={(isOpen) => !isOpen && setDeleteAlert(undefined)}+ onConfirm={handleDeleteAlert}+ />+ </>+ );+};diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsxnew file mode 100644index 0000000000..aab27891e1--- /dev/null+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsx@@ -0,0 +1,108 @@+import { ReactNode } from "react";+import { UseFormReturn, useWatch } from "react-hook-form";++import { Badge } from "@app/components/v3";+import {+ ALERT_CHANNEL_TYPE_LABELS,+ AlertChannelType,+ AlertPrincipalType,+ CertificateAlertEventType,+ TChannelForm+} from "@app/hooks/api/alerts";++import {+ CERTIFICATE_ALERT_EVENT_LABELS,+ TCertificateAlertForm,+ toRecipientEmails,+ TProjectMemberEmails+} from "./types";++type Props = { form: UseFormReturn<TCertificateAlertForm>; members: TProjectMemberEmails };++const Section = ({ title, children }: { title: string; children: ReactNode }) => (+ <div className="flex flex-col gap-4">+ <p className="border-b border-border pb-2 text-sm font-medium text-foreground">{title}</p>+ {children}+ </div>+);++const Detail = ({ label, children }: { label: string; children: ReactNode }) => (+ <div className="flex flex-col gap-1">+ <span className="text-xs text-muted">{label}</span>+ <span className="text-sm text-foreground">{children}</span>+ </div>+);++const EnabledBadge = ({ enabled }: { enabled: boolean }) => (+ <Badge variant={enabled ? "success" : "neutral"}>{enabled ? "Enabled" : "Disabled"}</Badge>+);++const describeChannel = (channel: TChannelForm, members: TProjectMemberEmails): string => {+ switch (channel.channelType) {+ case AlertChannelType.Email: {+ const groupCount = channel.recipients.filter(+ (recipient) => recipient.principalType === AlertPrincipalType.Group+ ).length;+ return [+ ...toRecipientEmails(channel.recipients, members),+ ...(groupCount ? [`${groupCount} group(s)`] : [])+ ].join(", ");+ }+ case AlertChannelType.Webhook:+ return channel.url ?? "";+ case AlertChannelType.Slack:+ return "Slack Incoming Webhook";+ case AlertChannelType.PagerDuty:+ return "PagerDuty Events API v2";+ default:+ return "";+ }+};++export const ReviewStep = ({ form, members }: Props) => {+ const values = useWatch({ control: form.control }) as TCertificateAlertForm;+ const isExpiry = values.eventType === CertificateAlertEventType.Expiry;++ return (+ <div className="flex flex-col gap-8">+ <Section title="Basic Information">+ <div className="grid grid-cols-2 gap-x-6 gap-y-4 lg:grid-cols-4">+ <Detail label="Name">{values.name}</Detail>+ <Detail label="Alert Type">{CERTIFICATE_ALERT_EVENT_LABELS[values.eventType]}</Detail>+ <Detail label="Status">+ <EnabledBadge enabled={values.enabled} />+ </Detail>+ {isExpiry && <Detail label="Alert Before">{values.alertBefore}</Detail>}+ {isExpiry && (+ <Detail label="Repeat daily">+ <EnabledBadge enabled={values.dailyReminder} />+ </Detail>+ )}+ {values.description && <Detail label="Description">{values.description}</Detail>}+ </div>+ </Section>++ <Section title="Notification Channels">+ <div className="flex flex-col gap-3">+ {values.channels.map((channel, index) => (+ <div+ // eslint-disable-next-line react/no-array-index-key+ key={`${channel.channelType}-${index}`}+ className="flex items-center justify-between gap-4 rounded-md border border-border bg-container px-4 py-3"+ >+ <div className="flex min-w-0 flex-col gap-1">+ <span className="text-sm text-foreground">+ {ALERT_CHANNEL_TYPE_LABELS[channel.channelType]}+ </span>+ <span className="truncate text-xs text-muted">+ {describeChannel(channel, members)}+ </span>+ </div>+ <EnabledBadge enabled={channel.enabled} />+ </div>+ ))}+ </div>+ </Section>+ </div>+ );+};diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.tsnew file mode 100644index 0000000000..d4565ebf8d--- /dev/null+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts@@ -0,0 +1,177 @@+import { z } from "zod";++import {+ AlertPrincipalType,+ CertificateAlertEventType,+ channelFormSchema,+ MAX_CERTIFICATE_ALERT_BEFORE_DAYS,+ TAlert,+ TAlertChannelRecipient,+ TChannelForm+} from "@app/hooks/api/alerts";++export const CERTIFICATE_ALERT_EVENT_LABELS: Record<CertificateAlertEventType, string> = {+ [CertificateAlertEventType.Expiry]: "Certificate Expiration",+ [CertificateAlertEventType.Issuance]: "Certificate Issuance",+ [CertificateAlertEventType.Renewal]: "Certificate Renewal",+ [CertificateAlertEventType.Revocation]: "Certificate Revocation"+};++export const CERTIFICATE_ALERT_EVENT_DESCRIPTIONS: Record<CertificateAlertEventType, string> = {+ [CertificateAlertEventType.Expiry]: "Fires ahead of a certificate's expiry date.",+ [CertificateAlertEventType.Issuance]:+ "Fires when Infisical issues a certificate in this application.",+ [CertificateAlertEventType.Renewal]: "Fires when a certificate in this application is renewed.",+ [CertificateAlertEventType.Revocation]: "Fires when a certificate in this application is revoked."+};++export const MAX_CHANNELS = 10;++const ALERT_BEFORE_PATTERN = /^(\d{1,4})([dwmy])$/;+const DAYS_PER_UNIT: Record<string, number> = { d: 1, w: 7, m: 30, y: 365 };++const alertBeforeToDays = (alertBefore: string): number | null => {+ const match = alertBefore.trim().match(ALERT_BEFORE_PATTERN);+ return match ? parseInt(match[1], 10) * DAYS_PER_UNIT[match[2]] : null;+};++const ALERT_BEFORE_UNIT_LABELS: Record<string, string> = {+ d: "day",+ w: "week",+ m: "month",+ y: "year"+};++export const formatAlertBefore = (alertBefore?: string | null, fallback = "-"): string => {+ if (!alertBefore) return fallback;+ const match = alertBefore.trim().match(ALERT_BEFORE_PATTERN);+ if (!match) return alertBefore;+ const value = parseInt(match[1], 10);+ return `${value} ${ALERT_BEFORE_UNIT_LABELS[match[2]]}${value === 1 ? "" : "s"}`;+};++export const normalizeEmail = (email: string) => email.trim().toLowerCase();++export type TProjectMemberEmails = {+ emailByUserId: Map<string, string>;+ memberIdByEmail: Map<string, string>;+ isAvailable: boolean;+};++export const toRecipientEmails = (+ recipients: TAlertChannelRecipient[],+ { emailByUserId }: Pick<TProjectMemberEmails, "emailByUserId">+) =>+ recipients.flatMap((recipient) => {+ if (recipient.principalType === AlertPrincipalType.User) {+ const email = emailByUserId.get(recipient.principalId);+ return email ? [email] : [];+ }+ return recipient.principalType === AlertPrincipalType.Email ? [recipient.principalId] : [];+ });++export const STEPS = [+ {+ name: "Details",+ shortDescription: "Event and name",+ title: "Alert Details",+ subtitle: "Choose the event that triggers this alert and name it."+ },+ {+ name: "Channels",+ shortDescription: "Where it is sent",+ title: "Notification Channels",+ subtitle: "Add at least one destination for this alert."+ },+ {+ name: "Review",+ shortDescription: "Confirm and save",+ title: "Review",+ subtitle: "Check the settings below before saving this alert."+ }+] as const;++export const certificateAlertFormSchema = z+ .object({+ eventType: z.nativeEnum(CertificateAlertEventType),+ name: z.string().trim().min(1, "Name is required").max(255),+ description: z.string().trim().max(1000),+ alertBefore: z.string().trim(),+ dailyReminder: z.boolean(),+ enabled: z.boolean(),+ channels: z.array(channelFormSchema).min(1, "Add at least one channel").max(MAX_CHANNELS)+ })+ .superRefine((form, ctx) => {+ if (form.eventType !== CertificateAlertEventType.Expiry) return;+ const days = alertBeforeToDays(form.alertBefore);+ if (days === null) {+ ctx.addIssue({+ code: "custom",+ path: ["alertBefore"],+ message: "Use a number and a unit, for example 30d"+ });+ } else if (days < 1 || days > MAX_CERTIFICATE_ALERT_BEFORE_DAYS) {+ ctx.addIssue({+ code: "custom",+ path: ["alertBefore"],+ message: `Must be between 1 and ${MAX_CERTIFICATE_ALERT_BEFORE_DAYS} days`+ });+ }+ });++export type TCertificateAlertForm = z.infer<typeof certificateAlertFormSchema>;++export const STEP_FIELDS: (keyof TCertificateAlertForm)[][] = [+ ["eventType", "name", "description", "alertBefore", "dailyReminder"],+ ["channels"]+];++export const emptyCertificateAlertForm = (+ eventType = CertificateAlertEventType.Expiry+): TCertificateAlertForm => ({+ eventType,+ name: "",+ description: "",+ alertBefore: "30d",+ dailyReminder: false,+ enabled: true,+ channels: []+});++export const toCertificateAlertForm = (+ alert: TAlert,+ { emailByUserId, isAvailable }: Pick<TProjectMemberEmails, "emailByUserId" | "isAvailable">+): TCertificateAlertForm => ({+ eventType: alert.eventType as CertificateAlertEventType,+ name: alert.name,+ description: alert.description ?? "",+ alertBefore: alert.condition?.alertBefore ?? "30d",+ dailyReminder: alert.condition?.dailyReminder ?? false,+ enabled: alert.enabled,+ channels: alert.channels.map(+ (channel): TChannelForm => ({+ id: channel.id,+ name: channel.name,+ channelType: channel.channelType,+ enabled: channel.enabled,+ recipients: channel.recipients.filter(+ (recipient) =>+ !isAvailable ||+ recipient.principalType !== AlertPrincipalType.User ||+ emailByUserId.has(recipient.principalId)+ ),+ url: (channel.config.url as string) ?? "",+ webhookUrl: "",+ signingSecret: "",+ integrationKey: "",+ hasSigningSecret: Boolean(channel.config.hasSigningSecret),+ hasWebhookUrl: Boolean(channel.config.hasWebhookUrl),+ hasIntegrationKey: Boolean(channel.config.hasIntegrationKey)+ })+ )+});++export const toCondition = (form: TCertificateAlertForm) =>+ form.eventType === CertificateAlertEventType.Expiry+ ? { alertBefore: form.alertBefore.trim(), dailyReminder: form.dailyReminder }+ : null;diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsxindex e7c142ae99..3081e9ebba 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx@@ -5,17 +5,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { useQuery } from "@tanstack/react-query";import { Link, useParams } from "@tanstack/react-router";import { formatDistance } from "date-fns";-import {- CircleStopIcon,- EyeIcon,- InfoIcon,- MoreHorizontalIcon,- PencilIcon,- PlayIcon,- PlusIcon,- Settings2Icon,- Trash2Icon-} from "lucide-react";+import { MoreHorizontalIcon, PencilIcon, PlusIcon, Settings2Icon, Trash2Icon } from "lucide-react";import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";import { createNotification } from "@app/components/notifications";@@ -72,13 +62,6 @@ import {useDeleteApprovalPolicy} from "@app/hooks/api/approvalPolicies";import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";-import {- PkiAlertEventTypeV2,- TPkiAlertV2,- useDeletePkiAlertV2,- useGetPkiAlertsV2,- useUpdatePkiAlertV2-} from "@app/hooks/api/pkiAlertsV2";import {PkiApplicationResourceActions,PkiApplicationResourceSub,@@ -90,14 +73,10 @@ import {} from "@app/hooks/api/pkiApplications";import { PolicyModal } from "@app/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicyModal";import { CreateProfileModal } from "@app/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal";-import { CreatePkiAlertV2Modal } from "@app/views/PkiAlertsV2Page/components/CreatePkiAlertV2Modal";-import { ViewPkiAlertV2Modal } from "@app/views/PkiAlertsV2Page/components/ViewPkiAlertV2Modal";-import {- formatAlertBefore,- formatEventType-} from "@app/views/PkiAlertsV2Page/utils/pki-alert-formatters";import { PkiDocsUrls } from "../../pki-docs-urls";+import { ApplicationAlertsCard } from "./ApplicationAlerts/ApplicationAlertsCard";+import { LegacyApplicationAlertsCard } from "./ApplicationAlerts/LegacyApplicationAlertsCard";import {ConfigureEnrollmentModal,EnrollmentMethod,@@ -252,119 +231,6 @@ const ApplicationPoliciesTable = ({);};-type AlertRowProps = {- alert: TPkiAlertV2;- onView: () => void;- onEdit: () => void;- onDelete: () => void;- canEdit: boolean;- canDelete: boolean;-};--const AlertRow = ({ alert, onView, onEdit, onDelete, canEdit, canDelete }: AlertRowProps) => {- const { mutateAsync: updateAlert } = useUpdatePkiAlertV2();-- const handleToggleAlert = async () => {- try {- await updateAlert({ alertId: alert.id, enabled: !alert.enabled });- createNotification({- text: `Alert ${!alert.enabled ? "enabled" : "disabled"} successfully`,- type: "success"- });- } catch {- createNotification({ text: "Failed to update alert status", type: "error" });- }- };-- return (- <TableRow>- <TableCell isTruncatable>- <div className="flex items-center gap-2">- <span className="font-medium text-foreground">{alert.name}</span>- {alert.description ? (- <Tooltip>- <TooltipTrigger asChild>- <InfoIcon className="size-3.5 shrink-0 text-accent" />- </TooltipTrigger>- <TooltipContent side="right" className="max-w-xs">- {alert.description}- </TooltipContent>- </Tooltip>- ) : null}- </div>- </TableCell>- <TableCell className="whitespace-nowrap text-accent">- {formatEventType(alert.eventType)}- </TableCell>- <TableCell className="whitespace-nowrap">- <Badge variant={alert.enabled ? "success" : "neutral"}>- {alert.enabled ? "Enabled" : "Disabled"}- </Badge>- </TableCell>- <TableCell className="whitespace-nowrap text-accent">- {alert.eventType === PkiAlertEventTypeV2.EXPIRATION ? (- formatAlertBefore(alert.alertBefore)- ) : (- <span className="text-surface-selected">—</span>- )}- </TableCell>- <TableCell className="whitespace-nowrap">- {alert.lastRun ? (- <Tooltip>- <TooltipTrigger asChild>- <Badge variant={alert.lastRun.status === "success" ? "success" : "danger"}>- {alert.lastRun.status === "success" ? "Success" : "Failed"}- </Badge>- </TooltipTrigger>- <TooltipContent side="left" className="max-w-sm">- <div className="text-xs text-label">- {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-danger">- {alert.lastRun.error}- </div>- ) : null}- </TooltipContent>- </Tooltip>- ) : (- <span className="text-surface-selected">—</span>- )}- </TableCell>- <TableCell className="text-right">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton variant="ghost" size="xs" aria-label="Alert actions">- <MoreHorizontalIcon />- </IconButton>- </DropdownMenuTrigger>- <DropdownMenuContent className="min-w-44" align="end" sideOffset={2}>- <DropdownMenuItem onClick={onView}>- <EyeIcon />- View details- </DropdownMenuItem>- <DropdownMenuItem isDisabled={!canEdit} onClick={onEdit}>- <PencilIcon />- Edit alert- </DropdownMenuItem>- <DropdownMenuItem isDisabled={!canEdit} onClick={handleToggleAlert}>- {alert.enabled ? <CircleStopIcon /> : <PlayIcon />}- {alert.enabled ? "Disable" : "Enable"} alert- </DropdownMenuItem>- <DropdownMenuItem variant="danger" isDisabled={!canDelete} onClick={onDelete}>- <Trash2Icon />- Delete alert- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </TableCell>- </TableRow>- );-};-export const ApplicationSettingsTab = ({ application, profiles }: Props) => {const { orgId, projectId } = useParams({ strict: false }) as {orgId?: string;@@ -399,7 +265,7 @@ export const ApplicationSettingsTab = ({ application, profiles }: Props) => {const canEditPolicies = Boolean(appAbility?.can(PkiApplicationResourceActions.Edit, PkiApplicationResourceSub.ApprovalPolicies));- const canManageAlerts = Boolean(+ const canCreateAlerts = Boolean(appAbility?.can(PkiApplicationResourceActions.Create, PkiApplicationResourceSub.PkiAlerts));const canEditAlerts = Boolean(@@ -451,41 +317,6 @@ export const ApplicationSettingsTab = ({ application, profiles }: Props) => {};const deletePolicy = useDeleteApprovalPolicy();- const { data: alertsData, isLoading: isAlertsLoading } = useGetPkiAlertsV2({- applicationId: application.id,- limit: 100- });- const alerts = alertsData?.alerts ?? [];- const [alertModal, setAlertModal] = useState<{ isOpen: boolean; alertId?: string }>({- isOpen: false- });- const [viewAlertModal, setViewAlertModal] = useState<{ isOpen: boolean; alertId?: string }>({- isOpen: false- });- const [deleteAlertModal, setDeleteAlertModal] = useState<{- isOpen: boolean;- alertId?: string;- name?: string;- }>({ isOpen: false });- const { mutateAsync: deleteAlert } = useDeletePkiAlertV2();-- const handleDeleteAlert = async () => {- if (!deleteAlertModal.alertId) return;- try {- await deleteAlert({- alertId: deleteAlertModal.alertId,- applicationId: application.id- });- setDeleteAlertModal({ isOpen: false });- createNotification({ type: "success", text: "Alert deleted" });- } catch (err) {- createNotification({- type: "error",- text: err instanceof Error ? err.message : "Failed to delete alert"- });- }- };-const handleDeletePolicy = async () => {const p = popUp.deletePolicy.data as { policyId: string } | undefined;if (!p?.policyId) return;@@ -787,88 +618,15 @@ export const ApplicationSettingsTab = ({ application, profiles }: Props) => {</CardContent></Card>- <Card>- <CardHeader>- <CardTitle>- Alerting- <DocumentationLinkBadge href={PkiDocsUrls.applications.alerting.overview} />- </CardTitle>- <CardDescription>Get notified about certificate events.</CardDescription>- <CardAction>- <Tooltip>- <TooltipTrigger asChild>- {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- focusable wrapper required so the tooltip surfaces on keyboard focus despite the inner button being disabled */}- <span tabIndex={0}>- <Button- variant="outline"- onClick={() => setAlertModal({ isOpen: true })}- isDisabled={!canManageAlerts}- >- <FontAwesomeIcon icon={faPlus} />- Create Alert- </Button>- </span>- </TooltipTrigger>- {!canManageAlerts && (- <TooltipContent side="left">- You don't have permission to create alerts- </TooltipContent>- )}- </Tooltip>- </CardAction>- </CardHeader>- <CardContent>- {!isAlertsLoading && alerts.length === 0 ? (- <Empty className="border">- <EmptyHeader>- <EmptyTitle>No alerts configured</EmptyTitle>- <EmptyDescription>- Create one to get notified about certificate events for this application.- </EmptyDescription>- </EmptyHeader>- </Empty>- ) : (- <Table>- <TableHeader>- <TableRow>- <TableHead className="w-1/3">Name</TableHead>- <TableHead className="whitespace-nowrap">Event Type</TableHead>- <TableHead className="whitespace-nowrap">Status</TableHead>- <TableHead className="whitespace-nowrap">Alert Before</TableHead>- <TableHead className="whitespace-nowrap">Last Run</TableHead>- <TableHead className="w-5 text-right">Actions</TableHead>- </TableRow>- </TableHeader>- <TableBody>- {isAlertsLoading &&- Array.from({ length: 3 }, (_, idx) => (- <TableRow key={`alert-skeleton-${idx + 1}`}>- {Array.from({ length: 6 }, (__, cellIdx) => (- <TableCell key={`alert-skeleton-cell-${cellIdx + 1}`}>- <Skeleton className="h-4 w-24" />- </TableCell>- ))}- </TableRow>- ))}- {!isAlertsLoading &&- alerts.map((a: TPkiAlertV2) => (- <AlertRow- key={a.id}- alert={a}- onView={() => setViewAlertModal({ isOpen: true, alertId: a.id })}- onEdit={() => setAlertModal({ isOpen: true, alertId: a.id })}- onDelete={() =>- setDeleteAlertModal({ isOpen: true, alertId: a.id, name: a.name })- }- canEdit={canEditAlerts}- canDelete={canDeleteAlerts}- />- ))}- </TableBody>- </Table>- )}- </CardContent>- </Card>+ <ApplicationAlertsCard+ projectId={application.projectId}+ applicationId={application.id}+ applicationName={application.name}+ canCreate={canCreateAlerts}+ canEdit={canEditAlerts}+ canDelete={canDeleteAlerts}+ />+ <LegacyApplicationAlertsCard applicationId={application.id} canDelete={canDeleteAlerts} /><PolicyModalpopUp={popUp}@@ -888,24 +646,6 @@ export const ApplicationSettingsTab = ({ application, profiles }: Props) => {onChange={(isOpen) => handlePopUpToggle("deletePolicy", isOpen)}onDeleteApproved={handleDeletePolicy}/>- <CreatePkiAlertV2Modal- isOpen={alertModal.isOpen}- onOpenChange={(isOpen) => setAlertModal({ isOpen, alertId: undefined })}- applicationId={application.id}- alertId={alertModal.alertId}- />- <ViewPkiAlertV2Modal- isOpen={viewAlertModal.isOpen}- onOpenChange={(isOpen) => setViewAlertModal({ isOpen, alertId: undefined })}- alertId={viewAlertModal.alertId}- />- <DeleteActionModal- isOpen={deleteAlertModal.isOpen}- deleteKey="delete"- title={`Delete PKI Alert "${deleteAlertModal.name ?? ""}"`}- onChange={(isOpen) => setDeleteAlertModal({ isOpen, alertId: undefined, name: undefined })}- onDeleteApproved={handleDeleteAlert}- /><Dialogopen={isAttachOpen}diff --git a/frontend/src/views/Alerts/AddChannelMenu.tsx b/frontend/src/views/Alerts/AddChannelMenu.tsxnew file mode 100644index 0000000000..ed9c06f601--- /dev/null+++ b/frontend/src/views/Alerts/AddChannelMenu.tsx@@ -0,0 +1,57 @@+import { ChevronDownIcon, PlusIcon } from "lucide-react";++import {+ Badge,+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger+} from "@app/components/v3";+import { ALERT_CHANNEL_TYPE_LABELS, AlertChannelType } from "@app/hooks/api/alerts";++import { getChannelIcon } from "./channelIcons";++type Props = {+ onAdd: (channelType: AlertChannelType) => void;+ isDisabled?: boolean;+ lockedChannelTypes?: AlertChannelType[];+ onLockedSelect?: () => void;+};++export const AddChannelMenu = ({+ onAdd,+ isDisabled,+ lockedChannelTypes = [],+ onLockedSelect+}: Props) => (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button type="button" variant="outline" size="sm" isDisabled={isDisabled}>+ <PlusIcon className="size-4" />+ Add Channel+ <ChevronDownIcon className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" sideOffset={4} className="min-w-56">+ {Object.values(AlertChannelType).map((channelType) => {+ const Icon = getChannelIcon(channelType);+ const isLocked = lockedChannelTypes.includes(channelType);+ return (+ <DropdownMenuItem+ key={channelType}+ onClick={() => (isLocked ? onLockedSelect?.() : onAdd(channelType))}+ >+ <Icon className="size-4" />+ {ALERT_CHANNEL_TYPE_LABELS[channelType]}+ {isLocked && (+ <Badge variant="neutral" className="ml-auto">+ Enterprise+ </Badge>+ )}+ </DropdownMenuItem>+ );+ })}+ </DropdownMenuContent>+ </DropdownMenu>+);diff --git a/frontend/src/views/Alerts/ChannelCard.tsx b/frontend/src/views/Alerts/ChannelCard.tsxindex 51fd317d02..d78b482e68 100644--- a/frontend/src/views/Alerts/ChannelCard.tsx+++ b/frontend/src/views/Alerts/ChannelCard.tsx@@ -1,4 +1,4 @@-import { useState } from "react";+import { ReactElement, useState } from "react";import { Controller, useFormContext, UseFormRegisterReturn, useWatch } from "react-hook-form";import { EyeIcon, EyeOffIcon, SendIcon, TrashIcon } from "lucide-react";@@ -22,6 +22,7 @@ import { useScopeVariant } from "@app/hooks";import {ALERT_CHANNEL_TYPE_LABELS,AlertChannelType,+ TAlertChannelRecipient,TAlertForm,toChannelInput,useTestAlertChannel@@ -30,6 +31,12 @@ import {import { getChannelIcon } from "./channelIcons";import { ChannelRecipientsField } from "./ChannelRecipientsField";+export type TChannelRecipientsRenderProps = {+ value: TAlertChannelRecipient[];+ onChange: (recipients: TAlertChannelRecipient[]) => void;+ isError: boolean;+};+type Props = {index: number;projectId?: string;@@ -37,6 +44,7 @@ type Props = {resourceId?: string | null;onRemove: () => void;canRemove: boolean;+ renderRecipients?: (props: TChannelRecipientsRenderProps) => ReactElement;};const KEEP_PLACEHOLDER = "•••••••• (leave blank to keep)";@@ -82,7 +90,8 @@ export const ChannelCard = ({resourceType,resourceId,onRemove,- canRemove+ canRemove,+ renderRecipients}: Props) => {const scopeVariant = useScopeVariant();const {@@ -193,14 +202,22 @@ export const ChannelCard = ({<Controllercontrol={control}name={`channels.${index}.recipients`}- render={({ field }) => (- <ChannelRecipientsField- projectId={projectId}- value={field.value ?? []}- onChange={field.onChange}- isError={Boolean(channelErrors?.recipients)}- />- )}+ render={({ field }) =>+ renderRecipients ? (+ renderRecipients({+ value: field.value ?? [],+ onChange: field.onChange,+ isError: Boolean(channelErrors?.recipients)+ })+ ) : (+ <ChannelRecipientsField+ projectId={projectId}+ value={field.value ?? []}+ onChange={field.onChange}+ isError={Boolean(channelErrors?.recipients)}+ />+ )+ }/><FieldError errors={[channelErrors?.recipients as { message?: string } | undefined]} /></FieldContent>diff --git a/frontend/src/views/Alerts/ChannelsField.tsx b/frontend/src/views/Alerts/ChannelsField.tsxindex a022e39cb2..6c6be485bd 100644--- a/frontend/src/views/Alerts/ChannelsField.tsx+++ b/frontend/src/views/Alerts/ChannelsField.tsx@@ -1,14 +1,6 @@import { useFieldArray, useFormContext } from "react-hook-form";-import { ChevronDownIcon, PlusIcon } from "lucide-react";-import {- Button,- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,- Label-} from "@app/components/v3";+import { Label } from "@app/components/v3";import {ALERT_CHANNEL_TYPE_LABELS,AlertChannelType,@@ -17,8 +9,8 @@ import {TChannelForm} from "@app/hooks/api/alerts";+import { AddChannelMenu } from "./AddChannelMenu";import { ChannelCard } from "./ChannelCard";-import { getChannelIcon } from "./channelIcons";type Props = {projectId?: string;@@ -26,7 +18,7 @@ type Props = {resourceId?: string | null;};-const buildNewChannel = (channelType: AlertChannelType, name: string): TChannelForm => ({+export const buildNewChannel = (channelType: AlertChannelType, name: string): TChannelForm => ({channelType,name,enabled: true,@@ -37,6 +29,15 @@ const buildNewChannel = (channelType: AlertChannelType, name: string): TChannelFintegrationKey: ""});+export const getNextChannelName = (takenNames: Set<string>, channelType: AlertChannelType) => {+ const baseName = ALERT_CHANNEL_TYPE_LABELS[channelType];+ let name = baseName;+ for (let suffix = 2; takenNames.has(name); suffix += 1) {+ name = `${baseName} ${suffix}`;+ }+ return name;+};+export const ChannelsField = ({ projectId, resourceType, resourceId }: Props) => {const {control,@@ -50,12 +51,7 @@ export const ChannelsField = ({ projectId, resourceType, resourceId }: Props) =>// suffixed to stay unique so multiples remain distinguishable (e.g. in Terraform).const appendChannel = (channelType: AlertChannelType) => {const takenNames = new Set((getValues("channels") ?? []).map((channel) => channel.name));- const baseName = ALERT_CHANNEL_TYPE_LABELS[channelType];- let name = baseName;- for (let suffix = 2; takenNames.has(name); suffix += 1) {- name = `${baseName} ${suffix}`;- }- append(buildNewChannel(channelType, name));+ append(buildNewChannel(channelType, getNextChannelName(takenNames, channelType)));};return (@@ -67,30 +63,7 @@ export const ChannelsField = ({ projectId, resourceType, resourceId }: Props) =></Label><span className="text-xs text-muted">Add at least one delivery channel.</span></div>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button type="button" variant="outline" size="sm">- <PlusIcon className="size-4" />- Add channel- <ChevronDownIcon className="size-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent- align="end"- sideOffset={4}- className="w-[var(--radix-dropdown-menu-trigger-width)]"- >- {Object.values(AlertChannelType).map((type) => {- const Icon = getChannelIcon(type);- return (- <DropdownMenuItem key={type} onClick={() => appendChannel(type)}>- <Icon className="size-4" />- {ALERT_CHANNEL_TYPE_LABELS[type]}- </DropdownMenuItem>- );- })}- </DropdownMenuContent>- </DropdownMenu>+ <AddChannelMenu onAdd={appendChannel} /></div>{rootError && <p className="text-xs text-danger">{rootError}</p>}diff --git a/frontend/src/views/Alerts/index.ts b/frontend/src/views/Alerts/index.tsindex 68fe73c77e..ec302873d3 100644--- a/frontend/src/views/Alerts/index.ts+++ b/frontend/src/views/Alerts/index.ts@@ -1,2 +1,5 @@export { AddAlertModal } from "./AddAlertModal";+export { AddChannelMenu } from "./AddChannelMenu";export { AlertAction } from "./AlertAction";+export { ChannelCard, type TChannelRecipientsRenderProps } from "./ChannelCard";+export { buildNewChannel, getNextChannelName } from "./ChannelsField";diff --git a/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsx b/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsxindex 8a5a7726c6..9cdd14cf8c 100644--- a/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsx+++ b/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsx@@ -19,7 +19,6 @@ import {import { useDebounce } from "@app/hooks";import { useDeletePkiAlertV2, useGetPkiAlertsV2 } from "@app/hooks/api/pkiAlertsV2";-import { CreatePkiAlertV2Modal } from "./components/CreatePkiAlertV2Modal";import { PkiAlertV2Row } from "./components/PkiAlertV2Row";import { ViewPkiAlertV2Modal } from "./components/ViewPkiAlertV2Modal";@@ -33,9 +32,6 @@ export const PkiAlertsV2Page = ({ hideContainer = false }: Props) => {const [search, setSearch] = useState("");const [debouncedSearch] = useDebounce(search, 500);- const [alertModal, setAlertModal] = useState<{ isOpen: boolean; alertId?: string }>({- isOpen: false- });const [viewModal, setViewModal] = useState<{ isOpen: boolean; alertId?: string }>({isOpen: false});@@ -107,7 +103,6 @@ export const PkiAlertsV2Page = ({ hideContainer = false }: Props) => {key={alert.id}alert={alert}onView={() => setViewModal({ isOpen: true, alertId: alert.id })}- onEdit={() => setAlertModal({ isOpen: true, alertId: alert.id })}onDelete={() =>setDeleteModal({isOpen: true,@@ -138,7 +133,10 @@ export const PkiAlertsV2Page = ({ hideContainer = false }: Props) => {Legacy</span></div>- <p className="text-xs text-label-secondary">Create new alerts inside an Application.</p>+ <p className="text-xs text-label-secondary">+ Legacy alerts can only be viewed or deleted. Create new alerts from the Alerting section+ of an application's Settings tab.+ </p></div><div className="mb-4 flex items-center">@@ -185,12 +183,6 @@ export const PkiAlertsV2Page = ({ hideContainer = false }: Props) => {)}</div>- <CreatePkiAlertV2Modal- isOpen={alertModal.isOpen}- onOpenChange={(isOpen) => setAlertModal({ isOpen, alertId: undefined })}- alertId={alertModal.alertId}- />-<ViewPkiAlertV2ModalisOpen={viewModal.isOpen}onOpenChange={(isOpen) => setViewModal({ isOpen, alertId: undefined })}diff --git a/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2FormSteps.tsx b/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2FormSteps.tsxdeleted file mode 100644index 7e72126231..0000000000--- a/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2FormSteps.tsx+++ /dev/null@@ -1,1170 +0,0 @@-/* eslint-disable react/no-array-index-key */-import { useEffect, useRef, useState } from "react";-import { Controller, useFieldArray, useFormContext } from "react-hook-form";-import { faSlack } from "@fortawesome/free-brands-svg-icons";-import {- faBell,- 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,- IconButton,- Input,- Pagination,- Select,- SelectItem,- Skeleton,- Switch,- Table,- TableContainer,- TBody,- Td,- TextArea,- Th,- THead,- Tooltip,- Tr-} from "@app/components/v2";-import {- Accordion,- AccordionContent,- AccordionItem,- AccordionTrigger,- Badge-} from "@app/components/v3";-import { useProject, useSubscription } from "@app/context";-import {- PkiAlertChannelTypeV2,- PkiAlertEventTypeV2,- PkiFilterFieldV2,- PkiFilterOperatorV2,- TCreatePkiAlertV2,- TPkiAlertChannelConfigEmail,- TPkiAlertChannelConfigPagerDuty,- TPkiAlertChannelConfigSlack,- TPkiAlertChannelConfigWebhook,- TPkiFilterRuleV2,- useGetPkiAlertV2CurrentMatchingCertificates,- useTestPkiWebhookConfigV2-} from "@app/hooks/api/pkiAlertsV2";--import {- formatAlertBefore,- formatEventType,- getChannelDisplayName,- getChannelIcon,- getChannelSummary-} from "../utils/pki-alert-formatters";--const MAX_CHANNELS = 10;--interface CreatePkiAlertV2FormStepsProps {- expandedChannel: string | undefined;- setExpandedChannel: (channel: string | undefined) => void;- showPreview?: boolean;- showFilters?: boolean;- applicationId?: string;-}--type ChannelUIState = {- emailInput?: string;- webhookTest?: {- success: boolean | null;- error?: string;- isLoading?: boolean;- };-};--export const CreatePkiAlertV2FormSteps = ({- expandedChannel,- setExpandedChannel,- showPreview = true,- showFilters = true,- applicationId-}: CreatePkiAlertV2FormStepsProps) => {- const {- control,- watch,- setValue,- trigger,- clearErrors,- formState: { errors }- } = useFormContext<TCreatePkiAlertV2>();- const { currentProject } = useProject();- const { subscription } = useSubscription();-- const [certificatesPage, setCertificatesPage] = useState(1);- 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 watchedEventType = watch("eventType");- const watchedAlertBefore = watch("alertBefore");-- const previewEnabledTypes = [- PkiAlertEventTypeV2.EXPIRATION,- PkiAlertEventTypeV2.RENEWAL,- PkiAlertEventTypeV2.REVOCATION- ];- const isPreviewEnabled = !!currentProject?.id && previewEnabledTypes.includes(watchedEventType);-- const { data: currentCertificatesData, isLoading: isLoadingCurrentCertificates } =- useGetPkiAlertV2CurrentMatchingCertificates(- {- filters: watchedFilters || [],- ...(watchedEventType === PkiAlertEventTypeV2.EXPIRATION- ? { alertBefore: watchedAlertBefore || "30d" }- : {}),- limit: certificatesPerPage,- offset: (certificatesPage - 1) * certificatesPerPage- },- {- enabled: isPreviewEnabled,- refetchOnWindowFocus: false- }- );-- 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 isChannelLimitReached = watchedChannels.length >= MAX_CHANNELS;- const isEnterpriseAlertingAllowed = Boolean(subscription?.pkiEnterpriseAlerting);-- const addChannel = (type: PkiAlertChannelTypeV2) => {- if (isChannelLimitReached) return;- if (type !== PkiAlertChannelTypeV2.EMAIL && !isEnterpriseAlertingAllowed) return;- justAddedRef.current = true;-- let config:- | TPkiAlertChannelConfigEmail- | TPkiAlertChannelConfigWebhook- | TPkiAlertChannelConfigSlack- | TPkiAlertChannelConfigPagerDuty;- switch (type) {- case PkiAlertChannelTypeV2.EMAIL:- config = { recipients: [] };- break;- case PkiAlertChannelTypeV2.WEBHOOK:- config = { url: "" };- break;- case PkiAlertChannelTypeV2.SLACK:- config = { webhookUrl: "" };- break;- case PkiAlertChannelTypeV2.PAGERDUTY:- config = { integrationKey: "" };- break;- default:- config = { recipients: [] };- }-- prependChannel({- channelType: type,- config,- enabled: true- });- clearErrors("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({- url: webhookConfig.url,- signingSecret: webhookConfig.signingSecret || undefined,- applicationId- });-- 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) => {- 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;- };-- return (- <>- <Tab.Panel>- <div className="space-y-6">- <p className="mb-4 text-sm text-label-secondary">- Choose the event type and configure basic details for your alert.- </p>-- <div className="w-full">- <Controller- control={control}- name="eventType"- render={({ field, fieldState: { error } }) => (- <FormControl label="Alert Type" isError={Boolean(error)} errorText={error?.message}>- <Select- value={field.value}- onValueChange={(value) => field.onChange(value)}- className="w-full"- >- <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>- )}- />- </div>-- <Controller- control={control}- name="name"- render={({ field, fieldState: { error } }) => (- <FormControl label="Alert Name" isError={Boolean(error)} errorText={error?.message}>- <Input- {...field}- placeholder="e.g., tls-expiry-alert"- autoComplete="off"- name="pki-alert-name"- />- </FormControl>- )}- />-- <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>- )}- />-- {watchedEventType === PkiAlertEventTypeV2.EXPIRATION && (- <Controller- control={control}- name="alertBefore"- render={({ field, fieldState: { error } }) => (- <FormControl- label="Alert Before"- 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>- )}- />- )}-- {watchedEventType === PkiAlertEventTypeV2.EXPIRATION && (- <Controller- control={control}- name="notificationConfig.enableDailyNotification"- render={({ field }) => (- <div className="flex items-center justify-between">- <div className="flex flex-col gap-1">- <span className="text-sm text-label-secondary">Repeat daily until expiry</span>- <p className="text-xs text-muted-secondary">- Send a reminder every day from the alert threshold until the certificate- expires.- </p>- </div>- <Switch- id="daily-alerts"- isChecked={field.value}- onCheckedChange={field.onChange}- />- </div>- )}- />- )}- </div>- </Tab.Panel>-- {showFilters && (- <Tab.Panel>- <div className="space-y-6">- <p className="mb-4 text-sm text-label-secondary">- Add filter rules to specify which certificates should trigger this alert. Leave empty- to monitor all certificates.- </p>-- <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-${index}`}- className="space-y-2 rounded-md border border-border-control p-3"- >- <div className="flex items-center justify-between">- <h4 className="text-sm font-medium text-foreground">- 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-4 md:grid-cols-3">- <div className="md:col-span-1">- <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 : ""- })- }- className="w-full min-w-[200px]"- >- <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>- </div>-- <div className="md:col-span-1">- <FormControl label="Operator">- <Select- value={filter.operator}- onValueChange={(value) =>- updateFilter(index, { operator: value as PkiFilterOperatorV2 })- }- className="w-full min-w-[140px]"- >- {getFieldOperators(filter.field).map((operator) => (- <SelectItem key={operator} value={operator}>- {operator- .replace(/_/g, " ")- .toLowerCase()- .replace(/\b\w/g, (l) => l.toUpperCase())}- </SelectItem>- ))}- </Select>- </FormControl>- </div>-- <div className="md:col-span-1">- <FormControl label="Value">- {isValueBoolean(filter.field) ? (- <Select- value={String(filter.value)}- onValueChange={(value) =>- updateFilter(index, { value: value === "true" })- }- className="w-full"- >- <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;- updateFilter(index, { value });- }}- onBlur={(e) => {- const { value } = e.target;- if (canOperatorTakeArray(filter.operator) && value.includes(",")) {- const finalValue = value- .split(",")- .map((v) => v.trim())- .filter(Boolean);- updateFilter(index, { value: finalValue });- }- }}- placeholder={- canOperatorTakeArray(filter.operator)- ? "example.com, test.com"- : "example.com"- }- className="w-full"- />- )}- </FormControl>- </div>- </div>- </div>- ))}-- {(!watchedFilters || watchedFilters.length === 0) && (- <div className="py-8 text-center text-muted-secondary">- No filter rules configured. This alert will monitor all certificates.- </div>- )}- </div>- </div>- </Tab.Panel>- )}-- {showPreview && (- <Tab.Panel>- <div className="space-y-6">- <p className="mb-4 text-sm text-label-secondary">- {watchedEventType === PkiAlertEventTypeV2.EXPIRATION &&- "Preview certificates that will expire within the configured alert window and match your filter criteria."}- {watchedEventType === PkiAlertEventTypeV2.RENEWAL &&- "Preview active certificates that match your filter criteria. When any of these certificates are renewed, this alert will trigger."}- {watchedEventType === PkiAlertEventTypeV2.REVOCATION &&- "Preview active certificates that match your filter criteria. When any of these certificates are revoked, this alert will trigger."}- </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 (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-muted-cool">- No certificates currently match this alert'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>- )}- </div>- </div>- </Tab.Panel>- )}-- <Tab.Panel>- <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-muted">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} className="z-[70]">- <DropdownMenuItem onClick={() => addChannel(PkiAlertChannelTypeV2.EMAIL)}>- <FontAwesomeIcon icon={faEnvelope} className="mr-2" />- </DropdownMenuItem>- <DropdownMenuItem- isDisabled={!isEnterpriseAlertingAllowed}- onClick={() => addChannel(PkiAlertChannelTypeV2.WEBHOOK)}- >- <span className="flex items-center gap-2">- <FontAwesomeIcon icon={faLink} />- Webhook- {!isEnterpriseAlertingAllowed && <Badge variant="info">Enterprise</Badge>}- </span>- </DropdownMenuItem>- <DropdownMenuItem- isDisabled={!isEnterpriseAlertingAllowed}- onClick={() => addChannel(PkiAlertChannelTypeV2.SLACK)}- >- <span className="flex items-center gap-2">- <FontAwesomeIcon icon={faSlack} />- Slack- {!isEnterpriseAlertingAllowed && <Badge variant="info">Enterprise</Badge>}- </span>- </DropdownMenuItem>- <DropdownMenuItem- isDisabled={!isEnterpriseAlertingAllowed}- onClick={() => addChannel(PkiAlertChannelTypeV2.PAGERDUTY)}- >- <span className="flex items-center gap-2">- <FontAwesomeIcon icon={faBell} />- PagerDuty- {!isEnterpriseAlertingAllowed && <Badge variant="info">Enterprise</Badge>}- </span>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </div>-- {channelFields.length > 0 && (- <Accordion- type="single"- collapsible- value={expandedChannel}- onValueChange={setExpandedChannel}- className="border-border-strong bg-surface-active"- >- {channelFields.map((field, index) => {- const channel = watchedChannels[index];- const channelError = errors.channels?.[index];- return (- <AccordionItem key={field.id} value={field.id} className="border-border-control">- <AccordionTrigger className="group overflow-hidden bg-surface-raised hover:bg-surface-active data-[state=open]:bg-surface-hover data-[state=open]:hover:bg-surface-active">- <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-label"- />- <span className="shrink-0 text-sm font-medium">- {channel?.channelType && getChannelDisplayName(channel.channelType)}- </span>- <span className="truncate text-xs text-muted 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-surface-raised p-6">- {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();- }}- placeholder="[email protected], [email protected]"- 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-success">- <FontAwesomeIcon icon={faCheck} />- Success- </span>- )}- {channelUIStates[field.id]?.webhookTest?.success === false && (- <span className="flex items-center gap-1 text-sm text-danger">- <FontAwesomeIcon icon={faXmark} />- {channelUIStates[field.id]?.webhookTest?.error || "Failed"}- </span>- )}- </div>- </div>- )}-- {channel?.channelType === PkiAlertChannelTypeV2.SLACK && (- <Controller- control={control}- name={`channels.${index}.config.webhookUrl`}- render={({ field: urlField, fieldState: { error } }) => (- <FormControl- label="Slack Webhook URL"- isRequired- isError={Boolean(error)}- errorText={error?.message}- helperText="Create an Incoming Webhook in your Slack workspace settings"- >- <Input- value={urlField.value || ""}- onChange={urlField.onChange}- onBlur={urlField.onBlur}- placeholder="https://hooks.slack.com/services/..."- />- </FormControl>- )}- />- )}-- {channel?.channelType === PkiAlertChannelTypeV2.PAGERDUTY && (- <Controller- control={control}- name={`channels.${index}.config.integrationKey`}- render={({ field: keyField, fieldState: { error } }) => (- <FormControl- label="Integration Key"- isRequired- isError={Boolean(error)}- errorText={error?.message}- helperText="Find this in PagerDuty under Services → Integrations → Events API v2"- >- <Input- value={keyField.value || ""}- onChange={keyField.onChange}- onBlur={keyField.onBlur}- placeholder="32-character hex integration key"- />- </FormControl>- )}- />- )}- </AccordionContent>- </AccordionItem>- );- })}- </Accordion>- )}-- {channelFields.length > 0 && errors.channels?.message && (- <span className="text-sm text-danger">{errors.channels.message}</span>- )}-- {channelFields.length === 0 && (- <div className="flex flex-1 flex-col items-center justify-center gap-2">- <span className="text-muted-secondary">- At least one notification channel is required. Click "Add Channel" to add- one.- </span>- {errors.channels?.message && (- <span className="text-sm text-danger">{errors.channels.message}</span>- )}- </div>- )}- </div>- </Tab.Panel>-- <Tab.Panel>- <div className="mb-4 flex flex-col gap-6">- <p className="text-sm text-label-secondary">- Please review the settings below before creating your alert.- </p>-- <div className="flex flex-col gap-3">- <div className="w-full border-b border-border-control">- <span className="text-sm text-label">Basic Information</span>- </div>- <div className="flex flex-wrap gap-x-8 gap-y-2">- <GenericFieldLabel label="Name">{watch("name") || "Not specified"}</GenericFieldLabel>- <GenericFieldLabel label="Event Type">- {formatEventType(watchedEventType)}- </GenericFieldLabel>- <GenericFieldLabel label="Status">- <div className="mt-1">- <Badge variant={watch("enabled") ? "success" : "danger"}>- {watch("enabled") ? "Enabled" : "Disabled"}- </Badge>- </div>- </GenericFieldLabel>- {watchedEventType === PkiAlertEventTypeV2.EXPIRATION && (- <GenericFieldLabel label="Alert Before">- {formatAlertBefore(watch("alertBefore"))}- </GenericFieldLabel>- )}- {watchedEventType === PkiAlertEventTypeV2.EXPIRATION && (- <GenericFieldLabel label="Repeat daily until expiry">- {watch("notificationConfig.enableDailyNotification") ? "Enabled" : "Disabled"}- </GenericFieldLabel>- )}- {watch("description") && (- <GenericFieldLabel label="Description">{watch("description")}</GenericFieldLabel>- )}- </div>- </div>-- {showFilters && (- <div className="flex flex-col gap-3">- <div className="w-full border-b border-border-control">- <span className="text-sm text-label">Filter Rules</span>- </div>- <div className="flex flex-wrap gap-x-8 gap-y-2">- {watchedFilters && watchedFilters.length > 0 ? (- watchedFilters.map((filter, index) => (- <GenericFieldLabel key={`review-filter-${index}`} label={`Rule ${index + 1}`}>- <span className="font-mono text-xs">- {filter.field- .replace(/_/g, " ")- .toLowerCase()- .replace(/\b\w/g, (l) => l.toUpperCase())}{" "}- {filter.operator- .replace(/_/g, " ")- .toLowerCase()- .replace(/\b\w/g, (l) => l.toUpperCase())}{" "}- "{String(filter.value)}"- </span>- </GenericFieldLabel>- ))- ) : (- <span className="text-muted-secondary">- No filter rules - will monitor all certificates- </span>- )}- </div>- </div>- )}-- <div className="flex flex-col gap-3">- <div className="w-full border-b border-border-control">- <span className="text-sm text-label">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-border-control px-3 py-2"- >- <FontAwesomeIcon- icon={getChannelIcon(channel.channelType)}- className="text-muted"- />- <div className="flex min-w-0 flex-1 flex-col">- <div className="flex items-center gap-2">- <span className="text-sm font-medium text-foreground">- {getChannelDisplayName(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-muted" />- </Tooltip>- ) : (- <Tooltip content="Unsigned webhook - consider adding a signing secret for security">- <FontAwesomeIcon- icon={faTriangleExclamation}- className="text-xs text-muted"- />- </Tooltip>- ))}- </div>- <span className="truncate text-xs text-muted">- {(() => {- if (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;- }- if (channel.channelType === PkiAlertChannelTypeV2.WEBHOOK) {- const config = channel.config as TPkiAlertChannelConfigWebhook;- try {- const url = new URL(config.url);- return url.hostname;- } catch {- return config.url || "Not configured";- }- }- if (channel.channelType === PkiAlertChannelTypeV2.SLACK) {- const config = channel.config as TPkiAlertChannelConfigSlack;- return config.webhookUrl- ? "Slack webhook configured"- : "Not configured";- }- if (channel.channelType === PkiAlertChannelTypeV2.PAGERDUTY) {- return "PagerDuty integration configured";- }- return "";- })()}- </span>- </div>- {!channel.enabled && (- <Badge variant="neutral" className="text-xs">- Disabled- </Badge>- )}- </div>- ))}- </div>- ) : (- <span className="text-sm text-danger">- 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.tsxdeleted file mode 100644index 93757bd814..0000000000--- a/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2Modal.tsx+++ /dev/null@@ -1,398 +0,0 @@-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";-import { twMerge } from "tailwind-merge";--import { createNotification } from "@app/components/notifications";-import { Button, Modal, ModalContent } from "@app/components/v2";-import { useProject } from "@app/context";-import {- createPkiAlertV2Schema,- PkiAlertChannelTypeV2,- PkiAlertEventTypeV2,- SECRET_MASK,- TCreatePkiAlertV2,- TPkiAlertChannelConfigEmail,- TPkiAlertChannelConfigWebhook,- TPkiAlertChannelConfigWebhookResponse,- TPkiAlertV2,- TUpdatePkiAlertV2,- updatePkiAlertV2Schema,- useCreatePkiAlertV2,- useGetPkiAlertV2ById,- useUpdatePkiAlertV2-} from "@app/hooks/api/pkiAlertsV2";--import { CreatePkiAlertV2FormSteps } from "./CreatePkiAlertV2FormSteps";--interface Props {- isOpen: boolean;- onOpenChange: (isOpen: boolean) => void;- alertToEdit?: TPkiAlertV2;- alertId?: string;- applicationId?: string;-}--type TFormData = TCreatePkiAlertV2;--type TFormTab = { name: string; key: string; fields: (keyof TFormData)[] };--const TABS_WITH_PREVIEW: TFormTab[] = [- {- name: "Details",- key: "basicInfo",- fields: ["eventType", "name", "description", "alertBefore", "notificationConfig"]- },- { name: "Filters", key: "filterRules", fields: ["filters"] },- { name: "Preview", key: "preview", fields: [] },- { name: "Channels", key: "channels", fields: ["channels"] },- { name: "Review", key: "review", fields: [] }-];--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 TABS_APPLICATION_SCOPED: TFormTab[] = [- {- name: "Details",- key: "basicInfo",- fields: ["eventType", "name", "description", "alertBefore", "notificationConfig"]- },- { name: "Channels", key: "channels", fields: ["channels"] },- { name: "Review", key: "review", fields: [] }-];--const hasPreviewTab = (- eventType: PkiAlertEventTypeV2 | undefined,- applicationScoped: boolean-): boolean => {- if (applicationScoped) return false;- return (- !eventType ||- eventType === PkiAlertEventTypeV2.EXPIRATION ||- eventType === PkiAlertEventTypeV2.RENEWAL ||- eventType === PkiAlertEventTypeV2.REVOCATION- );-};--const getFormTabs = (- eventType: PkiAlertEventTypeV2 | undefined,- applicationScoped: boolean-): TFormTab[] => {- if (applicationScoped) return TABS_APPLICATION_SCOPED;- if (hasPreviewTab(eventType, false)) return TABS_WITH_PREVIEW;- return TABS_WITHOUT_PREVIEW;-};--const getChannelsTabIndex = (- eventType: PkiAlertEventTypeV2 | undefined,- applicationScoped: boolean-): number => {- if (applicationScoped) return 1;- return hasPreviewTab(eventType, false) ? 3 : 2;-};--export const CreatePkiAlertV2Modal = ({- isOpen,- onOpenChange,- alertToEdit,- alertId,- applicationId-}: Props) => {- const { currentProject } = useProject();- const [selectedTabIndex, setSelectedTabIndex] = useState(0);- const [expandedChannel, setExpandedChannel] = useState<string | undefined>(undefined);-- const { data: fetchedAlert } = useGetPkiAlertV2ById(- { alertId: alertId || "" },- { enabled: !!alertId && isOpen && !alertToEdit }- );-- const editingAlert = alertToEdit || fetchedAlert;- const isEditing = !!(editingAlert || alertId);-- const formMethods = useForm<TFormData>({- resolver: zodResolver(isEditing ? updatePkiAlertV2Schema : createPkiAlertV2Schema),- defaultValues: {- name: "",- description: "",- eventType: PkiAlertEventTypeV2.EXPIRATION,- alertBefore: "30d",- filters: [],- enabled: true,- notificationConfig: { enableDailyNotification: false },- channels: []- },- reValidateMode: "onBlur"- });-- const {- handleSubmit,- trigger,- reset,- watch,- formState: { errors }- } = formMethods;-- const watchedEventType = watch("eventType");- const applicationScoped = !!applicationId;- const formTabs = getFormTabs(watchedEventType, applicationScoped);- const channelsTabIndex = getChannelsTabIndex(watchedEventType, applicationScoped);-- useEffect(() => {- if (selectedTabIndex >= formTabs.length) {- setSelectedTabIndex(0);- }- }, [watchedEventType]); // eslint-disable-line react-hooks/exhaustive-deps-- const { mutateAsync: createAlert } = useCreatePkiAlertV2();- const { mutateAsync: updateAlert } = useUpdatePkiAlertV2();-- const handleModalClose = () => {- reset();- setSelectedTabIndex(0);- setExpandedChannel(undefined);- onOpenChange(false);- };-- React.useEffect(() => {- if (editingAlert && isEditing) {- reset({- name: editingAlert.name,- description: editingAlert.description || "",- eventType: editingAlert.eventType,- alertBefore: editingAlert.alertBefore || "30d",- filters: editingAlert.filters || [],- enabled: editingAlert.enabled,- notificationConfig: editingAlert.notificationConfig ?? { enableDailyNotification: false },- 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 ? SECRET_MASK : undefined- }- };- }- return channel;- }) || []- });- } else if (!isEditing) {- reset({- name: "",- description: "",- eventType: PkiAlertEventTypeV2.EXPIRATION,- alertBefore: "30d",- filters: [],- enabled: true,- notificationConfig: { enableDailyNotification: false },- channels: []- });- }- }, [editingAlert, isEditing, currentProject?.id, reset]);-- const onSubmit = async (data: TFormData) => {- if (!currentProject?.id) return;-- const processedData = {- ...data,- channels: data.channels?.map((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 TPkiAlertChannelConfigWebhook;-- // Determine what to send for signingSecret- let signingSecret: string | null | undefined;- if (webhookConfig.signingSecret === 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;- })- };-- try {- if (isEditing && (alertId || editingAlert?.id)) {- await updateAlert({- alertId: alertId || editingAlert!.id,- ...processedData- } as TUpdatePkiAlertV2);- } else {- await createAlert({- ...processedData,- ...(applicationId && { applicationId })- });- }-- createNotification({- text: `PKI alert ${isEditing ? "updated" : "created"} successfully`,- type: "success"- });-- handleModalClose();- } catch {- createNotification({- text: `Failed to ${isEditing ? "update" : "create"} PKI alert`,- type: "error"- });- }- };-- const handlePrev = () => {- if (selectedTabIndex === 0) {- onOpenChange(false);- return;- }- setSelectedTabIndex((prev) => prev - 1);- };-- const isStepValid = async (index: number) => trigger(formTabs[index].fields);-- const isFinalStep = selectedTabIndex === formTabs.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)();- return;- }-- const isValid = await isStepValid(selectedTabIndex);- if (!isValid) {- // If on channels tab and validation failed, expand first channel with error- if (selectedTabIndex === channelsTabIndex) {- const firstErrorIdx = getFirstChannelErrorIndex();- if (firstErrorIdx >= 0) {- setExpandedChannel(`channel-${firstErrorIdx}`);- }- }- return;- }-- setSelectedTabIndex((prev) => prev + 1);- };-- const isTabEnabled = async (index: number) => {- const validationPromises = [];- for (let i = index - 1; i >= 0; i -= 1) {- validationPromises.push(isStepValid(i));- }- const results = await Promise.all(validationPromises);- return results.every(Boolean);- };-- return (- <Modal isOpen={isOpen} onOpenChange={handleModalClose}>- <ModalContent- title={`${isEditing ? "Update" : "Create"} Certificate Alert`}- className="max-w-2xl"- closeOnOutsideClick={false}- >- <form- className={twMerge(- "flex flex-col",- hasPreviewTab(watchedEventType, applicationScoped) ? "min-h-[60vh]" : "min-h-[40vh]",- 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-start border-b-2 border-border-control">- {formTabs.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-border-bright text-foreground-secondary"- : "text-label-secondary"- }`- }- key={tab.key}- >- {index + 1}. {tab.name}- </Tab>- ))}- </Tab.List>- <Tab.Panels>- <CreatePkiAlertV2FormSteps- expandedChannel={expandedChannel}- setExpandedChannel={setExpandedChannel}- showPreview={hasPreviewTab(watchedEventType, applicationScoped)}- showFilters={!applicationScoped}- applicationId={applicationId}- />- </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">- {isFinalStep ? `${isEditing ? "Update" : "Create"} Alert` : "Next"}- </Button>- <Button onClick={handlePrev} colorSchema="secondary">- {selectedTabIndex === 0 ? "Cancel" : "Back"}- </Button>- </div>- </form>- </ModalContent>- </Modal>- );-};diff --git a/frontend/src/views/PkiAlertsV2Page/components/PkiAlertV2Row.tsx b/frontend/src/views/PkiAlertsV2Page/components/PkiAlertV2Row.tsxindex fc40481e75..77c7e0a6e3 100644--- a/frontend/src/views/PkiAlertsV2Page/components/PkiAlertV2Row.tsx+++ b/frontend/src/views/PkiAlertsV2Page/components/PkiAlertV2Row.tsx@@ -1,15 +1,6 @@-import {- faCircleInfo,- faEllipsisH,- faEye,- faPencil,- faPlay,- faStop,- faTrash-} from "@fortawesome/free-solid-svg-icons";+import { faCircleInfo, faEllipsisH, faEye, faTrash } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { createNotification } from "@app/components/notifications";import {DropdownMenu,DropdownMenuContent,@@ -21,38 +12,17 @@ import {Tr} from "@app/components/v2";import { Badge } from "@app/components/v3";-import { PkiAlertEventTypeV2, TPkiAlertV2, useUpdatePkiAlertV2 } from "@app/hooks/api/pkiAlertsV2";+import { PkiAlertEventTypeV2, TPkiAlertV2 } from "@app/hooks/api/pkiAlertsV2";import { formatAlertBefore, formatEventType } from "../utils/pki-alert-formatters";interface Props {alert: TPkiAlertV2;onView: () => void;- onEdit: () => void;onDelete: () => void;}-export const PkiAlertV2Row = ({ alert, onView, onEdit, onDelete }: Props) => {- const { mutateAsync: updateAlert } = useUpdatePkiAlertV2();-- const handleToggleAlert = async () => {- try {- await updateAlert({- alertId: alert.id,- enabled: !alert.enabled- });- createNotification({- text: `Alert ${!alert.enabled ? "enabled" : "disabled"} successfully`,- type: "success"- });- } catch {- createNotification({- text: "Failed to update alert status",- type: "error"- });- }- };-+export const PkiAlertV2Row = ({ alert, onView, onDelete }: Props) => {return (<Tr><Td>@@ -119,14 +89,6 @@ export const PkiAlertV2Row = ({ alert, onView, onEdit, onDelete }: Props) => {<FontAwesomeIcon icon={faEye} className="mr-2 h-4 w-4" />View details</DropdownMenuItem>- <DropdownMenuItem onClick={onEdit}>- <FontAwesomeIcon icon={faPencil} className="mr-2 h-4 w-4" />- Edit alert- </DropdownMenuItem>- <DropdownMenuItem onClick={handleToggleAlert}>- <FontAwesomeIcon icon={alert.enabled ? faStop : faPlay} className="mr-2 h-4 w-4" />- {alert.enabled ? "Disable" : "Enable"} alert- </DropdownMenuItem><DropdownMenuItem onClick={onDelete} className="text-danger"><FontAwesomeIcon icon={faTrash} className="mr-2 h-4 w-4" />Delete alertdiff --git a/frontend/src/views/PkiAlertsV2Page/components/index.ts b/frontend/src/views/PkiAlertsV2Page/components/index.tsindex e46bb445e7..834dc92f47 100644--- a/frontend/src/views/PkiAlertsV2Page/components/index.ts+++ b/frontend/src/views/PkiAlertsV2Page/components/index.ts@@ -1,3 +1,2 @@-export { CreatePkiAlertV2Modal } from "./CreatePkiAlertV2Modal";export { PkiAlertV2Row } from "./PkiAlertV2Row";export { ViewPkiAlertV2Modal } from "./ViewPkiAlertV2Modal";