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
Move project-level cert manager alerts to a dedicated provider
Carlos Monastyrskie6290c34f02f
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 108240ddfe..61b1d7de61 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -707,7 +707,7 @@ 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)` for resource-bound alerts**, enforced by the partial `alert_unique_scope_resource_event_bound` index. A provider that sets `supportsScopeWideAlerts` also accepts alerts with no `resourceId`: such an alert watches every resource of its type in scope (`findEnabledForEvent` matches it for any `resourceId`), several can watch the same event because they differ by condition, and `assertConditionInScope` is where the provider checks the IDs inside a condition, on create and on update (newly added IDs only). Certificate Manager-wide alerts are `cert-manager.application` alerts with no `resourceId`, narrowed by `applicationIds` and `profileIds`; creating or editing one requires unconditional certificate read, since it sends details from every application. Signer certificate expiration has its own provider, `cert-manager.signer` (`cert-manager-signer-alert-provider.ts`, event `cert-manager.signer.certificate.expiry`), that only exists scope-wide: it scans one row per certificate an active signer points at through `pki_signers.certificateId`, naming every signer that shares it (so a reissue moves the alert to the new certificate), takes no filters, and creating or editing one requires the project Admin role (unconditional `code-signers` read only opens the signer list; non-admins see only signers they are members of). Helpers both Certificate Manager providers share (expiry schema, dedup windows, license gate, audit and telemetry builders) live in `cert-manager-alert-fns.ts`. **Every provider hook is opt-in, and its absence must reproduce the behaviour identity alerts had before any other provider existed.** `recipientPolicy` decides who can receive: `atOrgScope` validates and resolves user and group recipients against the org instead of the alert's project, and `allowEmailAddresses` accepts plain `EMAIL` recipients and makes test sends validate recipients like create and update do, instead of silently dropping out-of-scope ones (application alerts set both). `includeLastRun` adds `lastRun` to alert responses, and `resourceName` is only returned by providers that implement `getResourceNames`, and `filters` (read-only `{ id, name }` lists for the IDs inside a condition, keyed by kind, such as `applications` and `profiles` on a Certificate Manager-wide alert, with a null name for deleted IDs, matching how approval policies return approvers) only by providers that implement `getFilters`. Resolve such names there rather than adding ID filters to another domain's list endpoint. `assertChannelTypesAllowed` is where a provider gates paid channel types on create and on update (new, retyped, or re-enabled channels only, so a downgraded org can still edit the alert). `getResourceNames` (batched) supplies the resource's display name for alert responses and for a provider's own audit events. `resolveProjectId` lets create, list and test sends omit `projectId` when the resource already belongs to one project (`resolveAlertProjectId` in `alert-provider-registry.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. `getAuditEvent` does the same for audit logs: a provider that needs distinct event types (application alerts log `create-pki-application-alert` and its siblings, with the application's ID and name) returns its own event, and every other provider falls back to the generic `create-alert` family via `buildGenericAlertAuditEvent`. Add a provider's own event interfaces next to the generic ones; never widen the generic ones. 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.+- **One alert per `(scope, resource, event)` for resource-bound alerts**, enforced by the partial `alert_unique_scope_resource_event_bound` index. A provider that sets `supportsScopeWideAlerts` also accepts alerts with no `resourceId`: such an alert watches every resource of its type in scope, several can watch the same event because they differ by condition, and `assertConditionInScope` is where the provider checks the IDs inside a condition, on create and on update (newly added IDs only). `findEnabledForEvent` matches exactly: the bound alerts for a `resourceId`, or the resource-less ones when it is null. To let a scope-wide provider hear another provider's events without a second outbox write, an event definition can declare `relayedFrom: { resourceType, eventKey }`; the consumer then runs the source resource's alerts plus every relaying provider's resource-less alerts (`alertProviderRegistry.relaysFor`), each under its own `eventType`. Certificate Manager-wide alerts are their own provider, `cert-manager` (`cert-manager-alert-provider.ts`, events `cert-manager.certificate.*`), narrowed by `applicationIds` and `profileIds`; its issuance, renewal and revocation events are relayed from the `cert-manager.application` events the certificate code emits, and creating or editing one requires unconditional certificate read, since it sends details from every application. `cert-manager.application` alerts are always bound to one application. Signer certificate expiration has its own provider, `cert-manager.signer` (`cert-manager-signer-alert-provider.ts`, event `cert-manager.signer.certificate.expiry`), that only exists scope-wide: it scans one row per certificate an active signer points at through `pki_signers.certificateId`, naming every signer that shares it (so a reissue moves the alert to the new certificate), takes no filters, and creating or editing one requires the project Admin role (unconditional `code-signers` read only opens the signer list; non-admins see only signers they are members of). Helpers the three Certificate Manager providers share (expiry schema, dedup windows, certificate payload, license gate, audit and telemetry builders) live in `cert-manager-alert-fns.ts`. **Every provider hook is opt-in, and its absence must reproduce the behaviour identity alerts had before any other provider existed.** `recipientPolicy` decides who can receive: `atOrgScope` validates and resolves user and group recipients against the org instead of the alert's project, and `allowEmailAddresses` accepts plain `EMAIL` recipients and makes test sends validate recipients like create and update do, instead of silently dropping out-of-scope ones (application alerts set both). `includeLastRun` adds `lastRun` to alert responses, and `resourceName` is only returned by providers that implement `getResourceNames`, and `filters` (read-only `{ id, name }` lists for the IDs inside a condition, keyed by kind, such as `applications` and `profiles` on a Certificate Manager-wide alert, with a null name for deleted IDs, matching how approval policies return approvers) only by providers that implement `getFilters`. Resolve such names there rather than adding ID filters to another domain's list endpoint. `assertChannelTypesAllowed` is where a provider gates paid channel types on create and on update (new, retyped, or re-enabled channels only, so a downgraded org can still edit the alert). `getResourceNames` (batched) supplies the resource's display name for alert responses and for a provider's own audit events. `resolveProjectId` lets create, list and test sends omit `projectId` when the resource already belongs to one project (`resolveAlertProjectId` in `alert-provider-registry.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. `getAuditEvent` does the same for audit logs: a provider that needs distinct event types (application alerts log `create-pki-application-alert` and its siblings, with the application's ID and name) returns its own event, and every other provider falls back to the generic `create-alert` family via `buildGenericAlertAuditEvent`. Add a provider's own event interfaces next to the generic ones; never widen the generic ones. 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 when the provider opts in** (`recipientPolicy.allowEmailAddresses`), 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`), and again at send time, so an address on a domain the org has since removed stops receiving alerts. The resolver sends to them directly and skips an address that a user recipient on the same channel already covers.- **`findScheduledTargets` 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.- **A `findScheduledTargets` that caps its own row count must honour `alreadyAlerted`.** The engine passes `{ alertId, channelIds, since }` (the alert's enabled channels and its dedup cutoff), and the provider drops targets every one of those channels already delivered since then, in SQL before the limit. Dedup otherwise runs after the fetch, so once more targets are due than the cap, the same head of the list comes back every run, is deduped, and nothing past it is ever alerted. That filter alone is not enough when the dedup window is shorter than the scan interval (a daily reminder), because yesterday's head is due again, so such a provider also orders the targets this alert notified least recently first, then by expiry. The certificate alert DAL does both in `findExpiringCertificates`.diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 39309a84ad..5f1ab334ed 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -2421,7 +2421,7 @@ export const ALERTING = {LIST: {resourceType: "The type of resource to list alerts for.",resourceId:- "The ID of the resource to list alerts for. If omitted, lists every alert on the resource type. For resource types that support alerts covering all of their resources, such as `cert-manager.application`, lists only those alerts.",+ "The ID of the resource to list alerts for. If omitted, lists every alert on the resource type. For resource types that support alerts covering all of their resources, such as `cert-manager`, lists only those alerts.",projectId: "The ID of the project to list alerts in.",enabled: "Whether to list only enabled or only disabled alerts."},diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex dccdfa45fd..602403308f 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -249,6 +249,7 @@ 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 { certManagerAlertProviderFactory } from "@app/services/alert/providers/cert-manager-alert-provider";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 { certManagerSignerAlertDALFactory } from "@app/services/alert/providers/cert-manager-signer-alert-dal";@@ -1099,6 +1100,13 @@ export const registerRoutes = async ();alertProviderRegistry.register(certManagerApplicationAlertProviderFactory({+ certManagerApplicationAlertDAL,+ permissionService,+ licenseService+ })+ );+ alertProviderRegistry.register(+ certManagerAlertProviderFactory({certManagerApplicationAlertDAL,permissionService,licenseService,diff --git a/backend/src/services/alert/alert-dal.test.ts b/backend/src/services/alert/alert-dal.test.tsindex 39a72c878c..be3528593b 100644--- a/backend/src/services/alert/alert-dal.test.ts+++ b/backend/src/services/alert/alert-dal.test.ts@@ -119,7 +119,7 @@ describe("alert dal", () => {expect(calls.where).toContainEqual([`${TableName.Alert}.orgId`, "org-1"]);expect(calls.where).toContainEqual([`${TableName.Alert}.resourceType`, "approval.workflow"]);expect(calls.where).toContainEqual([`${TableName.Alert}.resourceId`, "policy-1"]);- expect(calls.orWhereNull).toContainEqual(`${TableName.Alert}.resourceId`);+ expect(calls.orWhereNull ?? []).not.toContainEqual(`${TableName.Alert}.resourceId`);expect(calls.where).toContainEqual([`${TableName.Alert}.eventType`, "approval.workflow.request_opened"]);// Mirrors the cron's filter: an event must never trigger a scheduled alert.expect(calls.where).toContainEqual([`${TableName.Alert}.triggerType`, "event"]);diff --git a/backend/src/services/alert/alert-dal.ts b/backend/src/services/alert/alert-dal.tsindex 8d0c8e06ca..487b5f136f 100644--- a/backend/src/services/alert/alert-dal.ts+++ b/backend/src/services/alert/alert-dal.ts@@ -77,14 +77,8 @@ export const alertDALFactory = (db: TDbClient) => {.where(`${TableName.AlertChannel}.enabled`, true));- void query.where(- (builder) =>- void (filter.resourceId- ? builder- .where(`${TableName.Alert}.resourceId`, filter.resourceId)- .orWhereNull(`${TableName.Alert}.resourceId`)- : builder.whereNull(`${TableName.Alert}.resourceId`))- );+ if (filter.resourceId) void query.where(`${TableName.Alert}.resourceId`, filter.resourceId);+ else void query.whereNull(`${TableName.Alert}.resourceId`);if (filter.projectId) {void query.where(diff --git a/backend/src/services/alert/alert-event-consumer.test.ts b/backend/src/services/alert/alert-event-consumer.test.tsindex 9322a80b1f..745065a648 100644--- a/backend/src/services/alert/alert-event-consumer.test.ts+++ b/backend/src/services/alert/alert-event-consumer.test.ts@@ -12,7 +12,8 @@ vi.mock("@app/lib/logger", () => ({const ORG_ID = "11111111-1111-1111-1111-111111111111";const EVENT_TYPE = "approval.workflow.request_opened";-const makeAlert = (id: string) => ({ id, resourceType: "approval.workflow", orgId: ORG_ID }) as never;+const makeAlert = (id: string) =>+ ({ id, resourceType: "approval.workflow", orgId: ORG_ID, eventType: EVENT_TYPE }) as never;const makePayload = (overrides?: Record<string, unknown>) => ({orgId: ORG_ID,@@ -36,11 +37,13 @@ const buildConsumer = (opts?: {alerts?: unknown[];results?: AlertDispatchOutcome[];eventKeys?: string[];- findAlerts?: () => Promise<unknown[]>;+ findAlerts?: (filter: { resourceType: string; resourceId?: string | null; eventType: string }) => Promise<unknown[]>;+ relays?: { resourceType: string; eventKey: string }[];}) => {const runs: {alertId: string;eventId: string;+ eventType: string;targetIds: string[];payload?: Record<string, unknown>;}[] = [];@@ -50,18 +53,24 @@ const buildConsumer = (opts?: {const eventKeys = opts?.eventKeys ?? [EVENT_TYPE];const consumer = alertEventConsumerFactory({alertDAL: {- findEnabledForEvent: async () => {+ findEnabledForEvent: async (filter) => {lookups += 1;- if (opts?.findAlerts) return (await opts.findAlerts()) as never;+ if (opts?.findAlerts) return (await opts.findAlerts(filter)) as never;return (opts?.alerts ?? [makeAlert("alert-1")]) as never;}},alertEngine: {runAlertForEvent: async (alert: { id: string },- input: { eventId: string; targetIds: string[]; payload: Record<string, unknown> }+ input: { eventId: string; eventType: string; targetIds: string[]; payload: Record<string, unknown> }) => {- runs.push({ alertId: alert.id, eventId: input.eventId, targetIds: input.targetIds, payload: input.payload });+ runs.push({+ alertId: alert.id,+ eventId: input.eventId,+ eventType: input.eventType,+ targetIds: input.targetIds,+ payload: input.payload+ });const result = results[Math.min(runIdx, results.length - 1)];runIdx += 1;return result;@@ -69,6 +78,7 @@ const buildConsumer = (opts?: {} as never,alertProviderRegistry: {eventTriggeredKeys: () => new Set(eventKeys),+ relaysFor: () => opts?.relays ?? [],get: (resourceType: string) =>resourceType === "approval.workflow"? ({ events: eventKeys.map((key) => ({ key, triggerType: AlertTriggerType.Event })) } as never)@@ -107,6 +117,44 @@ describe("alert event consumer", () => {expect(runs[0].targetIds).toEqual(["req-1"]);});+ test("also runs the alerts of a provider that relays the event, as resource-less alerts on its own event", async () => {+ const lookupsSeen: { resourceType: string; resourceId?: string | null; eventType: string }[] = [];+ const { consumer, runs } = buildConsumer({+ relays: [{ resourceType: "approval.org", eventKey: "approval.org.request_opened" }],+ findAlerts: async (filter) => {+ lookupsSeen.push(filter);+ return [+ {+ id: filter.resourceType === "approval.org" ? "relayed-alert" : "bound-alert",+ resourceType: filter.resourceType,+ orgId: ORG_ID,+ eventType: filter.eventType+ }+ ];+ }+ });++ const [result] = await consumer.handle([makeEvent()]);++ expect(result.status).toBe(EventResultStatus.Delivered);+ expect(lookupsSeen).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ resourceType: "approval.workflow", resourceId: "policy-1", eventType: EVENT_TYPE }),+ expect.objectContaining({+ resourceType: "approval.org",+ resourceId: null,+ eventType: "approval.org.request_opened"+ })+ ])+ );+ expect(runs.map((run) => [run.alertId, run.eventType])).toEqual(+ expect.arrayContaining([+ ["bound-alert", EVENT_TYPE],+ ["relayed-alert", "approval.org.request_opened"]+ ])+ );+ });+// The outbox row id is stable across attempts, so it's the only key a retry can use to find what// already went out.test("hands the engine the event id so a retry can skip channels that already delivered", async () => {diff --git a/backend/src/services/alert/alert-event-consumer.ts b/backend/src/services/alert/alert-event-consumer.tsindex 0180f2f389..030c2080c9 100644--- a/backend/src/services/alert/alert-event-consumer.ts+++ b/backend/src/services/alert/alert-event-consumer.ts@@ -28,7 +28,7 @@ type TAlertEventPayload = z.infer<typeof AlertEventPayloadSchema>;export type TAlertEventConsumerDep = {alertDAL: Pick<TAlertDALFactory, "findEnabledForEvent">;alertEngine: Pick<TAlertEngine, "runAlertForEvent">;- alertProviderRegistry: Pick<TAlertProviderRegistry, "get" | "eventTriggeredKeys">;+ alertProviderRegistry: Pick<TAlertProviderRegistry, "get" | "eventTriggeredKeys" | "relaysFor">;};type TAlertLookup = TAlertDALFactory["findEnabledForEvent"];@@ -70,13 +70,13 @@ export const alertEventConsumerFactory = ({};}- const alerts = await findAlerts({- orgId,- projectId,- resourceType,- resourceId,- eventType: event.eventType- });+ const lookups = [+ { resourceType, resourceId, eventType: event.eventType },+ ...alertProviderRegistry+ .relaysFor(resourceType, event.eventType)+ .map((relay) => ({ resourceType: relay.resourceType, resourceId: null, eventType: relay.eventKey }))+ ];+ const alerts = (await Promise.all(lookups.map((lookup) => findAlerts({ orgId, projectId, ...lookup })))).flat();if (alerts.length === 0) {recordAlertDispatchOutcomeMetric({ resourceType, outcome: AlertDispatchOutcome.NoMatchingAlert });@@ -89,7 +89,7 @@ export const alertEventConsumerFactory = ({// eslint-disable-next-line no-await-in-loop -- bounds DB connection use; a retry skips channels already delivered for this eventconst outcome = await alertEngine.runAlertForEvent(alert, {eventId: id,- eventType: event.eventType,+ eventType: alert.eventType,occurredAt: event.occurredAt,targetIds,payload: (event.payload ?? {}) as Record<string, unknown>diff --git a/backend/src/services/alert/alert-provider-registry.ts b/backend/src/services/alert/alert-provider-registry.tsindex b8338a97b9..8810ca4ea4 100644--- a/backend/src/services/alert/alert-provider-registry.ts+++ b/backend/src/services/alert/alert-provider-registry.ts@@ -70,5 +70,17 @@ export const alertProviderRegistryFactory = () => {return eventTriggeredKeyCache;};- return { register, get, resourceTypes, eventTriggeredKeys };+ const relaysFor = (resourceType: string, eventKey: string): { resourceType: string; eventKey: string }[] =>+ [...providers.values()].flatMap((provider) =>+ provider.events+ .filter(+ (event) =>+ event.triggerType === AlertTriggerType.Event &&+ event.relayedFrom?.resourceType === resourceType &&+ event.relayedFrom.eventKey === eventKey+ )+ .map((event) => ({ resourceType: provider.resourceType, eventKey: event.key }))+ );++ return { register, get, resourceTypes, eventTriggeredKeys, relaysFor };};diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.tsindex 9d7f17a7c2..1149160c63 100644--- a/backend/src/services/alert/alert-types.ts+++ b/backend/src/services/alert/alert-types.ts@@ -21,6 +21,7 @@ export type TAlertEventDefinition = {key: string;triggerType: AlertTriggerType;conditionSchema: z.ZodTypeAny;+ relayedFrom?: { resourceType: string; eventKey: string };};export enum AlertRunStatus {diff --git a/backend/src/services/alert/providers/cert-manager-alert-fns.ts b/backend/src/services/alert/providers/cert-manager-alert-fns.tsindex 2daf4a27ee..7ee98664a9 100644--- a/backend/src/services/alert/providers/cert-manager-alert-fns.ts+++ b/backend/src/services/alert/providers/cert-manager-alert-fns.ts@@ -1,21 +1,29 @@+import { ForbiddenError } from "@casl/ability";import { z } from "zod";+import { ActionProjectType } from "@app/db/schemas";import { Event as TAuditEvent, EventType } from "@app/ee/services/audit-log/audit-log-types";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";-import { ProjectPermissionActions } from "@app/ee/services/permission/project-permission";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { TCertManagerProjectResolverFactory } from "@app/services/cert-manager-instance/cert-manager-project-resolver";+import { getRevocationReasonLabel } from "@app/services/pki-alert-v2/pki-alert-v2-types";import { PkiAlertScope, PostHogEventTypes } from "@app/services/telemetry/telemetry-types";-import { AlertChannelType } from "../alert-channel-types";-import { durationToDays } from "../alert-format-fns";+import { AlertChannelType, TAlertPayload, TAlertSeverity } from "../alert-channel-types";+import { durationToDays, expirySeverity, formatUtcDate, humanizeDays } from "../alert-format-fns";import {AlertAuditAction,AlertPermissionAction,AlertTelemetryAction,+ DEFAULT_DEDUP_WINDOW_HOURS,TAlertAuditInput,+ TAlertContext,+ TAlertPermissionInput,TAlertTelemetryEvent} from "../alert-types";+import { TApplicationAlertCertificate } from "./cert-manager-application-alert-dal";const MIN_ALERT_BEFORE_DAYS = 1;const MAX_ALERT_BEFORE_DAYS = 365;@@ -39,13 +47,19 @@ const DAILY_SCAN_DEDUP_MARGIN_HOURS = 4;const dayMultipleDedupWindowHours = (days: number): number => days * 24 - DAILY_SCAN_DEDUP_MARGIN_HOURS;-export const expirationDedupWindowHours = (days: number, dailyReminder?: boolean): number => {+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 const expiryDedupWindowHours = (condition: unknown): number => {+ const parsed = ExpiryFieldsSchema.safeParse(condition);+ if (!parsed.success) return DEFAULT_DEDUP_WINDOW_HOURS;+ return expirationDedupWindowHours(durationToDays(parsed.data.alertBefore), parsed.data.dailyReminder);+};+export const CERT_MANAGER_ALERT_PERMISSION_ACTIONS: Record<AlertPermissionAction, ProjectPermissionActions> = {[AlertPermissionAction.Read]: ProjectPermissionActions.Read,[AlertPermissionAction.Create]: ProjectPermissionActions.Create,@@ -53,6 +67,29 @@ export const CERT_MANAGER_ALERT_PERMISSION_ACTIONS: Record<AlertPermissionAction[AlertPermissionAction.Delete]: ProjectPermissionActions.Delete};+export const assertNoAlertResource = (resourceId: string | null | undefined, message: string) => {+ if (resourceId) throw new BadRequestError({ message });+};++export const getCertManagerAlertPermission = async (+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">,+ { action, projectId, actor }: Pick<TAlertPermissionInput, "action" | "actor"> & { projectId: string }+) => {+ const result = await permissionService.getProjectPermission({+ actor: actor.actor,+ actorId: actor.actorId,+ projectId,+ actorAuthMethod: actor.actorAuthMethod,+ actorOrgId: actor.actorOrgId,+ actionProjectType: ActionProjectType.CertificateManager+ });+ ForbiddenError.from(result.permission).throwUnlessCan(+ CERT_MANAGER_ALERT_PERMISSION_ACTIONS[action],+ ProjectPermissionSub.PkiAlerts+ );+ return result;+};+export const splitAltNames = (altNames: string | null): string[] =>(altNames ?? "").split(",")@@ -135,3 +172,132 @@ export const buildPkiAlertTelemetryEvent = (return { event: PostHogEventTypes.PkiAlertDeleted, properties };}};++export enum CertificateAlertKind {+ Expiry = "expiry",+ Issuance = "issuance",+ Renewal = "renewal",+ Revocation = "revocation"+}++const CERTIFICATE_ALERT_KIND_LABELS: Record<CertificateAlertKind, string> = {+ [CertificateAlertKind.Expiry]: "Expiration",+ [CertificateAlertKind.Issuance]: "Issuance",+ [CertificateAlertKind.Renewal]: "Renewal",+ [CertificateAlertKind.Revocation]: "Revocation"+};++export const CERTIFICATE_ALERT_KIND_TELEMETRY_TYPES: Record<CertificateAlertKind, string> = {+ [CertificateAlertKind.Expiry]: "expiration",+ [CertificateAlertKind.Issuance]: "issuance",+ [CertificateAlertKind.Renewal]: "renewal",+ [CertificateAlertKind.Revocation]: "revocation"+};++const CERTIFICATE_ALERT_KIND_VERBS: Record<CertificateAlertKind, string> = {+ [CertificateAlertKind.Expiry]: "is expiring",+ [CertificateAlertKind.Issuance]: "was issued",+ [CertificateAlertKind.Renewal]: "was renewed",+ [CertificateAlertKind.Revocation]: "was revoked"+};++const certificateSeverity = (kind: CertificateAlertKind, targets: TApplicationAlertCertificate[]): TAlertSeverity => {+ if (kind === CertificateAlertKind.Expiry) return expirySeverity(targets.map((target) => target.notAfter));+ if (kind === CertificateAlertKind.Revocation) return "warning";+ return "info";+};++const inApplication = (applicationName?: string | null) =>+ applicationName ? ` in application '${applicationName}'` : "";++export const buildCertificateAlertPayload = ({+ alert,+ targets,+ viewUrl,+ kind,+ webhookSource,+ resourceOwnerKind,+ applicationName+}: {+ alert: TAlertContext;+ targets: TApplicationAlertCertificate[];+ viewUrl: string;+ kind: CertificateAlertKind;+ webhookSource?: string;+ resourceOwnerKind: string;+ applicationName: string | null;+}): TAlertPayload => {+ const alertBefore =+ kind === CertificateAlertKind.Expiry+ ? (alert.condition as { alertBefore?: string } | null)?.alertBefore+ : undefined;+ const verb = CERTIFICATE_ALERT_KIND_VERBS[kind];+ const certificates = `${targets.length} certificate${targets.length === 1 ? "" : "s"}`;+ let summary = `${certificates} ${verb}${inApplication(applicationName)}`;+ if (alertBefore) {+ summary = `${certificates}${inApplication(applicationName)} expiring within ${humanizeDays(durationToDays(alertBefore))}`;+ } else if (targets.length === 1) {+ summary = `Certificate '${certificateDisplayName(targets[0])}' ${verb}${inApplication(targets[0].applicationName)}`;+ }++ return {+ alert: {+ id: alert.id,+ name: alert.name,+ orgId: alert.orgId,+ ...(alert.projectId ? { projectId: alert.projectId } : {}),+ resourceType: alert.resourceType,+ ...(alert.resourceId ? { resourceId: alert.resourceId } : {}),+ ...(alertBefore ? { condition: alertBefore } : {}),+ viewUrl+ },+ eventKey: alert.eventType,+ eventLabel: CERTIFICATE_ALERT_KIND_LABELS[kind],+ webhookType: `com.infisical.${alert.eventType}`,+ webhookSource,+ resourceKind: "Certificate",+ resourceOwnerKind,+ severity: certificateSeverity(kind, targets),+ summary,+ items: targets.map((certificate) => {+ const revocationReason =+ kind === CertificateAlertKind.Revocation ? getRevocationReasonLabel(certificate.revocationReason) : undefined;+ const altNames = splitAltNames(certificate.altNames);+ const name = certificateDisplayName(certificate);+ return {+ id: certificate.id,+ title: name,+ summary:+ kind === CertificateAlertKind.Expiry+ ? `Certificate '${name}'${inApplication(certificate.applicationName)} expires on ${formatUtcDate(certificate.notAfter)}`+ : `Certificate '${name}' ${verb}${inApplication(certificate.applicationName)}`,+ severity: certificateSeverity(kind, [certificate]),+ fields: [+ { label: "Serial Number", value: certificate.serialNumber },+ ...(altNames.length ? [{ label: "SANs", value: altNames.join(", ") }] : []),+ ...(certificate.profileName ? [{ label: "Profile", value: certificate.profileName }] : []),+ ...(!alert.resourceId && certificate.applicationName+ ? [{ label: "Application", value: certificate.applicationName }]+ : []),+ { label: "Expires", value: formatUtcDate(certificate.notAfter) },+ ...(revocationReason ? [{ label: "Revocation Reason", value: revocationReason }] : [])+ ],+ resource: {+ id: certificate.id,+ serialNumber: certificate.serialNumber,+ commonName: certificate.commonName,+ altNames,+ status: certificate.status,+ notBefore: certificate.notBefore.toISOString(),+ notAfter: certificate.notAfter.toISOString(),+ revokedAt: certificate.revokedAt?.toISOString() ?? null,+ revocationReason: certificate.revocationReason,+ profileId: certificate.profileId,+ profileName: certificate.profileName,+ applicationId: certificate.applicationId,+ applicationName: certificate.applicationName+ }+ };+ })+ };+};diff --git a/backend/src/services/alert/providers/cert-manager-alert-provider.test.ts b/backend/src/services/alert/providers/cert-manager-alert-provider.test.tsnew file mode 100644index 0000000000..80a81a7d59--- /dev/null+++ b/backend/src/services/alert/providers/cert-manager-alert-provider.test.ts@@ -0,0 +1,538 @@+import { createMongoAbility } from "@casl/ability";+import { vi } from "vitest";++import { PkiAlertScope, PostHogEventTypes } from "@app/services/telemetry/telemetry-types";++import { AlertChannelType } from "../alert-channel-types";+import { AlertAuditAction, AlertPermissionAction, AlertTelemetryAction, TAlertContext } from "../alert-types";+import { certManagerAlertProviderFactory, TCertManagerAlertProviderDep } from "./cert-manager-alert-provider";+import { TApplicationAlertCertificate } from "./cert-manager-application-alert-dal";++vi.mock("@app/lib/config/env", () => ({+ getConfig: () => ({ SITE_URL: "https://app.infisical.com" })+}));++const RESOURCE_TYPE = "cert-manager";+const EXPIRY_EVENT = "cert-manager.certificate.expiry";+const ISSUANCE_EVENT = "cert-manager.certificate.issuance";+const REVOCATION_EVENT = "cert-manager.certificate.revocation";+const APPLICATION_ID = "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90";+const OTHER_APPLICATION_ID = "6c8e4a1f-9b2d-4f3c-8e7a-2b3c4d5e6f70";+const PROFILE_ID = "7d9f5b2a-0c3e-4a4d-9f8b-3c4d5e6f7081";++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",+ profileId: "profile-1",+ profileName: "tls-server",+ status: "active",+ notBefore: new Date("2026-09-01T00:00:00.000Z"),+ notAfter: futureDate(5),+ revokedAt: null,+ revocationReason: null,+ applicationId: "app-1",+ 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: null,+ 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;+ onFindApplicationIds?: (ids: string[]) => void;+ abilityRules?: { action: string; subject: string; inverted?: boolean; conditions?: unknown }[];+ 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.some((id) => id.toLowerCase() === 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 ?? [];+ },+ findProjectApplicationIds: async (_projectId: string, ids: string[]) => {+ opts?.onFindApplicationIds?.(ids);+ return ids.some((id) => id.toLowerCase() === application.id) ? [application.id] : [];+ },+ findProjectProfileIds: async (_projectId: string, ids: string[]) => ids.filter((id) => id === PROFILE_ID),+ findProfileNamesByIds: async (_projectId: string, ids: string[]) =>+ ids.filter((id) => id === PROFILE_ID).map((id) => ({ id, name: "tls-server" }))+ };+ const ability = () =>+ createMongoAbility((opts?.abilityRules ?? [{ action: "read", subject: "pki-alerts" }]) as never);+ const permissionService = {+ getProjectPermission: vi.fn(async () => ({ permission: ability() }))+ };+ const licenseService = {+ getPlan: async () => ({ pkiEnterpriseAlerting: opts?.pkiEnterpriseAlerting ?? false })+ };+ const provider = certManagerAlertProviderFactory({+ certManagerApplicationAlertDAL: dal,+ permissionService,+ licenseService,+ certManagerProjectResolver: {+ getActiveProjectId: async (orgId: string) => (orgId === "org-1" ? "proj-1" : null)+ }+ } as unknown as TCertManagerAlertProviderDep);+ 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 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 relayed from the application events and take only optional filters", () => {+ const { provider } = buildProvider();+ expect(provider.resourceType).toBe("cert-manager");+ expect(provider.supportsScopeWideAlerts).toBe(true);+ const eventTriggered = provider.events.filter((event) => event.triggerType === "event");+ expect(eventTriggered.map((event) => [event.key, event.relayedFrom])).toEqual([+ [+ ISSUANCE_EVENT,+ { resourceType: "cert-manager.application", eventKey: "cert-manager.application.certificate.issuance" }+ ],+ [+ "cert-manager.certificate.renewal",+ { resourceType: "cert-manager.application", eventKey: "cert-manager.application.certificate.renewal" }+ ],+ [+ REVOCATION_EVENT,+ { resourceType: "cert-manager.application", eventKey: "cert-manager.application.certificate.revocation" }+ ]+ ]);+ eventTriggered.forEach((event) => {+ expect(event.conditionSchema.safeParse(null).success).toBe(true);+ expect(event.conditionSchema.safeParse({ profileIds: [PROFILE_ID] }).success).toBe(true);+ expect(event.conditionSchema.safeParse({ profileIds: [] }).success).toBe(false);+ expect(event.conditionSchema.safeParse({ alertBefore: "30d" }).success).toBe(false);+ });+ });++ test("filters must be non-empty UUID lists and are stored as sent", () => {+ const schema = expiryConditionSchema(buildProvider().provider);+ expect(+ schema.safeParse({ alertBefore: "30d", applicationIds: [APPLICATION_ID], profileIds: [PROFILE_ID] }).success+ ).toBe(true);+ expect(schema.safeParse({ alertBefore: "30d", applicationIds: ["not-a-uuid"] }).success).toBe(false);+ expect(schema.safeParse({ alertBefore: "30d", applicationIds: [] }).success).toBe(false);+ const upper = schema.safeParse({ alertBefore: "30d", applicationIds: [APPLICATION_ID.toUpperCase()] });+ expect(upper.success && (upper.data as { applicationIds: string[] }).applicationIds).toEqual([+ APPLICATION_ID.toUpperCase()+ ]);+ });++ test("filters reject an ID listed twice, in any case, instead of storing the duplicate", () => {+ const schema = expiryConditionSchema(buildProvider().provider);+ const duplicated = schema.safeParse({+ alertBefore: "30d",+ applicationIds: [APPLICATION_ID, APPLICATION_ID.toUpperCase()]+ });+ expect(duplicated.success).toBe(false);+ expect(duplicated.error?.issues[0].message).toBe(+ `applicationIds lists the same ID more than once: '${APPLICATION_ID.toUpperCase()}'`+ );+ expect(schema.safeParse({ alertBefore: "30d", profileIds: [PROFILE_ID, PROFILE_ID] }).success).toBe(false);+ });++ test("filter IDs match case-insensitively when checked and named", async () => {+ const { provider } = buildProvider();+ await expect(+ provider.assertConditionInScope?.({+ projectId: "proj-1",+ condition: { applicationIds: [APPLICATION_ID.toUpperCase()] }+ })+ ).resolves.toBeUndefined();+ const names = await provider.getFilters?.({+ orgId: "org-1",+ projectId: "proj-1",+ alerts: [{ id: "alert-1", condition: { applicationIds: [APPLICATION_ID.toUpperCase()] } }]+ });+ expect(names?.get("alert-1")).toEqual({+ applications: [{ id: APPLICATION_ID.toUpperCase(), name: "payments-api" }],+ profiles: []+ });+ });++ test("findScheduledTargets scans nothing when the alert has no channel to deliver to", async () => {+ let scanned = false;+ const { provider } = buildProvider({+ onFindExpiring: () => {+ scanned = true;+ }+ });++ const targets = await provider.findScheduledTargets({+ orgId: "org-1",+ projectId: "proj-1",+ resourceId: null,+ eventType: EXPIRY_EVENT,+ condition: { alertBefore: "2w" },+ asOf: new Date(),+ alreadyAlerted: { alertId: "alert-1", channelIds: [], since: new Date() }+ });++ expect(targets).toEqual([]);+ expect(scanned).toBe(false);+ });++ test("findScheduledTargets and findEventTargets scan the whole project for an alert with no application", async () => {+ let scheduledArgs: Record<string, unknown> | undefined;+ let eventArgs: Record<string, unknown> | undefined;+ const { provider } = buildProvider({+ onFindExpiring: (value) => {+ scheduledArgs = value;+ },+ onFindByIds: (value) => {+ eventArgs = value;+ }+ });+ await provider.findScheduledTargets({+ orgId: "org-1",+ projectId: "proj-1",+ resourceId: null,+ eventType: EXPIRY_EVENT,+ condition: { alertBefore: "2w", profileIds: [PROFILE_ID] },+ asOf: new Date(),+ alreadyAlerted: { alertId: "alert-1", channelIds: ["channel-1"], since: new Date() }+ });+ await provider.findEventTargets({+ orgId: "org-1",+ projectId: "proj-1",+ resourceId: null,+ eventType: ISSUANCE_EVENT,+ condition: { applicationIds: [APPLICATION_ID] },+ targetIds: ["cert-1"]+ } as never);++ expect(scheduledArgs).toMatchObject({+ projectId: "proj-1",+ profileIds: [PROFILE_ID],+ alertBeforeInterval: "14 days"+ });+ expect(scheduledArgs?.applicationId).toBeUndefined();+ expect(eventArgs).toMatchObject({+ projectId: "proj-1",+ applicationIds: [APPLICATION_ID],+ certificateIds: ["cert-1"]+ });+ });++ 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 for an alert with no application names Certificate Manager and lists each application", () => {+ const { provider } = buildProvider();+ const payload = provider.buildPayload(+ alertContext({ resourceId: null }),+ [sampleCertificate({ notAfter: futureDate(20) })],+ "https://app.infisical.com/view"+ );++ expect(payload.resourceOwnerKind).toBe("Certificate Manager");+ expect(payload.alert.resourceType).toBe("cert-manager");+ expect(payload.alert).not.toHaveProperty("resourceId");+ expect(payload.webhookSource).toBe("/alerts/alert-1");+ expect(payload.eventKey).toBe("cert-manager.certificate.expiry");+ expect(payload.webhookType).toBe("com.infisical.cert-manager.certificate.expiry");+ expect(payload.summary).toBe("1 certificate expiring within 30 days");+ expect(payload.items[0].fields).toContainEqual({ label: "Application", value: "payments-api" });+ });++ test("assertConditionInScope accepts known filter IDs and rejects unknown ones", async () => {+ const { provider } = buildProvider();+ await expect(+ provider.assertConditionInScope?.({+ projectId: "proj-1",+ condition: { applicationIds: [APPLICATION_ID], profileIds: [PROFILE_ID] }+ })+ ).resolves.toBeUndefined();+ await expect(+ provider.assertConditionInScope?.({ projectId: "proj-1", condition: { applicationIds: [OTHER_APPLICATION_ID] } })+ ).rejects.toThrow(`Application not found in Certificate Manager: '${OTHER_APPLICATION_ID}'`);+ });++ test("refuses a resource everywhere a caller can name one", async () => {+ const { provider } = buildProvider({+ abilityRules: [+ { action: "create", subject: "pki-alerts" },+ { action: "read", subject: "certificates" }+ ]+ });+ const create = { action: AlertPermissionAction.Create, orgId: "org-1", projectId: "proj-1", actor };+ await expect(provider.assertPermission({ ...create, resourceId: APPLICATION_ID })).rejects.toThrow(+ "can't be bound to one"+ );+ await expect(provider.assertResourceInScope({ orgId: "org-1", resourceId: APPLICATION_ID })).rejects.toThrow(+ "can't be bound to one"+ );+ await expect(provider.resolveProjectId?.({ orgId: "org-1", resourceId: APPLICATION_ID })).rejects.toThrow(+ "can't be bound to one"+ );+ });++ test("delivers under its own resource type and keys, links to the inventory and sources from the alert", async () => {+ const { provider } = buildProvider();+ const alert = alertContext({ eventType: ISSUANCE_EVENT, condition: null });+ const viewUrl = await provider.buildViewUrl(alert);+ const payload = provider.buildPayload(alert, [sampleCertificate()], viewUrl);++ expect(viewUrl).toBe("https://app.infisical.com/organizations/org-1/projects/cert-manager/proj-1/inventory");+ expect(payload.alert.resourceType).toBe("cert-manager");+ expect(payload.alert).not.toHaveProperty("resourceId");+ expect(payload.eventKey).toBe(ISSUANCE_EVENT);+ expect(payload.webhookType).toBe(`com.infisical.${ISSUANCE_EVENT}`);+ expect(payload.webhookSource).toBe("/alerts/alert-1");+ expect(payload.eventLabel).toBe("Issuance");+ });++ test("assertConditionInScope only checks IDs the update adds, so a deleted one can stay", async () => {+ const lookups: string[][] = [];+ const { provider } = buildProvider({ onFindApplicationIds: (ids) => lookups.push(ids) });+ await expect(+ provider.assertConditionInScope?.({+ projectId: "proj-1",+ condition: { applicationIds: [OTHER_APPLICATION_ID, APPLICATION_ID] },+ previousCondition: { applicationIds: [OTHER_APPLICATION_ID] }+ })+ ).resolves.toBeUndefined();+ expect(lookups).toEqual([[APPLICATION_ID]]);+ });++ test("lists each alert's filter IDs with their names, with a null name for IDs that no longer exist", async () => {+ const { provider } = buildProvider();+ const names = await provider.getFilters?.({+ orgId: "org-1",+ projectId: "proj-1",+ alerts: [+ {+ id: "alert-1",+ condition: { applicationIds: [APPLICATION_ID, OTHER_APPLICATION_ID], profileIds: [PROFILE_ID] }+ },+ { id: "alert-2", condition: null }+ ]+ });++ expect(names?.get("alert-1")).toEqual({+ applications: [+ { id: APPLICATION_ID, name: "payments-api" },+ { id: OTHER_APPLICATION_ID, name: null }+ ],+ profiles: [{ id: PROFILE_ID, name: "tls-server" }]+ });+ expect(names?.get("alert-2")).toEqual({ applications: [], profiles: [] });+ });++ test("an alert with no application logs Certificate Manager audit events naming its filters", () => {+ const { provider } = buildProvider();+ const alert = {+ id: "alert-1",+ name: "prod-expiry",+ resourceType: RESOURCE_TYPE,+ resourceId: null,+ eventType: EXPIRY_EVENT,+ condition: {+ alertBefore: "30d",+ applicationIds: [APPLICATION_ID, OTHER_APPLICATION_ID],+ profileIds: [PROFILE_ID]+ },+ filters: {+ applications: [{ id: APPLICATION_ID, name: "payments-api" }],+ profiles: [{ id: PROFILE_ID, name: "tls-server" }]+ }+ };+ const metadata = {+ alertId: "alert-1",+ name: "prod-expiry",+ eventType: EXPIRY_EVENT,+ applications: [+ { id: APPLICATION_ID, name: "payments-api" },+ { id: OTHER_APPLICATION_ID, name: null }+ ],+ profiles: [{ id: PROFILE_ID, name: "tls-server" }]+ };++ expect(provider.getAuditEvent?.({ action: AlertAuditAction.Create, alert })).toEqual({+ type: "create-certificate-manager-alert",+ metadata+ });+ expect(provider.getAuditEvent?.({ action: AlertAuditAction.Delete, alert })).toEqual({+ type: "delete-certificate-manager-alert",+ metadata+ });+ expect(+ provider.getAuditEvent?.({+ action: AlertAuditAction.TestChannel,+ test: {+ resourceType: RESOURCE_TYPE,+ alertId: "alert-1",+ alertName: "prod-expiry",+ channelType: "email",+ success: true+ }+ })+ ).toMatchObject({+ type: "test-certificate-manager-alert-channel",+ metadata: { alertId: "alert-1", alertName: "prod-expiry", channelType: "email", success: true }+ });+ });++ test("assertPermission requires a project", async () => {+ const { provider } = buildProvider();+ await expect(+ provider.assertPermission({ action: AlertPermissionAction.Read, orgId: "org-1", actor })+ ).rejects.toThrow("Certificate alerts must be created in Certificate Manager");+ });++ test("an alert with no application uses the project-level alerts permission", async () => {+ const { provider, permissionService } = buildProvider();+ await expect(+ provider.assertPermission({ action: AlertPermissionAction.Read, orgId: "org-1", projectId: "proj-1", actor })+ ).resolves.toBeUndefined();+ await expect(+ provider.assertPermission({ action: AlertPermissionAction.Create, orgId: "org-1", projectId: "proj-1", actor })+ ).rejects.toThrow();+ expect(permissionService.getProjectPermission).toHaveBeenCalled();+ });++ test("creating or editing an alert with no application requires reading every certificate", async () => {+ const create = { action: AlertPermissionAction.Create, orgId: "org-1", projectId: "proj-1", actor };+ const alertRules = [+ { action: "create", subject: "pki-alerts" },+ { action: "edit", subject: "pki-alerts" }+ ];++ await expect(+ buildProvider({+ abilityRules: [...alertRules, { action: "read", subject: "certificates" }]+ }).provider.assertPermission(create)+ ).resolves.toBeUndefined();+ await expect(buildProvider({ abilityRules: alertRules }).provider.assertPermission(create)).rejects.toThrow(+ "require permission to read all certificates"+ );+ await expect(+ buildProvider({+ abilityRules: [+ ...alertRules,+ { action: "read", subject: "certificates", conditions: { commonName: { $glob: "*.internal" } } }+ ]+ }).provider.assertPermission({ ...create, action: AlertPermissionAction.Edit })+ ).rejects.toThrow("require permission to read all certificates");+ await expect(+ buildProvider({+ abilityRules: [+ ...alertRules,+ { action: "read", subject: "certificates" },+ { action: "read", subject: "certificates", inverted: true, conditions: { commonName: { $glob: "*.prod" } } }+ ]+ }).provider.assertPermission(create)+ ).rejects.toThrow("require permission to read all certificates");+ });++ test("resolveProjectId falls back to the org's Certificate Manager project without an application", async () => {+ const { provider } = buildProvider();+ await expect(provider.resolveProjectId?.({ orgId: "org-1" })).resolves.toBe("proj-1");+ await expect(provider.resolveProjectId?.({ orgId: "org-2" })).rejects.toThrow(+ "Certificate Manager isn't set up for this organization"+ );+ });++ 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("telemetry reports Certificate Manager scope with the shared alertType values", () => {+ const { provider } = buildProvider();+ expect(+ provider.getTelemetryEvent?.({+ action: AlertTelemetryAction.Create,+ orgId: "org-1",+ projectId: "proj-1",+ resourceId: null,+ eventType: ISSUANCE_EVENT+ })+ ).toEqual({+ event: PostHogEventTypes.PkiAlertCreated,+ properties: {+ orgId: "org-1",+ projectId: "proj-1",+ alertScope: PkiAlertScope.CertificateManager,+ alertType: "issuance"+ }+ });+ expect(+ provider.getTelemetryEvent?.({+ action: AlertTelemetryAction.Create,+ orgId: "org-1",+ projectId: "proj-1",+ resourceId: null,+ eventType: EXPIRY_EVENT+ })?.properties+ ).toMatchObject({ alertType: "expiration" });+ });+});diff --git a/backend/src/services/alert/providers/cert-manager-alert-provider.ts b/backend/src/services/alert/providers/cert-manager-alert-provider.tsnew file mode 100644index 0000000000..1fd9958373--- /dev/null+++ b/backend/src/services/alert/providers/cert-manager-alert-provider.ts@@ -0,0 +1,330 @@+import { MongoAbility } from "@casl/ability";+import { z } from "zod";++import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import {+ ProjectPermissionCertificateActions,+ ProjectPermissionSet,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";+import { getConfig } from "@app/lib/config/env";+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { TCertManagerProjectResolverFactory } from "@app/services/cert-manager-instance/cert-manager-project-resolver";+import {+ CERT_MANAGER_APPLICATION_RESOURCE_TYPE,+ CERT_MANAGER_RESOURCE_TYPE,+ CertificateAlertEvent,+ CertificateManagerAlertEvent+} from "@app/services/certificate/certificate-alert-events";+import { PkiAlertScope } from "@app/services/telemetry/telemetry-types";++import { durationToDays } from "../alert-format-fns";+import {+ ALERT_SCAN_LEAD_INTERVAL,+ AlertAuditAction,+ AlertPermissionAction,+ AlertTriggerType,+ IEventAlertProvider,+ IScheduledAlertProvider,+ TAlertAuditInput,+ TAlertContext,+ TAlertFilters,+ TAlertPermissionInput,+ TAlertTelemetryInput,+ TFindEventTargetsInput,+ TFindScheduledTargetsInput+} from "../alert-types";+import {+ assertCertManagerAlertChannelTypesAllowed,+ assertNoAlertResource,+ buildCertificateAlertPayload,+ buildCertificateManagerAlertAuditEvent,+ buildPkiAlertTelemetryEvent,+ CERTIFICATE_ALERT_KIND_TELEMETRY_TYPES,+ CertificateAlertKind,+ expiryDedupWindowHours,+ ExpiryFieldsSchema,+ getCertManagerAlertPermission,+ resolveCertManagerProjectId+} from "./cert-manager-alert-fns";+import {+ TApplicationAlertCertificate,+ TCertManagerApplicationAlertDALFactory+} from "./cert-manager-application-alert-dal";++const MAX_CERTIFICATE_ALERT_FILTER_IDS = 100;++const ALERT_KIND_BY_EVENT: Record<CertificateManagerAlertEvent, CertificateAlertKind> = {+ [CertificateManagerAlertEvent.Expiry]: CertificateAlertKind.Expiry,+ [CertificateManagerAlertEvent.Issuance]: CertificateAlertKind.Issuance,+ [CertificateManagerAlertEvent.Renewal]: CertificateAlertKind.Renewal,+ [CertificateManagerAlertEvent.Revocation]: CertificateAlertKind.Revocation+};++const RELAYED_EVENTS: [CertificateManagerAlertEvent, CertificateAlertEvent][] = [+ [CertificateManagerAlertEvent.Issuance, CertificateAlertEvent.Issuance],+ [CertificateManagerAlertEvent.Renewal, CertificateAlertEvent.Renewal],+ [CertificateManagerAlertEvent.Revocation, CertificateAlertEvent.Revocation]+];++const filterIdsSchema = (field: string, noun: string) =>+ z+ .array(z.string().uuid())+ .min(1, `${field} must list at least one ${noun}. Omit it to cover every ${noun}.`)+ .max(MAX_CERTIFICATE_ALERT_FILTER_IDS)+ .superRefine((ids, ctx) => {+ const seen = new Set<string>();+ const duplicates = new Set<string>();+ ids.forEach((id) => {+ const key = id.toLowerCase();+ if (seen.has(key)) duplicates.add(id);+ seen.add(key);+ });+ if (duplicates.size) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `${field} lists the same ID more than once: ${[...duplicates].map((id) => `'${id}'`).join(", ")}`+ });+ }+ })+ .optional();++const CertificateFilterSchema = z.object({+ applicationIds: filterIdsSchema("applicationIds", "application"),+ profileIds: filterIdsSchema("profileIds", "profile")+});++const ExpirationConditionSchema = ExpiryFieldsSchema.merge(CertificateFilterSchema).strict();++const EventConditionSchema = CertificateFilterSchema.strict().nullish();++const formatIds = (ids: string[]) => ids.map((id) => `'${id}'`).join(", ");++const toIdSet = (ids: string[] = []) => new Set(ids.map((id) => id.toLowerCase()));++const parseFilters = (condition: unknown) => {+ const filters = CertificateFilterSchema.safeParse(condition ?? {});+ return filters.success ? filters.data : {};+};++const isUnconditionalGrant = (rules: ReturnType<MongoAbility<ProjectPermissionSet>["rulesFor"]>) =>+ rules.some((rule) => !rule.inverted && !rule.conditions) && !rules.some((rule) => rule.inverted);++const assertNoResource = (resourceId?: string | null) =>+ assertNoAlertResource(+ resourceId,+ "Certificate Manager alerts cover every application and can't be bound to one. Remove resourceId, or narrow the alert with applicationIds."+ );++const getWebhookSource = ({ alertId }: { alertId: string }) => `/alerts/${alertId}`;++export type TCertManagerAlertProviderDep = {+ certManagerApplicationAlertDAL: TCertManagerApplicationAlertDALFactory;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ certManagerProjectResolver: Pick<TCertManagerProjectResolverFactory, "getActiveProjectId">;+};++export const certManagerAlertProviderFactory = ({+ certManagerApplicationAlertDAL,+ permissionService,+ licenseService,+ certManagerProjectResolver+}: TCertManagerAlertProviderDep): IScheduledAlertProvider<TApplicationAlertCertificate> &+ IEventAlertProvider<TApplicationAlertCertificate> => {+ const buildViewUrl = async (alert: TAlertContext): Promise<string> =>+ `${getConfig().SITE_URL}/organizations/${alert.orgId}/projects/cert-manager/${alert.projectId}/inventory`;++ const findScheduledTargets = async (input: TFindScheduledTargetsInput): Promise<TApplicationAlertCertificate[]> => {+ if (!input.projectId || input.resourceId || !input.alreadyAlerted?.channelIds.length) return [];+ const { alertBefore, applicationIds, profileIds } = ExpirationConditionSchema.parse(input.condition);++ return certManagerApplicationAlertDAL.findExpiringCertificates({+ projectId: input.projectId,+ applicationIds,+ profileIds,+ alertBeforeInterval: `${durationToDays(alertBefore)} days`,+ leadInterval: ALERT_SCAN_LEAD_INTERVAL,+ asOf: input.asOf,+ alreadyAlerted: input.alreadyAlerted+ });+ };++ const findEventTargets = async (input: TFindEventTargetsInput): Promise<TApplicationAlertCertificate[]> => {+ if (!input.projectId || input.resourceId) return [];+ const condition = EventConditionSchema.parse(input.condition);++ return certManagerApplicationAlertDAL.findCertificatesByIds({+ projectId: input.projectId,+ applicationIds: condition?.applicationIds,+ profileIds: condition?.profileIds,+ certificateIds: input.targetIds+ });+ };++ const buildPayload = (alert: TAlertContext, targets: TApplicationAlertCertificate[], viewUrl: string) =>+ buildCertificateAlertPayload({+ alert,+ targets,+ viewUrl,+ kind: ALERT_KIND_BY_EVENT[alert.eventType as CertificateManagerAlertEvent],+ webhookSource: getWebhookSource({ alertId: alert.id }),+ resourceOwnerKind: "Certificate Manager",+ applicationName: null+ });++ const getAuditEvent = (input: TAlertAuditInput) => {+ if (input.action === AlertAuditAction.TestChannel) {+ return buildCertificateManagerAlertAuditEvent(input, { applications: [], profiles: [] });+ }+ const { applicationIds = [], profileIds = [] } = parseFilters(input.alert.condition);+ const nameById = new Map(+ Object.values(input.alert.filters ?? {})+ .flat()+ .map((resource) => [resource.id, resource.name])+ );+ const withNames = (ids: string[]) => ids.map((id) => ({ id, name: nameById.get(id) ?? null }));+ return buildCertificateManagerAlertAuditEvent(input, {+ applications: withNames(applicationIds),+ profiles: withNames(profileIds)+ });+ };++ const getTelemetryEvent = ({ action, orgId, projectId, eventType }: TAlertTelemetryInput) => {+ if (!projectId) return undefined;+ return buildPkiAlertTelemetryEvent(+ action,+ { orgId, projectId, alertScope: PkiAlertScope.CertificateManager },+ CERTIFICATE_ALERT_KIND_TELEMETRY_TYPES[ALERT_KIND_BY_EVENT[eventType as CertificateManagerAlertEvent]]+ );+ };++ const assertPermission = async ({ action, projectId, resourceId, actor }: TAlertPermissionInput): Promise<void> => {+ if (!projectId) {+ throw new BadRequestError({ message: "Certificate alerts must be created in Certificate Manager" });+ }+ assertNoResource(resourceId);++ const { permission } = await getCertManagerAlertPermission(permissionService, { action, projectId, actor });++ const definesDelivery = action === AlertPermissionAction.Create || action === AlertPermissionAction.Edit;+ if (+ definesDelivery &&+ !isUnconditionalGrant(+ permission.rulesFor(ProjectPermissionCertificateActions.Read, ProjectPermissionSub.Certificates)+ )+ ) {+ throw new ForbiddenRequestError({+ message:+ "Certificate Manager alerts send certificate details from every application, so they require permission to read all certificates. Create the alert on an application instead."+ });+ }+ };++ const assertConditionInScope = async (input: {+ projectId?: string | null;+ condition: unknown;+ previousCondition?: unknown;+ }): Promise<void> => {+ if (!input.projectId) return;+ const { applicationIds = [], profileIds = [] } = CertificateFilterSchema.parse(input.condition ?? {});++ const previous = parseFilters(input.previousCondition);+ const savedApplicationIds = toIdSet(previous.applicationIds);+ const savedProfileIds = toIdSet(previous.profileIds);+ const addedApplicationIds = applicationIds.filter((id) => !savedApplicationIds.has(id.toLowerCase()));+ const addedProfileIds = profileIds.filter((id) => !savedProfileIds.has(id.toLowerCase()));++ const [foundApplicationIds, foundProfileIds]: string[][] = await Promise.all([+ addedApplicationIds.length+ ? certManagerApplicationAlertDAL.findProjectApplicationIds(input.projectId, addedApplicationIds)+ : [],+ addedProfileIds.length+ ? certManagerApplicationAlertDAL.findProjectProfileIds(input.projectId, addedProfileIds)+ : []+ ]);++ const foundApplicationIdSet = toIdSet(foundApplicationIds);+ const missingApplicationIds = addedApplicationIds.filter((id) => !foundApplicationIdSet.has(id.toLowerCase()));+ if (missingApplicationIds.length) {+ throw new NotFoundError({+ message: `${missingApplicationIds.length === 1 ? "Application" : "Applications"} not found in Certificate Manager: ${formatIds(missingApplicationIds)}`+ });+ }+ const foundProfileIdSet = toIdSet(foundProfileIds);+ const missingProfileIds = addedProfileIds.filter((id) => !foundProfileIdSet.has(id.toLowerCase()));+ if (missingProfileIds.length) {+ throw new NotFoundError({+ message: `${missingProfileIds.length === 1 ? "Certificate profile" : "Certificate profiles"} not found in Certificate Manager: ${formatIds(missingProfileIds)}`+ });+ }+ };++ const getFilters = async ({+ orgId,+ projectId,+ alerts+ }: {+ orgId: string;+ projectId: string | null;+ alerts: { id: string; condition: unknown }[];+ }): Promise<Map<string, TAlertFilters>> => {+ const filtersByAlert = alerts.map((alert) => ({ id: alert.id, ...parseFilters(alert.condition) }));+ const applicationIds = [...new Set(filtersByAlert.flatMap((filters) => filters.applicationIds ?? []))];+ const profileIds = [...new Set(filtersByAlert.flatMap((filters) => filters.profileIds ?? []))];++ const [applications, profiles] = await Promise.all([+ certManagerApplicationAlertDAL.findApplicationNamesByIds(applicationIds, orgId),+ projectId ? certManagerApplicationAlertDAL.findProfileNamesByIds(projectId, profileIds) : []+ ]);+ const nameById = new Map([...applications, ...profiles].map((entry) => [entry.id.toLowerCase(), entry.name]));++ const withNames = (ids: string[] = []) => ids.map((id) => ({ id, name: nameById.get(id.toLowerCase()) ?? null }));++ return new Map(+ filtersByAlert.map((filters) => [+ filters.id,+ { applications: withNames(filters.applicationIds), profiles: withNames(filters.profileIds) }+ ])+ );+ };++ return {+ resourceType: CERT_MANAGER_RESOURCE_TYPE,+ supportsScopeWideAlerts: true,+ events: [+ {+ key: CertificateManagerAlertEvent.Expiry,+ triggerType: AlertTriggerType.Scheduled,+ conditionSchema: ExpirationConditionSchema+ },+ ...RELAYED_EVENTS.map(([key, sourceEventKey]) => ({+ key,+ triggerType: AlertTriggerType.Event,+ conditionSchema: EventConditionSchema,+ relayedFrom: { resourceType: CERT_MANAGER_APPLICATION_RESOURCE_TYPE, eventKey: sourceEventKey }+ }))+ ],+ findScheduledTargets,+ findEventTargets,+ buildViewUrl,+ buildPayload,+ getTelemetryEvent,+ targetId: (certificate) => certificate.id,+ dedupWindowHours: expiryDedupWindowHours,+ assertPermission,+ assertResourceInScope: async ({ resourceId }) => assertNoResource(resourceId),+ assertConditionInScope,+ assertChannelTypesAllowed: (input) => assertCertManagerAlertChannelTypesAllowed(licenseService, input),+ recipientPolicy: { atOrgScope: true, allowEmailAddresses: true },+ includeLastRun: true,+ getAuditEvent,+ getWebhookSource,+ getFilters,+ resolveProjectId: async ({ orgId, resourceId }) => {+ assertNoResource(resourceId);+ return resolveCertManagerProjectId(certManagerProjectResolver, orgId);+ }+ };+};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.tsindex c05e7afc50..653864ed68 100644--- 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.ts@@ -20,7 +20,6 @@ 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 APPLICATION_ID = "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90";-const OTHER_APPLICATION_ID = "6c8e4a1f-9b2d-4f3c-8e7a-2b3c4d5e6f70";const PROFILE_ID = "7d9f5b2a-0c3e-4a4d-9f8b-3c4d5e6f7081";const futureDate = (days: number) => new Date(Date.now() + days * 24 * 60 * 60 * 1000);@@ -60,9 +59,7 @@ const buildProvider = (opts?: {onFindExpiring?: (args: Record<string, unknown>) => void;onFindByIds?: (args: Record<string, unknown>) => void;onFindNames?: (ids: string[], orgId: string) => void;- onFindApplicationIds?: (ids: string[]) => void;abilityRules?: { action: string; subject: string; inverted?: boolean; conditions?: unknown }[];- projectRoles?: string[];pkiEnterpriseAlerting?: boolean;}) => {const application = opts?.application ?? {@@ -86,23 +83,12 @@ const buildProvider = (opts?: {findCertificatesByIds: async (args: Record<string, unknown>) => {opts?.onFindByIds?.(args);return opts?.certificates ?? [];- },- findProjectApplicationIds: async (_projectId: string, ids: string[]) => {- opts?.onFindApplicationIds?.(ids);- return ids.some((id) => id.toLowerCase() === application.id) ? [application.id] : [];- },- findProjectProfileIds: async (_projectId: string, ids: string[]) => ids.filter((id) => id === PROFILE_ID),- findProfileNamesByIds: async (_projectId: string, ids: string[]) =>- ids.filter((id) => id === PROFILE_ID).map((id) => ({ id, name: "tls-server" }))+ }};const ability = () =>createMongoAbility((opts?.abilityRules ?? [{ action: "read", subject: "pki-alerts" }]) as never);const permissionService = {- getResourcePermission: vi.fn(async () => ({ permission: ability() })),- getProjectPermission: vi.fn(async () => ({- permission: ability(),- hasRole: (role: string) => (opts?.projectRoles ?? []).includes(role)- }))+ getResourcePermission: vi.fn(async () => ({ permission: ability() }))};const licenseService = {getPlan: async () => ({ pkiEnterpriseAlerting: opts?.pkiEnterpriseAlerting ?? false })@@ -110,10 +96,7 @@ const buildProvider = (opts?: {const provider = certManagerApplicationAlertProviderFactory({certManagerApplicationAlertDAL: dal,permissionService,- licenseService,- certManagerProjectResolver: {- getActiveProjectId: async (orgId: string) => (orgId === "org-1" ? "proj-1" : null)- }+ licenseService} as unknown as TCertManagerApplicationAlertProviderDep);return { provider, permissionService };};@@ -135,68 +118,6 @@ describe("cert manager application alert provider", () => {expect(schema.safeParse({ alertBefore: "30d", filters: [] }).success).toBe(false);});- test("issuance, renewal and revocation are event-triggered and take only optional filters", () => {- const { provider } = buildProvider();- expect(provider.supportsScopeWideAlerts).toBe(true);- const eventTriggered = provider.events.filter((event) => event.triggerType === "event");- expect(eventTriggered.map((event) => event.key)).toEqual([- ISSUANCE_EVENT,- "cert-manager.application.certificate.renewal",- REVOCATION_EVENT- ]);- eventTriggered.forEach((event) => {- expect(event.conditionSchema.safeParse(null).success).toBe(true);- expect(event.conditionSchema.safeParse({ profileIds: [PROFILE_ID] }).success).toBe(true);- expect(event.conditionSchema.safeParse({ profileIds: [] }).success).toBe(false);- expect(event.conditionSchema.safeParse({ alertBefore: "30d" }).success).toBe(false);- });- });-- test("filters must be non-empty UUID lists and are stored as sent", () => {- const schema = expiryConditionSchema(buildProvider().provider);- expect(- schema.safeParse({ alertBefore: "30d", applicationIds: [APPLICATION_ID], profileIds: [PROFILE_ID] }).success- ).toBe(true);- expect(schema.safeParse({ alertBefore: "30d", applicationIds: ["not-a-uuid"] }).success).toBe(false);- expect(schema.safeParse({ alertBefore: "30d", applicationIds: [] }).success).toBe(false);- const upper = schema.safeParse({ alertBefore: "30d", applicationIds: [APPLICATION_ID.toUpperCase()] });- expect(upper.success && (upper.data as { applicationIds: string[] }).applicationIds).toEqual([- APPLICATION_ID.toUpperCase()- ]);- });-- test("filters reject an ID listed twice, in any case, instead of storing the duplicate", () => {- const schema = expiryConditionSchema(buildProvider().provider);- const duplicated = schema.safeParse({- alertBefore: "30d",- applicationIds: [APPLICATION_ID, APPLICATION_ID.toUpperCase()]- });- expect(duplicated.success).toBe(false);- expect(duplicated.error?.issues[0].message).toBe(- `applicationIds lists the same ID more than once: '${APPLICATION_ID.toUpperCase()}'`- );- expect(schema.safeParse({ alertBefore: "30d", profileIds: [PROFILE_ID, PROFILE_ID] }).success).toBe(false);- });-- test("filter IDs match case-insensitively when checked and named", async () => {- const { provider } = buildProvider();- await expect(- provider.assertConditionInScope?.({- projectId: "proj-1",- condition: { applicationIds: [APPLICATION_ID.toUpperCase()] }- })- ).resolves.toBeUndefined();- const names = await provider.getFilters?.({- orgId: "org-1",- projectId: "proj-1",- alerts: [{ id: "alert-1", condition: { applicationIds: [APPLICATION_ID.toUpperCase()] } }]- });- expect(names?.get("alert-1")).toEqual({- applications: [{ id: APPLICATION_ID.toUpperCase(), name: "payments-api" }],- profiles: []- });- });-test("findScheduledTargets scans nothing when the alert has no channel to deliver to", async () => {let scanned = false;const { provider } = buildProvider({@@ -242,48 +163,6 @@ describe("cert manager application alert provider", () => {});});- test("findScheduledTargets and findEventTargets scan the whole project for an alert with no application", async () => {- let scheduledArgs: Record<string, unknown> | undefined;- let eventArgs: Record<string, unknown> | undefined;- const { provider } = buildProvider({- onFindExpiring: (value) => {- scheduledArgs = value;- },- onFindByIds: (value) => {- eventArgs = value;- }- });- await provider.findScheduledTargets({- orgId: "org-1",- projectId: "proj-1",- resourceId: null,- eventType: EXPIRY_EVENT,- condition: { alertBefore: "2w", profileIds: [PROFILE_ID] },- asOf: new Date(),- alreadyAlerted: { alertId: "alert-1", channelIds: ["channel-1"], since: new Date() }- });- await provider.findEventTargets({- orgId: "org-1",- projectId: "proj-1",- resourceId: null,- eventType: ISSUANCE_EVENT,- condition: { applicationIds: [APPLICATION_ID] },- targetIds: ["cert-1"]- } as never);-- expect(scheduledArgs).toMatchObject({- projectId: "proj-1",- profileIds: [PROFILE_ID],- alertBeforeInterval: "14 days"- });- expect(scheduledArgs?.applicationId).toBeNull();- expect(eventArgs).toMatchObject({- projectId: "proj-1",- applicationIds: [APPLICATION_ID],- certificateIds: ["cert-1"]- });- });-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);@@ -434,138 +313,6 @@ describe("cert manager application alert provider", () => {await expect(provider.buildViewUrl(alertContext({ resourceId: "missing" }))).resolves.toBe("https://app.infisical.com/organizations/org-1/projects/cert-manager/proj-1/applications");- await expect(provider.buildViewUrl(alertContext({ resourceId: null }))).resolves.toBe(- "https://app.infisical.com/organizations/org-1/projects/cert-manager/proj-1/inventory"- );- });-- test("buildPayload for an alert with no application names Certificate Manager and lists each application", () => {- const { provider } = buildProvider();- const payload = provider.buildPayload(- alertContext({ resourceId: null }),- [sampleCertificate({ notAfter: futureDate(20) })],- "https://app.infisical.com/view"- );-- expect(payload.resourceOwnerKind).toBe("Certificate Manager");- expect(payload.alert.resourceType).toBe("cert-manager");- expect(payload.alert).not.toHaveProperty("resourceId");- expect(payload.webhookSource).toBe("/alerts/alert-1");- expect(payload.eventKey).toBe("cert-manager.certificate.expiry");- expect(payload.webhookType).toBe("com.infisical.cert-manager.certificate.expiry");- expect(payload.summary).toBe("1 certificate expiring within 30 days");- expect(payload.items[0].fields).toContainEqual({ label: "Application", value: "payments-api" });- });-- test("assertConditionInScope rejects filters on an application alert and unknown IDs", async () => {- const { provider } = buildProvider();- await expect(- provider.assertConditionInScope?.({- projectId: "proj-1",- condition: { applicationIds: [APPLICATION_ID], profileIds: [PROFILE_ID] }- })- ).resolves.toBeUndefined();- await expect(- provider.assertConditionInScope?.({- projectId: "proj-1",- resourceId: APPLICATION_ID,- condition: { alertBefore: "30d", profileIds: [PROFILE_ID] }- })- ).rejects.toThrow("Application alerts already cover a single application");- await expect(- provider.assertConditionInScope?.({ projectId: "proj-1", condition: { applicationIds: [OTHER_APPLICATION_ID] } })- ).rejects.toThrow(`Application not found in Certificate Manager: '${OTHER_APPLICATION_ID}'`);- });-- test("assertConditionInScope only checks IDs the update adds, so a deleted one can stay", async () => {- const lookups: string[][] = [];- const { provider } = buildProvider({ onFindApplicationIds: (ids) => lookups.push(ids) });- await expect(- provider.assertConditionInScope?.({- projectId: "proj-1",- condition: { applicationIds: [OTHER_APPLICATION_ID, APPLICATION_ID] },- previousCondition: { applicationIds: [OTHER_APPLICATION_ID] }- })- ).resolves.toBeUndefined();- expect(lookups).toEqual([[APPLICATION_ID]]);- });-- test("lists each alert's filter IDs with their names, with a null name for IDs that no longer exist", async () => {- const { provider } = buildProvider();- const names = await provider.getFilters?.({- orgId: "org-1",- projectId: "proj-1",- alerts: [- {- id: "alert-1",- condition: { applicationIds: [APPLICATION_ID, OTHER_APPLICATION_ID], profileIds: [PROFILE_ID] }- },- { id: "alert-2", condition: null }- ]- });-- expect(names?.get("alert-1")).toEqual({- applications: [- { id: APPLICATION_ID, name: "payments-api" },- { id: OTHER_APPLICATION_ID, name: null }- ],- profiles: [{ id: PROFILE_ID, name: "tls-server" }]- });- expect(names?.get("alert-2")).toEqual({ applications: [], profiles: [] });- });-- test("an alert with no application logs Certificate Manager audit events naming its filters", () => {- const { provider } = buildProvider();- const alert = {- id: "alert-1",- name: "prod-expiry",- resourceType: RESOURCE_TYPE,- resourceId: null,- eventType: EXPIRY_EVENT,- condition: {- alertBefore: "30d",- applicationIds: [APPLICATION_ID, OTHER_APPLICATION_ID],- profileIds: [PROFILE_ID]- },- filters: {- applications: [{ id: APPLICATION_ID, name: "payments-api" }],- profiles: [{ id: PROFILE_ID, name: "tls-server" }]- }- };- const metadata = {- alertId: "alert-1",- name: "prod-expiry",- eventType: EXPIRY_EVENT,- applications: [- { id: APPLICATION_ID, name: "payments-api" },- { id: OTHER_APPLICATION_ID, name: null }- ],- profiles: [{ id: PROFILE_ID, name: "tls-server" }]- };-- expect(provider.getAuditEvent?.({ action: AlertAuditAction.Create, alert })).toEqual({- type: "create-certificate-manager-alert",- metadata- });- expect(provider.getAuditEvent?.({ action: AlertAuditAction.Delete, alert })).toEqual({- type: "delete-certificate-manager-alert",- metadata- });- expect(- provider.getAuditEvent?.({- action: AlertAuditAction.TestChannel,- test: {- resourceType: RESOURCE_TYPE,- alertId: "alert-1",- alertName: "prod-expiry",- channelType: "email",- success: true- }- })- ).toMatchObject({- type: "test-certificate-manager-alert-channel",- metadata: { alertId: "alert-1", alertName: "prod-expiry", channelType: "email", success: true }- });});test("assertPermission checks the application's resource permission when the alert is bound to one", async () => {@@ -598,52 +345,6 @@ describe("cert manager application alert provider", () => {).rejects.toThrow("Certificate alerts must be created in Certificate Manager");});- test("an alert with no application uses the project-level alerts permission", async () => {- const { provider, permissionService } = buildProvider();- await expect(- provider.assertPermission({ action: AlertPermissionAction.Read, orgId: "org-1", projectId: "proj-1", actor })- ).resolves.toBeUndefined();- await expect(- provider.assertPermission({ action: AlertPermissionAction.Create, orgId: "org-1", projectId: "proj-1", actor })- ).rejects.toThrow();- expect(permissionService.getProjectPermission).toHaveBeenCalled();- expect(permissionService.getResourcePermission).not.toHaveBeenCalled();- });-- test("creating or editing an alert with no application requires reading every certificate", async () => {- const create = { action: AlertPermissionAction.Create, orgId: "org-1", projectId: "proj-1", actor };- const alertRules = [- { action: "create", subject: "pki-alerts" },- { action: "edit", subject: "pki-alerts" }- ];-- await expect(- buildProvider({- abilityRules: [...alertRules, { action: "read", subject: "certificates" }]- }).provider.assertPermission(create)- ).resolves.toBeUndefined();- await expect(buildProvider({ abilityRules: alertRules }).provider.assertPermission(create)).rejects.toThrow(- "require permission to read all certificates"- );- await expect(- buildProvider({- abilityRules: [- ...alertRules,- { action: "read", subject: "certificates", conditions: { commonName: { $glob: "*.internal" } } }- ]- }).provider.assertPermission({ ...create, action: AlertPermissionAction.Edit })- ).rejects.toThrow("require permission to read all certificates");- await expect(- buildProvider({- abilityRules: [- ...alertRules,- { action: "read", subject: "certificates" },- { action: "read", subject: "certificates", inverted: true, conditions: { commonName: { $glob: "*.prod" } } }- ]- }).provider.assertPermission(create)- ).rejects.toThrow("require permission to read all certificates");- });-test("assertResourceInScope rejects an application from another project or org", async () => {const { provider } = buildProvider();await expect(@@ -680,14 +381,6 @@ describe("cert manager application alert provider", () => {).rejects.toThrow("Application with ID '7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90' not found");});- test("resolveProjectId falls back to the org's Certificate Manager project without an application", async () => {- const { provider } = buildProvider();- await expect(provider.resolveProjectId?.({ orgId: "org-1" })).resolves.toBe("proj-1");- await expect(provider.resolveProjectId?.({ orgId: "org-2" })).rejects.toThrow(- "Certificate Manager isn't set up for this organization"- );- });-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";@@ -774,22 +467,27 @@ describe("cert manager application alert provider", () => {eventType: ISSUANCE_EVENT})?.event).toBe(PostHogEventTypes.PkiAlertDeleted);- expect(- provider.getTelemetryEvent?.({- action: AlertTelemetryAction.Create,+ });++ test("only takes alerts bound to an application, with no filters", async () => {+ const { provider } = buildProvider({ abilityRules: [{ action: "create", subject: "pki-alerts" }] });+ expect(provider.supportsScopeWideAlerts).toBeUndefined();+ await expect(+ provider.assertPermission({+ action: AlertPermissionAction.Create,orgId: "org-1",projectId: "proj-1",resourceId: null,- eventType: ISSUANCE_EVENT+ actor})- ).toEqual({- event: PostHogEventTypes.PkiAlertCreated,- properties: {- orgId: "org-1",- projectId: "proj-1",- alertScope: PkiAlertScope.CertificateManager,- alertType: "issuance"- }- });+ ).rejects.toThrow("Application alerts require an application ID");+ await expect(provider.resolveProjectId?.({ orgId: "org-1", resourceId: null })).rejects.toThrow(+ "Application alerts require an application ID"+ );+ const eventSchema = provider.events.find((event) => event.key === ISSUANCE_EVENT)!.conditionSchema;+ expect(eventSchema.safeParse({ applicationIds: [APPLICATION_ID] }).success).toBe(false);+ expect(expiryConditionSchema(provider).safeParse({ alertBefore: "30d", profileIds: [PROFILE_ID] }).success).toBe(+ false+ );});});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.tsindex d53c8c558b..64943111dc 100644--- a/backend/src/services/alert/providers/cert-manager-application-alert-provider.ts+++ b/backend/src/services/alert/providers/cert-manager-application-alert-provider.ts@@ -1,105 +1,58 @@-import { ForbiddenError, MongoAbility } from "@casl/ability";+import { ForbiddenError } from "@casl/ability";import { z } from "zod";-import { ActionProjectType, ResourceType } from "@app/db/schemas";+import { ResourceType } from "@app/db/schemas";import { Event as TAuditEvent, EventType } from "@app/ee/services/audit-log/audit-log-types";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";-import {- ProjectPermissionCertificateActions,- ProjectPermissionSet,- 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, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";-import { TCertManagerProjectResolverFactory } from "@app/services/cert-manager-instance/cert-manager-project-resolver";+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 { PkiAlertScope } from "@app/services/telemetry/telemetry-types";-import { TAlertPayload, TAlertSeverity } from "../alert-channel-types";-import { durationToDays, expirySeverity, formatUtcDate, humanizeDays } from "../alert-format-fns";+import { durationToDays } from "../alert-format-fns";import {ALERT_SCAN_LEAD_INTERVAL,AlertAuditAction,- AlertPermissionAction,AlertTriggerType,- DEFAULT_DEDUP_WINDOW_HOURS,IEventAlertProvider,IScheduledAlertProvider,TAlertAuditInput,TAlertContext,- TAlertFilters,TAlertPermissionInput,- TAlertTelemetryEvent,TAlertTelemetryInput,TFindEventTargetsInput,TFindScheduledTargetsInput} from "../alert-types";import {assertCertManagerAlertChannelTypesAllowed,- buildCertificateManagerAlertAuditEvent,+ buildCertificateAlertPayload,buildPkiAlertTelemetryEvent,CERT_MANAGER_ALERT_PERMISSION_ACTIONS,- certificateDisplayName,- expirationDedupWindowHours,- ExpiryFieldsSchema,- resolveCertManagerProjectId,- splitAltNames+ CERTIFICATE_ALERT_KIND_TELEMETRY_TYPES,+ CertificateAlertKind,+ expiryDedupWindowHours,+ ExpiryFieldsSchema} from "./cert-manager-alert-fns";import {TApplicationAlertCertificate,TCertManagerApplicationAlertDALFactory} from "./cert-manager-application-alert-dal";-const MAX_CERTIFICATE_ALERT_FILTER_IDS = 100;--const CERT_MANAGER_DELIVERY_RESOURCE_TYPE = "cert-manager";--const toCertificateManagerEventKey = (eventType: CertificateAlertEvent) =>- eventType.replace(`${CERT_MANAGER_APPLICATION_RESOURCE_TYPE}.`, `${CERT_MANAGER_DELIVERY_RESOURCE_TYPE}.`);--const TELEMETRY_ALERT_TYPE_BY_EVENT: Record<CertificateAlertEvent, string> = {- [CertificateAlertEvent.Expiry]: "expiration",- [CertificateAlertEvent.Issuance]: "issuance",- [CertificateAlertEvent.Renewal]: "renewal",- [CertificateAlertEvent.Revocation]: "revocation"+const ALERT_KIND_BY_EVENT: Record<CertificateAlertEvent, CertificateAlertKind> = {+ [CertificateAlertEvent.Expiry]: CertificateAlertKind.Expiry,+ [CertificateAlertEvent.Issuance]: CertificateAlertKind.Issuance,+ [CertificateAlertEvent.Renewal]: CertificateAlertKind.Renewal,+ [CertificateAlertEvent.Revocation]: CertificateAlertKind.Revocation};-const filterIdsSchema = (field: string, noun: string) =>- z- .array(z.string().uuid())- .min(1, `${field} must list at least one ${noun}. Omit it to cover every ${noun}.`)- .max(MAX_CERTIFICATE_ALERT_FILTER_IDS)- .superRefine((ids, ctx) => {- const seen = new Set<string>();- const duplicates = new Set<string>();- ids.forEach((id) => {- const key = id.toLowerCase();- if (seen.has(key)) duplicates.add(id);- seen.add(key);- });- if (duplicates.size) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: `${field} lists the same ID more than once: ${[...duplicates].map((id) => `'${id}'`).join(", ")}`- });- }- })- .optional();--const CertificateFilterSchema = z.object({- applicationIds: filterIdsSchema("applicationIds", "application"),- profileIds: filterIdsSchema("profileIds", "profile")-});--const ExpirationConditionSchema = ExpiryFieldsSchema.merge(CertificateFilterSchema).strict();+const ExpirationConditionSchema = ExpiryFieldsSchema.strict();-const EventConditionSchema = CertificateFilterSchema.strict().nullish();+const EventConditionSchema = z.object({}).strict().nullish();const assertValidApplicationId = (applicationId: string) => {if (!z.string().uuid().safeParse(applicationId).success) {@@ -107,94 +60,33 @@ const assertValidApplicationId = (applicationId: string) => {}};-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 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 inApplication = (applicationName?: string | null) =>- applicationName ? ` in application '${applicationName}'` : "";--const buildSummary = (- eventType: CertificateAlertEvent,- targets: TApplicationAlertCertificate[],- applicationName: string | null,- alertBefore?: string-): string => {- if (alertBefore) {- const certificates = `${targets.length} certificate${targets.length === 1 ? "" : "s"}`;- return `${certificates}${inApplication(applicationName)} expiring within ${humanizeDays(durationToDays(alertBefore))}`;- }- if (targets.length === 1) {- return `Certificate '${certificateDisplayName(targets[0])}' ${EVENT_VERBS[eventType]}${inApplication(targets[0].applicationName)}`;- }- return `${targets.length} certificates ${EVENT_VERBS[eventType]}${inApplication(applicationName)}`;-};--const buildItemSummary = (eventType: CertificateAlertEvent, certificate: TApplicationAlertCertificate): string => {- if (eventType === CertificateAlertEvent.Expiry) {- return `Certificate '${certificateDisplayName(certificate)}'${inApplication(certificate.applicationName)} expires on ${formatUtcDate(certificate.notAfter)}`;- }- return `Certificate '${certificateDisplayName(certificate)}' ${EVENT_VERBS[eventType]}${inApplication(certificate.applicationName)}`;-};--const formatIds = (ids: string[]) => ids.map((id) => `'${id}'`).join(", ");--const toIdSet = (ids: string[] = []) => new Set(ids.map((id) => id.toLowerCase()));--const parseFilters = (condition: unknown) => {- const filters = CertificateFilterSchema.safeParse(condition ?? {});- return filters.success ? filters.data : {};-};--const isUnconditionalGrant = (rules: ReturnType<MongoAbility<ProjectPermissionSet>["rulesFor"]>) =>- rules.some((rule) => !rule.inverted && !rule.conditions) && !rules.some((rule) => rule.inverted);-export type TCertManagerApplicationAlertProviderDep = {certManagerApplicationAlertDAL: TCertManagerApplicationAlertDALFactory;- permissionService: Pick<TPermissionServiceFactory, "getResourcePermission" | "getProjectPermission">;+ permissionService: Pick<TPermissionServiceFactory, "getResourcePermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;- certManagerProjectResolver: Pick<TCertManagerProjectResolverFactory, "getActiveProjectId">;};export const certManagerApplicationAlertProviderFactory = ({certManagerApplicationAlertDAL,permissionService,- licenseService,- certManagerProjectResolver+ 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}`;- if (!alert.resourceId) return `${base}/inventory`;- const application = await certManagerApplicationAlertDAL.findApplicationById(alert.resourceId);+ const application = alert.resourceId+ ? await certManagerApplicationAlertDAL.findApplicationById(alert.resourceId)+ : undefined;return application ? `${base}/applications/${encodeURIComponent(application.name)}` : `${base}/applications`;};const findScheduledTargets = async (input: TFindScheduledTargetsInput): Promise<TApplicationAlertCertificate[]> => {- if (!input.projectId || !input.alreadyAlerted?.channelIds.length) return [];- const { alertBefore, applicationIds, profileIds } = ExpirationConditionSchema.parse(input.condition);+ if (!input.projectId || !input.resourceId || !input.alreadyAlerted?.channelIds.length) return [];+ const { alertBefore } = ExpirationConditionSchema.parse(input.condition);return certManagerApplicationAlertDAL.findExpiringCertificates({projectId: input.projectId,applicationId: input.resourceId,- applicationIds,- profileIds,alertBeforeInterval: `${durationToDays(alertBefore)} days`,leadInterval: ALERT_SCAN_LEAD_INTERVAL,asOf: input.asOf,@@ -203,126 +95,26 @@ export const certManagerApplicationAlertProviderFactory = ({};const findEventTargets = async (input: TFindEventTargetsInput): Promise<TApplicationAlertCertificate[]> => {- if (!input.projectId) return [];- const condition = EventConditionSchema.parse(input.condition);+ if (!input.projectId || !input.resourceId) return [];+ EventConditionSchema.parse(input.condition);return certManagerApplicationAlertDAL.findCertificatesByIds({projectId: input.projectId,applicationId: input.resourceId,- applicationIds: condition?.applicationIds,- profileIds: condition?.profileIds,certificateIds: input.targetIds});};const getWebhookSource = ({ alertId, resourceId }: { alertId: string; resourceId?: string | null }) =>- resourceId ? `/applications/${resourceId}/alerts/${alertId}` : `/alerts/${alertId}`;-- const buildPayload = (- alert: TAlertContext,- targets: TApplicationAlertCertificate[],- viewUrl: string- ): TAlertPayload => {- const eventType = alert.eventType as CertificateAlertEvent;- const isApplicationAlert = Boolean(alert.resourceId);- const deliveryEventKey = isApplicationAlert ? eventType : toCertificateManagerEventKey(eventType);- const alertBefore =- eventType === CertificateAlertEvent.Expiry- ? (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: isApplicationAlert ? alert.resourceType : CERT_MANAGER_DELIVERY_RESOURCE_TYPE,- ...(alert.resourceId ? { resourceId: alert.resourceId } : {}),- ...(alertBefore ? { condition: alertBefore } : {}),- viewUrl- },- eventKey: deliveryEventKey,- eventLabel: EVENT_LABELS[eventType],- webhookType: `com.infisical.${deliveryEventKey}`,- webhookSource: getWebhookSource({ alertId: alert.id, resourceId: alert.resourceId }),- resourceKind: "Certificate",- resourceOwnerKind: isApplicationAlert ? "Application" : "Certificate Manager",- severity: eventSeverity(eventType, targets),- summary: buildSummary(- eventType,- targets,- isApplicationAlert ? (targets[0]?.applicationName ?? null) : null,- alertBefore- ),- items: targets.map((certificate) => {- const revocationReason =- eventType === CertificateAlertEvent.Revocation- ? getRevocationReasonLabel(certificate.revocationReason)- : undefined;- const altNames = splitAltNames(certificate.altNames);- return {- id: certificate.id,- title: certificateDisplayName(certificate),- summary: buildItemSummary(eventType, certificate),- severity: eventSeverity(eventType, [certificate]),- fields: [- { label: "Serial Number", value: certificate.serialNumber },- ...(altNames.length ? [{ label: "SANs", value: altNames.join(", ") }] : []),- ...(certificate.profileName ? [{ label: "Profile", value: certificate.profileName }] : []),- ...(!isApplicationAlert && certificate.applicationName- ? [{ label: "Application", value: certificate.applicationName }]- : []),- { label: "Expires", value: formatUtcDate(certificate.notAfter) },- ...(revocationReason ? [{ label: "Revocation Reason", value: revocationReason }] : [])- ],- resource: {- id: certificate.id,- serialNumber: certificate.serialNumber,- commonName: certificate.commonName,- altNames,- status: certificate.status,- notBefore: certificate.notBefore.toISOString(),- notAfter: certificate.notAfter.toISOString(),- revokedAt: certificate.revokedAt?.toISOString() ?? null,- revocationReason: certificate.revocationReason,- profileId: certificate.profileId,- profileName: certificate.profileName,- applicationId: certificate.applicationId,- applicationName: certificate.applicationName- }- };- })- };- };-- const getCertificateManagerAuditEvent = (input: TAlertAuditInput): TAuditEvent => {- if (input.action === AlertAuditAction.TestChannel) {- return buildCertificateManagerAlertAuditEvent(input, { applications: [], profiles: [] });- }- const { applicationIds = [], profileIds = [] } = parseFilters(input.alert.condition);- const nameById = new Map(- Object.values(input.alert.filters ?? {})- .flat()- .map((resource) => [resource.id, resource.name])- );- const withNames = (ids: string[]) => ids.map((id) => ({ id, name: nameById.get(id) ?? null }));- return buildCertificateManagerAlertAuditEvent(input, {- applications: withNames(applicationIds),- profiles: withNames(profileIds)- });- };+ resourceId ? `/applications/${resourceId}/alerts/${alertId}` : undefined;const getAuditEvent = (input: TAlertAuditInput): TAuditEvent => {- const resourceId = input.action === AlertAuditAction.TestChannel ? input.test.resourceId : input.alert.resourceId;- if (!resourceId) return getCertificateManagerAuditEvent(input);-if (input.action === AlertAuditAction.TestChannel) {const { test } = input;return {type: EventType.TEST_PKI_APPLICATION_ALERT_CHANNEL,metadata: {- applicationId: resourceId,+ applicationId: test.resourceId ?? null,applicationName: test.resourceName ?? null,alertId: test.alertId,alertName: test.alertName ?? null,@@ -337,7 +129,7 @@ export const certManagerApplicationAlertProviderFactory = ({}const metadata = {- applicationId: resourceId,+ applicationId: input.alert.resourceId,applicationName: input.alert.resourceName ?? null,alertId: input.alert.id,name: input.alert.name,@@ -348,70 +140,33 @@ export const certManagerApplicationAlertProviderFactory = ({return { type: EventType.DELETE_PKI_APPLICATION_ALERT, metadata };};- const getTelemetryEvent = ({- action,- orgId,- projectId,- resourceId,- eventType- }: TAlertTelemetryInput): TAlertTelemetryEvent | undefined => {- if (!projectId) return undefined;- const properties = {- orgId,- projectId,- ...(resourceId- ? { applicationId: resourceId, alertScope: PkiAlertScope.Application }- : { alertScope: PkiAlertScope.CertificateManager })- };+ const getTelemetryEvent = ({ action, orgId, projectId, resourceId, eventType }: TAlertTelemetryInput) => {+ if (!projectId || !resourceId) return undefined;return buildPkiAlertTelemetryEvent(action,- properties,- TELEMETRY_ALERT_TYPE_BY_EVENT[eventType as CertificateAlertEvent]+ { orgId, projectId, applicationId: resourceId, alertScope: PkiAlertScope.Application },+ CERTIFICATE_ALERT_KIND_TELEMETRY_TYPES[ALERT_KIND_BY_EVENT[eventType as CertificateAlertEvent]]);};- const $assertCertificateManagerPermission = async ({- action,- projectId,- actor- }: TAlertPermissionInput & { projectId: string }) => {- const { permission } = await permissionService.getProjectPermission({- actor: actor.actor,- actorId: actor.actorId,- projectId,- actorAuthMethod: actor.actorAuthMethod,- actorOrgId: actor.actorOrgId,- actionProjectType: ActionProjectType.CertificateManager+ const buildPayload = (alert: TAlertContext, targets: TApplicationAlertCertificate[], viewUrl: string) =>+ buildCertificateAlertPayload({+ alert,+ targets,+ viewUrl,+ kind: ALERT_KIND_BY_EVENT[alert.eventType as CertificateAlertEvent],+ webhookSource: getWebhookSource({ alertId: alert.id, resourceId: alert.resourceId }),+ resourceOwnerKind: "Application",+ applicationName: targets[0]?.applicationName ?? null});- ForbiddenError.from(permission).throwUnlessCan(- CERT_MANAGER_ALERT_PERMISSION_ACTIONS[action],- ProjectPermissionSub.PkiAlerts- );-- const definesDelivery = action === AlertPermissionAction.Create || action === AlertPermissionAction.Edit;- if (!definesDelivery) return;- if (- !isUnconditionalGrant(- permission.rulesFor(ProjectPermissionCertificateActions.Read, ProjectPermissionSub.Certificates)- )- ) {- throw new ForbiddenRequestError({- message:- "Certificate Manager alerts send certificate details from every application, so they require permission to read all certificates. Create the alert on an application instead."- });- }- };-- const assertPermission = async (input: TAlertPermissionInput): Promise<void> => {- const { action, projectId, resourceId, actor } = input;+ 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) {- await $assertCertificateManagerPermission({ ...input, projectId });- return;+ throw new BadRequestError({ message: "Application alerts require an application ID" });}assertValidApplicationId(resourceId);@@ -446,83 +201,10 @@ export const certManagerApplicationAlertProviderFactory = ({}};- const assertConditionInScope = async (input: {- projectId?: string | null;- resourceId?: string | null;- condition: unknown;- previousCondition?: unknown;- }): Promise<void> => {- if (!input.projectId) return;- const { applicationIds = [], profileIds = [] } = CertificateFilterSchema.parse(input.condition ?? {});- if (input.resourceId && (applicationIds.length || profileIds.length)) {- throw new BadRequestError({- message:- "Application alerts already cover a single application. Remove applicationIds and profileIds, or create a Certificate Manager alert instead."- });- }-- const previous = parseFilters(input.previousCondition);- const savedApplicationIds = toIdSet(previous.applicationIds);- const savedProfileIds = toIdSet(previous.profileIds);- const addedApplicationIds = applicationIds.filter((id) => !savedApplicationIds.has(id.toLowerCase()));- const addedProfileIds = profileIds.filter((id) => !savedProfileIds.has(id.toLowerCase()));-- const [foundApplicationIds, foundProfileIds]: string[][] = await Promise.all([- addedApplicationIds.length- ? certManagerApplicationAlertDAL.findProjectApplicationIds(input.projectId, addedApplicationIds)- : [],- addedProfileIds.length- ? certManagerApplicationAlertDAL.findProjectProfileIds(input.projectId, addedProfileIds)- : []- ]);-- const foundApplicationIdSet = toIdSet(foundApplicationIds);- const missingApplicationIds = addedApplicationIds.filter((id) => !foundApplicationIdSet.has(id.toLowerCase()));- if (missingApplicationIds.length) {- throw new NotFoundError({- message: `${missingApplicationIds.length === 1 ? "Application" : "Applications"} not found in Certificate Manager: ${formatIds(missingApplicationIds)}`- });- }- const foundProfileIdSet = toIdSet(foundProfileIds);- const missingProfileIds = addedProfileIds.filter((id) => !foundProfileIdSet.has(id.toLowerCase()));- if (missingProfileIds.length) {- throw new NotFoundError({- message: `${missingProfileIds.length === 1 ? "Certificate profile" : "Certificate profiles"} not found in Certificate Manager: ${formatIds(missingProfileIds)}`- });- }- };-- const getFilters = async ({- orgId,- projectId,- alerts- }: {- orgId: string;- projectId: string | null;- alerts: { id: string; condition: unknown }[];- }): Promise<Map<string, TAlertFilters>> => {- const filtersByAlert = alerts.map((alert) => ({ id: alert.id, ...parseFilters(alert.condition) }));- const applicationIds = [...new Set(filtersByAlert.flatMap((filters) => filters.applicationIds ?? []))];- const profileIds = [...new Set(filtersByAlert.flatMap((filters) => filters.profileIds ?? []))];-- const [applications, profiles] = await Promise.all([- certManagerApplicationAlertDAL.findApplicationNamesByIds(applicationIds, orgId),- projectId ? certManagerApplicationAlertDAL.findProfileNamesByIds(projectId, profileIds) : []- ]);- const nameById = new Map([...applications, ...profiles].map((entry) => [entry.id.toLowerCase(), entry.name]));-- const withNames = (ids: string[] = []) => ids.map((id) => ({ id, name: nameById.get(id.toLowerCase()) ?? null }));-- return new Map(- filtersByAlert.map((filters) => [- filters.id,- { applications: withNames(filters.applicationIds), profiles: withNames(filters.profileIds) }- ])- );- };-const resolveProjectId = async ({ orgId, resourceId }: { orgId: string; resourceId?: string | null }) => {- if (!resourceId) return resolveCertManagerProjectId(certManagerProjectResolver, orgId);+ if (!resourceId) {+ throw new BadRequestError({ message: "Application alerts require an application ID" });+ }assertValidApplicationId(resourceId);const application = await certManagerApplicationAlertDAL.findApplicationById(resourceId);if (!application || application.orgId !== orgId) {@@ -533,7 +215,6 @@ export const certManagerApplicationAlertProviderFactory = ({return {resourceType: CERT_MANAGER_APPLICATION_RESOURCE_TYPE,- supportsScopeWideAlerts: true,events: [{key: CertificateAlertEvent.Expiry,@@ -554,20 +235,14 @@ export const certManagerApplicationAlertProviderFactory = ({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);- },+ dedupWindowHours: expiryDedupWindowHours,assertPermission,assertResourceInScope,- assertConditionInScope,assertChannelTypesAllowed: (input) => assertCertManagerAlertChannelTypesAllowed(licenseService, input),recipientPolicy: { atOrgScope: true, allowEmailAddresses: true },includeLastRun: true,getAuditEvent,getWebhookSource,- getFilters,resolveProjectId,getResourceNames: async ({ orgId, resourceIds }) =>new Map(diff --git a/backend/src/services/alert/providers/cert-manager-signer-alert-provider.ts b/backend/src/services/alert/providers/cert-manager-signer-alert-provider.tsindex 0e0dd64723..14298cb817 100644--- a/backend/src/services/alert/providers/cert-manager-signer-alert-provider.ts+++ b/backend/src/services/alert/providers/cert-manager-signer-alert-provider.ts@@ -1,9 +1,6 @@-import { ForbiddenError } from "@casl/ability";--import { ActionProjectType, ProjectMembershipRole } from "@app/db/schemas";+import { ProjectMembershipRole } from "@app/db/schemas";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";-import { ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import { getConfig } from "@app/lib/config/env";import { BadRequestError, ForbiddenRequestError } from "@app/lib/errors";import { TCertManagerProjectResolverFactory } from "@app/services/cert-manager-instance/cert-manager-project-resolver";@@ -16,7 +13,6 @@ import {ALERT_SCAN_LEAD_INTERVAL,AlertPermissionAction,AlertTriggerType,- DEFAULT_DEDUP_WINDOW_HOURS,IScheduledAlertProvider,TAlertContext,TAlertPermissionInput,@@ -25,12 +21,13 @@ import {} from "../alert-types";import {assertCertManagerAlertChannelTypesAllowed,+ assertNoAlertResource,buildCertificateManagerAlertAuditEvent,buildPkiAlertTelemetryEvent,- CERT_MANAGER_ALERT_PERMISSION_ACTIONS,certificateDisplayName,- expirationDedupWindowHours,+ expiryDedupWindowHours,ExpiryFieldsSchema,+ getCertManagerAlertPermission,resolveCertManagerProjectId,splitAltNames} from "./cert-manager-alert-fns";@@ -38,14 +35,11 @@ import { TCertManagerSignerAlertDALFactory, TSignerAlertCertificate } from "./ceconst SignerExpirationConditionSchema = ExpiryFieldsSchema.strict();-const assertNoResource = (resourceId?: string | null) => {- if (resourceId) {- throw new BadRequestError({- message:- "Signer certificate expiration alerts cover every signer in Certificate Manager and can't be bound to a resource. Remove resourceId."- });- }-};+const assertNoResource = (resourceId?: string | null) =>+ assertNoAlertResource(+ resourceId,+ "Signer certificate expiration alerts cover every signer in Certificate Manager and can't be bound to a resource. Remove resourceId."+ );const getWebhookSource = ({ alertId }: { alertId: string }) => `/alerts/${alertId}`;@@ -140,18 +134,7 @@ export const certManagerSignerAlertProviderFactory = ({}assertNoResource(resourceId);- const { permission, hasRole } = await permissionService.getProjectPermission({- actor: actor.actor,- actorId: actor.actorId,- projectId,- actorAuthMethod: actor.actorAuthMethod,- actorOrgId: actor.actorOrgId,- actionProjectType: ActionProjectType.CertificateManager- });- ForbiddenError.from(permission).throwUnlessCan(- CERT_MANAGER_ALERT_PERMISSION_ACTIONS[action],- ProjectPermissionSub.PkiAlerts- );+ const { hasRole } = await getCertManagerAlertPermission(permissionService, { action, projectId, actor });const definesDelivery = action === AlertPermissionAction.Create || action === AlertPermissionAction.Edit;if (definesDelivery && !hasRole(ProjectMembershipRole.Admin)) {@@ -185,11 +168,7 @@ export const certManagerSignerAlertProviderFactory = ({buildViewUrl,buildPayload,targetId: (certificate) => certificate.id,- dedupWindowHours: (condition) => {- const parsed = SignerExpirationConditionSchema.safeParse(condition);- if (!parsed.success) return DEFAULT_DEDUP_WINDOW_HOURS;- return expirationDedupWindowHours(durationToDays(parsed.data.alertBefore), parsed.data.dailyReminder);- },+ dedupWindowHours: expiryDedupWindowHours,assertPermission,assertResourceInScope: async ({ resourceId }) => assertNoResource(resourceId),assertChannelTypesAllowed: (input) => assertCertManagerAlertChannelTypesAllowed(licenseService, input),diff --git a/backend/src/services/certificate/certificate-alert-events.ts b/backend/src/services/certificate/certificate-alert-events.tsindex 9f5feea73e..e7b2d8d6f0 100644--- a/backend/src/services/certificate/certificate-alert-events.ts+++ b/backend/src/services/certificate/certificate-alert-events.ts@@ -13,6 +13,15 @@ export enum CertificateAlertEvent {Revocation = "cert-manager.application.certificate.revocation"}+export const CERT_MANAGER_RESOURCE_TYPE = "cert-manager";++export enum CertificateManagerAlertEvent {+ Expiry = "cert-manager.certificate.expiry",+ Issuance = "cert-manager.certificate.issuance",+ Renewal = "cert-manager.certificate.renewal",+ Revocation = "cert-manager.certificate.revocation"+}+export const getIssuanceAlertEvent = (isRenewal?: boolean) =>isRenewal ? CertificateAlertEvent.Renewal : CertificateAlertEvent.Issuance;diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.tsindex f14d9a4465..a223f73e62 100644--- a/frontend/src/hooks/api/alerts/types.ts+++ b/frontend/src/hooks/api/alerts/types.ts@@ -30,6 +30,7 @@ export enum AlertRunStatus {export enum CertificateAlertResourceType {Application = "cert-manager.application",+ CertificateManager = "cert-manager",Signer = "cert-manager.signer"}@@ -41,6 +42,13 @@ export enum CertificateAlertEventType {SignerCertificateExpiry = "cert-manager.signer.certificate.expiry"}+export enum CertificateManagerAlertEventType {+ Expiry = "cert-manager.certificate.expiry",+ Issuance = "cert-manager.certificate.issuance",+ Renewal = "cert-manager.certificate.renewal",+ Revocation = "cert-manager.certificate.revocation"+}+export const MIN_ALERT_BEFORE_DAYS = 1;export const MAX_ALERT_BEFORE_DAYS = 90;export const MAX_CERTIFICATE_ALERT_BEFORE_DAYS = 365;diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsxindex 32bf9c9e4c..81ac9f7bd5 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx@@ -64,6 +64,7 @@ import {CertificateAlertScopeKind,CertificateFilterKind,formatAlertBefore,+ fromApiEventType,getAlertResourceId,getFilterName,getScopeEventTypes,@@ -309,7 +310,10 @@ export const ApplicationAlertsCard = ({isLoading: isCertificateAlertsLoading,isError: isCertificateAlertsError} = useListAlerts({- resourceType: CertificateAlertResourceType.Application,+ resourceType:+ scope.kind === CertificateAlertScopeKind.CertificateManager+ ? CertificateAlertResourceType.CertificateManager+ : CertificateAlertResourceType.Application,projectId,...(resourceId ? { resourceId } : {})});@@ -321,10 +325,11 @@ export const ApplicationAlertsCard = ({{ resourceType: CertificateAlertResourceType.Signer, projectId },{ enabled: scope.kind === CertificateAlertScopeKind.CertificateManager });- const alerts =+ const alerts = (scope.kind === CertificateAlertScopeKind.CertificateManager? [...certificateAlerts, ...signerAlerts]- : certificateAlerts;+ : certificateAlerts+ ).map((alert) => ({ ...alert, eventType: fromApiEventType(alert.eventType) }));const isAlertsLoading =isCertificateAlertsLoading ||(scope.kind === CertificateAlertScopeKind.CertificateManager && isSignerAlertsLoading);diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsxindex c14fc49148..48a8b1dfe0 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx@@ -51,6 +51,7 @@ import {TCertificateAlertForm,TCertificateAlertScope,TMemberEmails,+ toApiEventType,toCertificateAlertForm,toCondition} from "./types";@@ -124,9 +125,9 @@ const CertificateAlertWizard = ({await createAlert.mutateAsync({name: values.name,description: values.description || undefined,- resourceType: getAlertResourceType(values.eventType),+ resourceType: getAlertResourceType(scope, values.eventType),resourceId: getAlertResourceId(scope),- eventType: values.eventType,+ eventType: toApiEventType(scope, values.eventType),condition,enabled: values.enabled,projectId,diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsxindex 6a548007be..1adbbc8575 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx@@ -171,7 +171,7 @@ export const ChannelsStep = ({key={field.id}index={index}projectId={projectId}- resourceType={getAlertResourceType(eventType)}+ resourceType={getAlertResourceType(scope, eventType)}resourceId={getAlertResourceId(scope)}alertId={alertId}canRemovediff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.tsindex 1556572e06..99cafe7a08 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts@@ -4,6 +4,7 @@ import {AlertPrincipalType,CertificateAlertEventType,CertificateAlertResourceType,+ CertificateManagerAlertEventType,channelFormSchema,MAX_CERTIFICATE_ALERT_BEFORE_DAYS,MAX_CERTIFICATE_ALERT_FILTER_IDS,@@ -37,7 +38,7 @@ export enum CertificateAlertAccess {Admin = "admin"}-export const CERTIFICATE_ALERT_EVENT_GROUPS: {+const CERTIFICATE_ALERT_EVENT_GROUPS: {label: string;events: CertificateAlertEventType[];scopes: CertificateAlertScopeKind[];@@ -80,10 +81,43 @@ export const isExpiryEventType = (eventType: CertificateAlertEventType) =>export const isFilterableEventType = (eventType: CertificateAlertEventType) =>eventType !== CertificateAlertEventType.SignerCertificateExpiry;-export const getAlertResourceType = (eventType: CertificateAlertEventType) =>- eventType === CertificateAlertEventType.SignerCertificateExpiry- ? CertificateAlertResourceType.Signer+const CERTIFICATE_MANAGER_EVENT_TYPES: Partial<+ Record<CertificateAlertEventType, CertificateManagerAlertEventType>+> = {+ [CertificateAlertEventType.Expiry]: CertificateManagerAlertEventType.Expiry,+ [CertificateAlertEventType.Issuance]: CertificateManagerAlertEventType.Issuance,+ [CertificateAlertEventType.Renewal]: CertificateManagerAlertEventType.Renewal,+ [CertificateAlertEventType.Revocation]: CertificateManagerAlertEventType.Revocation+};++const EVENT_TYPES_BY_CERTIFICATE_MANAGER_EVENT = Object.fromEntries(+ Object.entries(CERTIFICATE_MANAGER_EVENT_TYPES).map(([eventType, apiEventType]) => [+ apiEventType,+ eventType+ ])+) as Record<string, CertificateAlertEventType>;++export const getAlertResourceType = (+ scope: TCertificateAlertScope,+ eventType: CertificateAlertEventType+) => {+ if (eventType === CertificateAlertEventType.SignerCertificateExpiry)+ return CertificateAlertResourceType.Signer;+ return scope.kind === CertificateAlertScopeKind.CertificateManager+ ? CertificateAlertResourceType.CertificateManager: CertificateAlertResourceType.Application;+};++export const toApiEventType = (+ scope: TCertificateAlertScope,+ eventType: CertificateAlertEventType+): string =>+ (scope.kind === CertificateAlertScopeKind.CertificateManager &&+ CERTIFICATE_MANAGER_EVENT_TYPES[eventType]) ||+ eventType;++export const fromApiEventType = (eventType: string) =>+ EVENT_TYPES_BY_CERTIFICATE_MANAGER_EVENT[eventType] ?? eventType;const ALERT_EVENT_DESCRIPTIONS: Record<CertificateAlertEventType, (where: string) => string> = {[CertificateAlertEventType.Expiry]: () => "Fires ahead of a certificate's expiry date.",