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
Address PR comments
Carlos Monastyrski6f0e98f8c39a
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 88ad6d938c..6f04b2ffce 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -707,10 +707,10 @@ 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, 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 the project Admin role, since it sends details from every application (PKI permissions are admin or member, not granular). `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 too (`assertCertManagerAdminAlertPermission` in `cert-manager-alert-fns.ts`). 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.+- **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 `sourceEvent: { resourceType, eventKey }`; the consumer then runs the source resource's alerts plus the resource-less alerts of every event sourced from it (`alertProviderRegistry.findEventsBySource`), each under its own `eventType`. Certificate Manager-wide (`cert-manager`) and signer (`cert-manager.signer`) alerts are scope-wide providers, and creating or editing either requires the project Admin role, since PKI permissions are admin or member, not granular. **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`.+- **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. For dedup windows shorter than the scan interval (daily reminders), also order least-recently-notified first. `scanExpiringCertificates` (`cert-manager-expiring-certificates-fns.ts`) does both.- **Deleting an alertable resource does NOT delete its alerts. You have to reap them yourself.** `alerts.resourceId` is a plain string column with **no foreign key** to the resource's table (a provider's `resourceType` can point at anything), so nothing cascades. Skip the reap and the row survives as a dangling alert whose `findScheduledTargets` matches nothing and whose "view" link 404s. Two helpers on `alertService`, and picking the wrong one is the bug:- **`deleteAlertsForDeletedResource({ resourceType, resourceId })`** when the resource **row is gone**. It has **no scope filter** and reaps across every org and project. This is required, not just tidier: the same resource can be watched from another org (a root-org identity invited into a child org), so an `orgId`-filtered reap leaves those rows orphaned.- **`deleteAlertsForResource({ orgId, projectId?, resourceType, resourceId })`** when the resource merely **left a scope** (removed from a project, removed from an org) but still exists. Narrow on purpose: leaving one project must not drop the org-level alert, and leaving one org must not touch another org's alerts. Omitting `projectId` reaps the whole org, which is what org-membership removal wants since it cascades the project memberships.diff --git a/backend/e2e-test/cert-manager-application-alert-dal.spec.ts b/backend/e2e-test/cert-manager-certificate-alert-dal.spec.tssimilarity index 97%rename from backend/e2e-test/cert-manager-application-alert-dal.spec.tsrename to backend/e2e-test/cert-manager-certificate-alert-dal.spec.tsindex 825bf53555..a50e4b1db2 100644--- a/backend/e2e-test/cert-manager-application-alert-dal.spec.ts+++ b/backend/e2e-test/cert-manager-certificate-alert-dal.spec.ts@@ -6,11 +6,11 @@ import { afterAll, beforeAll, describe, expect, test } from "vitest";import { TableName } from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";import { AlertRunStatus } from "@app/services/alert/alert-types";-import { certManagerApplicationAlertDALFactory } from "@app/services/alert/providers/cert-manager-application-alert-dal";+import { certManagerCertificateAlertDALFactory } from "@app/services/alert/providers/cert-manager-certificate-alert-dal";declare const testDb: Knex;-const dal = certManagerApplicationAlertDALFactory(testDb as never);+const dal = certManagerCertificateAlertDALFactory(testDb as never);const PROJECT_ID = seedData1.project.id;const ORG_ID = seedData1.organization.id;diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 9439acf1fe..d08fd75a11 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -966,7 +966,11 @@ export enum EventType {CREATE_CERTIFICATE_MANAGER_ALERT = "create-certificate-manager-alert",UPDATE_CERTIFICATE_MANAGER_ALERT = "update-certificate-manager-alert",DELETE_CERTIFICATE_MANAGER_ALERT = "delete-certificate-manager-alert",- TEST_CERTIFICATE_MANAGER_ALERT_CHANNEL = "test-certificate-manager-alert-channel"+ TEST_CERTIFICATE_MANAGER_ALERT_CHANNEL = "test-certificate-manager-alert-channel",+ CREATE_SIGNER_ALERT = "create-signer-alert",+ UPDATE_SIGNER_ALERT = "update-signer-alert",+ DELETE_SIGNER_ALERT = "delete-signer-alert",+ TEST_SIGNER_ALERT_CHANNEL = "test-signer-alert-channel"}// Maps each actor type to the JSONB key that holds the actor's primary ID in actorMetadata.@@ -7959,18 +7963,46 @@ interface DeleteCertificateManagerAlertEvent {metadata: TCertificateManagerAlertEventMetadata;}+type TAlertChannelTestEventMetadata = {+ alertId?: string;+ alertName?: string | null;+ channelId?: string;+ channelName?: string | null;+ channelType: string;+ success: boolean;+ deliveredTo?: number;+ error?: string;+};+interface TestCertificateManagerAlertEvent {type: EventType.TEST_CERTIFICATE_MANAGER_ALERT_CHANNEL;- metadata: {- alertId?: string;- alertName?: string | null;- channelId?: string;- channelName?: string | null;- channelType: string;- success: boolean;- deliveredTo?: number;- error?: string;- };+ metadata: TAlertChannelTestEventMetadata;+}++type TSignerAlertEventMetadata = {+ alertId: string;+ name: string;+ eventType: string;+};++interface CreateSignerAlertEvent {+ type: EventType.CREATE_SIGNER_ALERT;+ metadata: TSignerAlertEventMetadata;+}++interface UpdateSignerAlertEvent {+ type: EventType.UPDATE_SIGNER_ALERT;+ metadata: TSignerAlertEventMetadata;+}++interface DeleteSignerAlertEvent {+ type: EventType.DELETE_SIGNER_ALERT;+ metadata: TSignerAlertEventMetadata;+}++interface TestSignerAlertEvent {+ type: EventType.TEST_SIGNER_ALERT_CHANNEL;+ metadata: TAlertChannelTestEventMetadata;}export type Event =@@ -7986,6 +8018,10 @@ export type Event =| UpdateCertificateManagerAlertEvent| DeleteCertificateManagerAlertEvent| TestCertificateManagerAlertEvent+ | CreateSignerAlertEvent+ | UpdateSignerAlertEvent+ | DeleteSignerAlertEvent+ | TestSignerAlertEvent| CreateSubOrganizationEvent| UpdateSubOrganizationEvent| DeleteSubOrganizationEventdiff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 602403308f..8b726b488e 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -250,8 +250,8 @@ import { 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 { certManagerCertificateAlertDALFactory } from "@app/services/alert/providers/cert-manager-certificate-alert-dal";import { certManagerSignerAlertDALFactory } from "@app/services/alert/providers/cert-manager-signer-alert-dal";import { certManagerSignerAlertProviderFactory } from "@app/services/alert/providers/cert-manager-signer-alert-provider";import { identityCredentialAlertDALFactory } from "@app/services/alert/providers/identity-credential-alert-dal";@@ -1086,7 +1086,7 @@ export const registerRoutes = async (const alertChannelDAL = alertChannelDALFactory(db);const alertChannelMembershipDAL = alertChannelMembershipDALFactory(db);const alertHistoryDAL = alertHistoryDALFactory(db);- const certManagerApplicationAlertDAL = certManagerApplicationAlertDALFactory(db);+ const certManagerCertificateAlertDAL = certManagerCertificateAlertDALFactory(db);const certManagerProjectResolver = certManagerProjectResolverFactory({orgDAL,projectDAL@@ -1100,14 +1100,14 @@ export const registerRoutes = async ();alertProviderRegistry.register(certManagerApplicationAlertProviderFactory({- certManagerApplicationAlertDAL,+ certManagerCertificateAlertDAL,permissionService,licenseService}));alertProviderRegistry.register(certManagerAlertProviderFactory({- certManagerApplicationAlertDAL,+ certManagerCertificateAlertDAL,permissionService,licenseService,certManagerProjectResolverdiff --git a/backend/src/services/alert/alert-event-consumer.test.ts b/backend/src/services/alert/alert-event-consumer.test.tsindex 745065a648..7ef5ef92b5 100644--- a/backend/src/services/alert/alert-event-consumer.test.ts+++ b/backend/src/services/alert/alert-event-consumer.test.ts@@ -38,7 +38,7 @@ const buildConsumer = (opts?: {results?: AlertDispatchOutcome[];eventKeys?: string[];findAlerts?: (filter: { resourceType: string; resourceId?: string | null; eventType: string }) => Promise<unknown[]>;- relays?: { resourceType: string; eventKey: string }[];+ sourcedEvents?: { resourceType: string; eventKey: string }[];}) => {const runs: {alertId: string;@@ -78,7 +78,7 @@ const buildConsumer = (opts?: {} as never,alertProviderRegistry: {eventTriggeredKeys: () => new Set(eventKeys),- relaysFor: () => opts?.relays ?? [],+ findEventsBySource: () => opts?.sourcedEvents ?? [],get: (resourceType: string) =>resourceType === "approval.workflow"? ({ events: eventKeys.map((key) => ({ key, triggerType: AlertTriggerType.Event })) } as never)@@ -117,15 +117,15 @@ 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 () => {+ test("also runs the resource-less alerts of every event sourced from this event, each under 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" }],+ sourcedEvents: [{ resourceType: "approval.org", eventKey: "approval.org.request_opened" }],findAlerts: async (filter) => {lookupsSeen.push(filter);return [{- id: filter.resourceType === "approval.org" ? "relayed-alert" : "bound-alert",+ id: filter.resourceType === "approval.org" ? "sourced-alert" : "bound-alert",resourceType: filter.resourceType,orgId: ORG_ID,eventType: filter.eventType@@ -150,7 +150,7 @@ describe("alert event consumer", () => {expect(runs.map((run) => [run.alertId, run.eventType])).toEqual(expect.arrayContaining([["bound-alert", EVENT_TYPE],- ["relayed-alert", "approval.org.request_opened"]+ ["sourced-alert", "approval.org.request_opened"]]));});diff --git a/backend/src/services/alert/alert-event-consumer.ts b/backend/src/services/alert/alert-event-consumer.tsindex 030c2080c9..4765954f3c 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" | "relaysFor">;+ alertProviderRegistry: Pick<TAlertProviderRegistry, "get" | "eventTriggeredKeys" | "findEventsBySource">;};type TAlertLookup = TAlertDALFactory["findEnabledForEvent"];@@ -70,11 +70,14 @@ export const alertEventConsumerFactory = ({};}+ const sourcedEvents = alertProviderRegistry.findEventsBySource({ resourceType, eventKey: event.eventType });const lookups = [{ resourceType, resourceId, eventType: event.eventType },- ...alertProviderRegistry- .relaysFor(resourceType, event.eventType)- .map((relay) => ({ resourceType: relay.resourceType, resourceId: null, eventType: relay.eventKey }))+ ...sourcedEvents.map((sourced) => ({+ resourceType: sourced.resourceType,+ resourceId: null,+ eventType: sourced.eventKey+ }))];const alerts = (await Promise.all(lookups.map((lookup) => findAlerts({ orgId, projectId, ...lookup })))).flat();diff --git a/backend/src/services/alert/alert-provider-registry.ts b/backend/src/services/alert/alert-provider-registry.tsindex 8810ca4ea4..9f878c097d 100644--- a/backend/src/services/alert/alert-provider-registry.ts+++ b/backend/src/services/alert/alert-provider-registry.ts@@ -1,6 +1,6 @@import { BadRequestError } from "@app/lib/errors";-import { AlertTriggerType, IResourceAlertProvider, TAlertEventDefinition } from "./alert-types";+import { AlertTriggerType, IResourceAlertProvider, TAlertEventDefinition, TAlertEventRef } from "./alert-types";export const resolveAlertProjectId = async (provider: IResourceAlertProvider,@@ -70,17 +70,17 @@ export const alertProviderRegistryFactory = () => {return eventTriggeredKeyCache;};- const relaysFor = (resourceType: string, eventKey: string): { resourceType: string; eventKey: string }[] =>+ const findEventsBySource = (source: TAlertEventRef): TAlertEventRef[] =>[...providers.values()].flatMap((provider) =>provider.events.filter((event) =>event.triggerType === AlertTriggerType.Event &&- event.relayedFrom?.resourceType === resourceType &&- event.relayedFrom.eventKey === eventKey+ event.sourceEvent?.resourceType === source.resourceType &&+ event.sourceEvent.eventKey === source.eventKey).map((event) => ({ resourceType: provider.resourceType, eventKey: event.key })));- return { register, get, resourceTypes, eventTriggeredKeys, relaysFor };+ return { register, get, resourceTypes, eventTriggeredKeys, findEventsBySource };};diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.tsindex 1149160c63..7cfd027017 100644--- a/backend/src/services/alert/alert-types.ts+++ b/backend/src/services/alert/alert-types.ts@@ -17,11 +17,13 @@ export enum AlertTriggerType {Event = "event"}+export type TAlertEventRef = { resourceType: string; eventKey: string };+export type TAlertEventDefinition = {key: string;triggerType: AlertTriggerType;conditionSchema: z.ZodTypeAny;- relayedFrom?: { resourceType: string; eventKey: string };+ sourceEvent?: TAlertEventRef;};export enum AlertRunStatus {@@ -191,9 +193,7 @@ export interface IResourceAlertProvider<TTarget = unknown> {// afterwards, so this returns all current matches in the window (not minus already-alerted).// Must be ordered most-urgent-first (soonest expiry): the engine's per-channel maxTargetsPerRun cap// keeps the head of this list and defers the tail, so urgency ordering ensures the targets closest- // to expiry are never the ones dropped. A provider that caps its own row count first takes targets- // not yet delivered on every channel, then the ones this alert notified least recently, so a cap- // below the due count rotates instead of re-sending the same head every run.+ // to expiry are never the ones dropped.// Required for any Scheduled event; the registry enforces that at boot.findScheduledTargets?(input: TFindScheduledTargetsInput): Promise<TTarget[]>;diff --git a/backend/src/services/alert/providers/cert-manager-alert-fns.ts b/backend/src/services/alert/providers/cert-manager-alert-fns.tsindex 8d4298b48c..120a0d4094 100644--- a/backend/src/services/alert/providers/cert-manager-alert-fns.ts+++ b/backend/src/services/alert/providers/cert-manager-alert-fns.ts@@ -24,7 +24,7 @@ import {TAlertPermissionInput,TAlertTelemetryEvent} from "../alert-types";-import { TApplicationAlertCertificate } from "./cert-manager-application-alert-dal";+import { TAlertCertificate } from "./cert-manager-certificate-alert-dal";const MIN_ALERT_BEFORE_DAYS = 1;const MAX_ALERT_BEFORE_DAYS = 365;@@ -68,6 +68,8 @@ export const CERT_MANAGER_ALERT_PERMISSION_ACTIONS: Record<AlertPermissionAction[AlertPermissionAction.Delete]: ProjectPermissionActions.Delete};+export const getScopeWideAlertWebhookSource = ({ alertId }: { alertId: string }) => `/alerts/${alertId}`;+export const assertNoAlertResource = (resourceId: string | null | undefined, message: string) => {if (resourceId) throw new BadRequestError({ message });};@@ -136,6 +138,19 @@ export const resolveCertManagerProjectId = async (type TAlertFilterNames = { id: string; name: string | null }[];+export const toAlertChannelTestAuditMetadata = ({+ test+}: Extract<TAlertAuditInput, { action: AlertAuditAction.TestChannel }>) => ({+ alertId: test.alertId,+ alertName: test.alertName ?? null,+ channelId: test.channelId,+ channelName: test.channelName ?? null,+ channelType: test.channelType,+ success: test.success,+ deliveredTo: test.deliveredTo,+ error: test.error+});+export const buildCertificateManagerAlertAuditEvent = (input: TAlertAuditInput,{@@ -145,20 +160,7 @@ export const buildCertificateManagerAlertAuditEvent = (}: { applications: TAlertFilterNames; profiles: TAlertFilterNames; sources: CertificateSource[] }): TAuditEvent => {if (input.action === AlertAuditAction.TestChannel) {- const { test } = input;- return {- type: EventType.TEST_CERTIFICATE_MANAGER_ALERT_CHANNEL,- metadata: {- alertId: test.alertId,- alertName: test.alertName ?? null,- channelId: test.channelId,- channelName: test.channelName ?? null,- channelType: test.channelType,- success: test.success,- deliveredTo: test.deliveredTo,- error: test.error- }- };+ return { type: EventType.TEST_CERTIFICATE_MANAGER_ALERT_CHANNEL, metadata: toAlertChannelTestAuditMetadata(input) };}const { alert } = input;@@ -211,7 +213,7 @@ const CERTIFICATE_ALERT_KIND_VERBS: Record<CertificateAlertKind, string> = {[CertificateAlertKind.Revocation]: "was revoked"};-const certificateSeverity = (kind: CertificateAlertKind, targets: TApplicationAlertCertificate[]): TAlertSeverity => {+const certificateSeverity = (kind: CertificateAlertKind, targets: TAlertCertificate[]): TAlertSeverity => {if (kind === CertificateAlertKind.Expiry) return expirySeverity(targets.map((target) => target.notAfter));if (kind === CertificateAlertKind.Revocation) return "warning";return "info";@@ -230,7 +232,7 @@ export const buildCertificateAlertPayload = ({applicationName}: {alert: TAlertContext;- targets: TApplicationAlertCertificate[];+ targets: TAlertCertificate[];viewUrl: string;kind: CertificateAlertKind;webhookSource?: string;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.tsindex 45e68ef80b..8245c1d4b6 100644--- a/backend/src/services/alert/providers/cert-manager-alert-provider.test.ts+++ b/backend/src/services/alert/providers/cert-manager-alert-provider.test.ts@@ -6,7 +6,7 @@ import { PkiAlertScope, PostHogEventTypes } from "@app/services/telemetry/telemeimport { 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";+import { TAlertCertificate } from "./cert-manager-certificate-alert-dal";vi.mock("@app/lib/config/env", () => ({getConfig: () => ({ SITE_URL: "https://app.infisical.com" })@@ -22,7 +22,7 @@ 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 => ({+const sampleCertificate = (overrides: Partial<TAlertCertificate> = {}): TAlertCertificate => ({id: "cert-1",serialNumber: "105d3b4c",commonName: "api.example.com",@@ -53,7 +53,7 @@ const alertContext = (overrides: Partial<TAlertContext> = {}): TAlertContext =>const buildProvider = (opts?: {application?: { id: string; name: string; projectId: string; orgId: string };- certificates?: TApplicationAlertCertificate[];+ certificates?: TAlertCertificate[];onFindExpiring?: (args: Record<string, unknown>) => void;onFindByIds?: (args: Record<string, unknown>) => void;onFindNames?: (ids: string[], orgId: string) => void;@@ -104,7 +104,7 @@ const buildProvider = (opts?: {getPlan: async () => ({ pkiEnterpriseAlerting: opts?.pkiEnterpriseAlerting ?? false })};const provider = certManagerAlertProviderFactory({- certManagerApplicationAlertDAL: dal,+ certManagerCertificateAlertDAL: dal,permissionService,licenseService,certManagerProjectResolver: {@@ -131,12 +131,12 @@ describe("cert manager alert provider", () => {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", () => {+ test("issuance, renewal and revocation are sourced 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([+ expect(eventTriggered.map((event) => [event.key, event.sourceEvent])).toEqual([[ISSUANCE_EVENT,{ resourceType: "cert-manager.application", eventKey: "cert-manager.application.certificate.issuance" }@@ -326,13 +326,13 @@ describe("cert manager alert provider", () => {});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"+ "aren't bound to a single application");await expect(provider.assertResourceInScope({ orgId: "org-1", resourceId: APPLICATION_ID })).rejects.toThrow(- "can't be bound to one"+ "aren't bound to a single application");await expect(provider.resolveProjectId?.({ orgId: "org-1", resourceId: APPLICATION_ID })).rejects.toThrow(- "can't be bound to one"+ "aren't bound to a single application");});@@ -451,17 +451,6 @@ describe("cert manager 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();- });-test("creating or editing an alert with no application requires a project admin, reading and deleting only PKI alert access", async () => {const create = { action: AlertPermissionAction.Create, orgId: "org-1", projectId: "proj-1", actor };const alertRules = [diff --git a/backend/src/services/alert/providers/cert-manager-alert-provider.ts b/backend/src/services/alert/providers/cert-manager-alert-provider.tsindex 4c9e3d438e..2351f6c3be 100644--- a/backend/src/services/alert/providers/cert-manager-alert-provider.ts+++ b/backend/src/services/alert/providers/cert-manager-alert-provider.ts@@ -9,7 +9,7 @@ import { TCertManagerProjectResolverFactory } from "@app/services/cert-manager-iimport {CERT_MANAGER_APPLICATION_RESOURCE_TYPE,CERT_MANAGER_RESOURCE_TYPE,- CertificateAlertEvent,+ CertificateApplicationAlertEvent,CertificateManagerAlertEvent} from "@app/services/certificate/certificate-alert-events";import { PkiAlertScope } from "@app/services/telemetry/telemetry-types";@@ -40,12 +40,10 @@ import {CertificateAlertKind,expiryDedupWindowHours,ExpiryFieldsSchema,+ getScopeWideAlertWebhookSource,resolveCertManagerProjectId} from "./cert-manager-alert-fns";-import {- TApplicationAlertCertificate,- TCertManagerApplicationAlertDALFactory-} from "./cert-manager-application-alert-dal";+import { TAlertCertificate, TCertManagerCertificateAlertDALFactory } from "./cert-manager-certificate-alert-dal";const MAX_CERTIFICATE_ALERT_FILTER_IDS = 100;@@ -56,10 +54,10 @@ const ALERT_KIND_BY_EVENT: Record<CertificateManagerAlertEvent, CertificateAlert[CertificateManagerAlertEvent.Revocation]: CertificateAlertKind.Revocation};-const RELAYED_EVENTS: [CertificateManagerAlertEvent, CertificateAlertEvent][] = [- [CertificateManagerAlertEvent.Issuance, CertificateAlertEvent.Issuance],- [CertificateManagerAlertEvent.Renewal, CertificateAlertEvent.Renewal],- [CertificateManagerAlertEvent.Revocation, CertificateAlertEvent.Revocation]+const EVENTS_SOURCED_FROM_APPLICATION_EVENTS: [CertificateManagerAlertEvent, CertificateApplicationAlertEvent][] = [+ [CertificateManagerAlertEvent.Issuance, CertificateApplicationAlertEvent.Issuance],+ [CertificateManagerAlertEvent.Renewal, CertificateApplicationAlertEvent.Renewal],+ [CertificateManagerAlertEvent.Revocation, CertificateApplicationAlertEvent.Revocation]];const filterIdsSchema = (field: string, noun: string) =>@@ -110,33 +108,31 @@ const parseFilters = (condition: unknown) => {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."+ "Certificate Manager alerts aren't bound to a single application. Remove resourceId, and use applicationIds to narrow the alert to specific applications.");-const getWebhookSource = ({ alertId }: { alertId: string }) => `/alerts/${alertId}`;-export type TCertManagerAlertProviderDep = {- certManagerApplicationAlertDAL: TCertManagerApplicationAlertDALFactory;+ certManagerCertificateAlertDAL: TCertManagerCertificateAlertDALFactory;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;certManagerProjectResolver: Pick<TCertManagerProjectResolverFactory, "getActiveProjectId">;};export const certManagerAlertProviderFactory = ({- certManagerApplicationAlertDAL,+ certManagerCertificateAlertDAL,permissionService,licenseService,certManagerProjectResolver-}: TCertManagerAlertProviderDep): IScheduledAlertProvider<TApplicationAlertCertificate> &- IEventAlertProvider<TApplicationAlertCertificate> => {+}: TCertManagerAlertProviderDep): IScheduledAlertProvider<TAlertCertificate> &+ IEventAlertProvider<TAlertCertificate> => {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[]> => {+ const findScheduledTargets = async (input: TFindScheduledTargetsInput): Promise<TAlertCertificate[]> => {if (!input.projectId || input.resourceId || !input.alreadyAlerted?.channelIds.length) return [];const { alertBefore, applicationIds, profileIds, sources } = ExpirationConditionSchema.parse(input.condition);- return certManagerApplicationAlertDAL.findExpiringCertificates({+ return certManagerCertificateAlertDAL.findExpiringCertificates({projectId: input.projectId,applicationIds,profileIds,@@ -148,11 +144,11 @@ export const certManagerAlertProviderFactory = ({});};- const findEventTargets = async (input: TFindEventTargetsInput): Promise<TApplicationAlertCertificate[]> => {+ const findEventTargets = async (input: TFindEventTargetsInput): Promise<TAlertCertificate[]> => {if (!input.projectId || input.resourceId) return [];const condition = EventConditionSchema.parse(input.condition);- return certManagerApplicationAlertDAL.findCertificatesByIds({+ return certManagerCertificateAlertDAL.findCertificatesByIds({projectId: input.projectId,applicationIds: condition?.applicationIds,profileIds: condition?.profileIds,@@ -161,13 +157,13 @@ export const certManagerAlertProviderFactory = ({});};- const buildPayload = (alert: TAlertContext, targets: TApplicationAlertCertificate[], viewUrl: string) =>+ const buildPayload = (alert: TAlertContext, targets: TAlertCertificate[], viewUrl: string) =>buildCertificateAlertPayload({alert,targets,viewUrl,kind: ALERT_KIND_BY_EVENT[alert.eventType as CertificateManagerAlertEvent],- webhookSource: getWebhookSource({ alertId: alert.id }),+ webhookSource: getScopeWideAlertWebhookSource({ alertId: alert.id }),resourceOwnerKind: "Certificate Manager",applicationName: null});@@ -208,7 +204,7 @@ export const certManagerAlertProviderFactory = ({await assertCertManagerAdminAlertPermission(permissionService,{ action, projectId, actor },- "Certificate Manager alerts send certificate details from every application, so only Certificate Manager admins can create or edit them. Create the alert on an application instead."+ "Certificate Manager alerts can send details of certificates from any application, so only Certificate Manager admins can create or edit them. Create the alert on an application instead.");};@@ -228,10 +224,10 @@ export const certManagerAlertProviderFactory = ({const [foundApplicationIds, foundProfileIds]: string[][] = await Promise.all([addedApplicationIds.length- ? certManagerApplicationAlertDAL.findProjectApplicationIds(input.projectId, addedApplicationIds)+ ? certManagerCertificateAlertDAL.findProjectApplicationIds(input.projectId, addedApplicationIds): [],addedProfileIds.length- ? certManagerApplicationAlertDAL.findProjectProfileIds(input.projectId, addedProfileIds)+ ? certManagerCertificateAlertDAL.findProjectProfileIds(input.projectId, addedProfileIds): []]);@@ -265,8 +261,8 @@ export const certManagerAlertProviderFactory = ({const profileIds = [...new Set(filtersByAlert.flatMap((filters) => filters.profileIds ?? []))];const [applications, profiles] = await Promise.all([- certManagerApplicationAlertDAL.findApplicationNamesByIds(applicationIds, orgId),- projectId ? certManagerApplicationAlertDAL.findProfileNamesByIds(projectId, profileIds) : []+ certManagerCertificateAlertDAL.findApplicationNamesByIds(applicationIds, orgId),+ projectId ? certManagerCertificateAlertDAL.findProfileNamesByIds(projectId, profileIds) : []]);const nameById = new Map([...applications, ...profiles].map((entry) => [entry.id.toLowerCase(), entry.name]));@@ -289,11 +285,11 @@ export const certManagerAlertProviderFactory = ({triggerType: AlertTriggerType.Scheduled,conditionSchema: ExpirationConditionSchema},- ...RELAYED_EVENTS.map(([key, sourceEventKey]) => ({+ ...EVENTS_SOURCED_FROM_APPLICATION_EVENTS.map(([key, sourceEventKey]) => ({key,triggerType: AlertTriggerType.Event,conditionSchema: EventConditionSchema,- relayedFrom: { resourceType: CERT_MANAGER_APPLICATION_RESOURCE_TYPE, eventKey: sourceEventKey }+ sourceEvent: { resourceType: CERT_MANAGER_APPLICATION_RESOURCE_TYPE, eventKey: sourceEventKey }}))],findScheduledTargets,@@ -310,7 +306,7 @@ export const certManagerAlertProviderFactory = ({recipientPolicy: { atOrgScope: true, allowEmailAddresses: true },includeLastRun: true,getAuditEvent,- getWebhookSource,+ getWebhookSource: getScopeWideAlertWebhookSource,getFilters,resolveProjectId: async ({ orgId, resourceId }) => {assertNoResource(resourceId);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 653864ed68..62162ec21b 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@@ -5,11 +5,11 @@ import { PkiAlertScope, PostHogEventTypes } from "@app/services/telemetry/telemeimport { AlertChannelType } from "../alert-channel-types";import { AlertAuditAction, AlertPermissionAction, AlertTelemetryAction, TAlertContext } from "../alert-types";-import { TApplicationAlertCertificate } from "./cert-manager-application-alert-dal";import {certManagerApplicationAlertProviderFactory,TCertManagerApplicationAlertProviderDep} from "./cert-manager-application-alert-provider";+import { TAlertCertificate } from "./cert-manager-certificate-alert-dal";vi.mock("@app/lib/config/env", () => ({getConfig: () => ({ SITE_URL: "https://app.infisical.com" })@@ -24,7 +24,7 @@ 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 => ({+const sampleCertificate = (overrides: Partial<TAlertCertificate> = {}): TAlertCertificate => ({id: "cert-1",serialNumber: "105d3b4c",commonName: "api.example.com",@@ -55,7 +55,7 @@ const alertContext = (overrides: Partial<TAlertContext> = {}): TAlertContext =>const buildProvider = (opts?: {application?: { id: string; name: string; projectId: string; orgId: string };- certificates?: TApplicationAlertCertificate[];+ certificates?: TAlertCertificate[];onFindExpiring?: (args: Record<string, unknown>) => void;onFindByIds?: (args: Record<string, unknown>) => void;onFindNames?: (ids: string[], orgId: string) => void;@@ -94,7 +94,7 @@ const buildProvider = (opts?: {getPlan: async () => ({ pkiEnterpriseAlerting: opts?.pkiEnterpriseAlerting ?? false })};const provider = certManagerApplicationAlertProviderFactory({- certManagerApplicationAlertDAL: dal,+ certManagerCertificateAlertDAL: dal,permissionService,licenseService} as unknown as TCertManagerApplicationAlertProviderDep);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 64943111dc..a0d58fef54 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@@ -10,7 +10,7 @@ import { getConfig } from "@app/lib/config/env";import { BadRequestError, NotFoundError } from "@app/lib/errors";import {CERT_MANAGER_APPLICATION_RESOURCE_TYPE,- CertificateAlertEvent+ CertificateApplicationAlertEvent} from "@app/services/certificate/certificate-alert-events";import { PkiAlertScope } from "@app/services/telemetry/telemetry-types";@@ -38,16 +38,13 @@ import {expiryDedupWindowHours,ExpiryFieldsSchema} from "./cert-manager-alert-fns";-import {- TApplicationAlertCertificate,- TCertManagerApplicationAlertDALFactory-} from "./cert-manager-application-alert-dal";--const ALERT_KIND_BY_EVENT: Record<CertificateAlertEvent, CertificateAlertKind> = {- [CertificateAlertEvent.Expiry]: CertificateAlertKind.Expiry,- [CertificateAlertEvent.Issuance]: CertificateAlertKind.Issuance,- [CertificateAlertEvent.Renewal]: CertificateAlertKind.Renewal,- [CertificateAlertEvent.Revocation]: CertificateAlertKind.Revocation+import { TAlertCertificate, TCertManagerCertificateAlertDALFactory } from "./cert-manager-certificate-alert-dal";++const ALERT_KIND_BY_EVENT: Record<CertificateApplicationAlertEvent, CertificateAlertKind> = {+ [CertificateApplicationAlertEvent.Expiry]: CertificateAlertKind.Expiry,+ [CertificateApplicationAlertEvent.Issuance]: CertificateAlertKind.Issuance,+ [CertificateApplicationAlertEvent.Renewal]: CertificateAlertKind.Renewal,+ [CertificateApplicationAlertEvent.Revocation]: CertificateAlertKind.Revocation};const ExpirationConditionSchema = ExpiryFieldsSchema.strict();@@ -61,30 +58,30 @@ const assertValidApplicationId = (applicationId: string) => {};export type TCertManagerApplicationAlertProviderDep = {- certManagerApplicationAlertDAL: TCertManagerApplicationAlertDALFactory;+ certManagerCertificateAlertDAL: TCertManagerCertificateAlertDALFactory;permissionService: Pick<TPermissionServiceFactory, "getResourcePermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;};export const certManagerApplicationAlertProviderFactory = ({- certManagerApplicationAlertDAL,+ certManagerCertificateAlertDAL,permissionService,licenseService-}: TCertManagerApplicationAlertProviderDep): IScheduledAlertProvider<TApplicationAlertCertificate> &- IEventAlertProvider<TApplicationAlertCertificate> => {+}: TCertManagerApplicationAlertProviderDep): IScheduledAlertProvider<TAlertCertificate> &+ IEventAlertProvider<TAlertCertificate> => {const buildViewUrl = async (alert: TAlertContext): Promise<string> => {const base = `${getConfig().SITE_URL}/organizations/${alert.orgId}/projects/cert-manager/${alert.projectId}`;const application = alert.resourceId- ? await certManagerApplicationAlertDAL.findApplicationById(alert.resourceId)+ ? await certManagerCertificateAlertDAL.findApplicationById(alert.resourceId): undefined;return application ? `${base}/applications/${encodeURIComponent(application.name)}` : `${base}/applications`;};- const findScheduledTargets = async (input: TFindScheduledTargetsInput): Promise<TApplicationAlertCertificate[]> => {+ const findScheduledTargets = async (input: TFindScheduledTargetsInput): Promise<TAlertCertificate[]> => {if (!input.projectId || !input.resourceId || !input.alreadyAlerted?.channelIds.length) return [];const { alertBefore } = ExpirationConditionSchema.parse(input.condition);- return certManagerApplicationAlertDAL.findExpiringCertificates({+ return certManagerCertificateAlertDAL.findExpiringCertificates({projectId: input.projectId,applicationId: input.resourceId,alertBeforeInterval: `${durationToDays(alertBefore)} days`,@@ -94,11 +91,11 @@ export const certManagerApplicationAlertProviderFactory = ({});};- const findEventTargets = async (input: TFindEventTargetsInput): Promise<TApplicationAlertCertificate[]> => {+ const findEventTargets = async (input: TFindEventTargetsInput): Promise<TAlertCertificate[]> => {if (!input.projectId || !input.resourceId) return [];EventConditionSchema.parse(input.condition);- return certManagerApplicationAlertDAL.findCertificatesByIds({+ return certManagerCertificateAlertDAL.findCertificatesByIds({projectId: input.projectId,applicationId: input.resourceId,certificateIds: input.targetIds@@ -145,16 +142,16 @@ export const certManagerApplicationAlertProviderFactory = ({return buildPkiAlertTelemetryEvent(action,{ orgId, projectId, applicationId: resourceId, alertScope: PkiAlertScope.Application },- CERTIFICATE_ALERT_KIND_TELEMETRY_TYPES[ALERT_KIND_BY_EVENT[eventType as CertificateAlertEvent]]+ CERTIFICATE_ALERT_KIND_TELEMETRY_TYPES[ALERT_KIND_BY_EVENT[eventType as CertificateApplicationAlertEvent]]);};- const buildPayload = (alert: TAlertContext, targets: TApplicationAlertCertificate[], viewUrl: string) =>+ const buildPayload = (alert: TAlertContext, targets: TAlertCertificate[], viewUrl: string) =>buildCertificateAlertPayload({alert,targets,viewUrl,- kind: ALERT_KIND_BY_EVENT[alert.eventType as CertificateAlertEvent],+ kind: ALERT_KIND_BY_EVENT[alert.eventType as CertificateApplicationAlertEvent],webhookSource: getWebhookSource({ alertId: alert.id, resourceId: alert.resourceId }),resourceOwnerKind: "Application",applicationName: targets[0]?.applicationName ?? null@@ -193,7 +190,7 @@ export const certManagerApplicationAlertProviderFactory = ({if (!input.resourceId) return;assertValidApplicationId(input.resourceId);- const application = await certManagerApplicationAlertDAL.findApplicationById(input.resourceId);+ const application = await certManagerCertificateAlertDAL.findApplicationById(input.resourceId);if (!application || application.orgId !== input.orgId || application.projectId !== input.projectId) {throw new NotFoundError({message: `Application with ID '${input.resourceId}' not found in Certificate Manager`@@ -206,7 +203,7 @@ export const certManagerApplicationAlertProviderFactory = ({throw new BadRequestError({ message: "Application alerts require an application ID" });}assertValidApplicationId(resourceId);- const application = await certManagerApplicationAlertDAL.findApplicationById(resourceId);+ const application = await certManagerCertificateAlertDAL.findApplicationById(resourceId);if (!application || application.orgId !== orgId) {throw new NotFoundError({ message: `Application with ID '${resourceId}' not found` });}@@ -217,17 +214,19 @@ export const certManagerApplicationAlertProviderFactory = ({resourceType: CERT_MANAGER_APPLICATION_RESOURCE_TYPE,events: [{- key: CertificateAlertEvent.Expiry,+ key: CertificateApplicationAlertEvent.Expiry,triggerType: AlertTriggerType.Scheduled,conditionSchema: ExpirationConditionSchema},- ...[CertificateAlertEvent.Issuance, CertificateAlertEvent.Renewal, CertificateAlertEvent.Revocation].map(- (key) => ({- key,- triggerType: AlertTriggerType.Event,- conditionSchema: EventConditionSchema- })- )+ ...[+ CertificateApplicationAlertEvent.Issuance,+ CertificateApplicationAlertEvent.Renewal,+ CertificateApplicationAlertEvent.Revocation+ ].map((key) => ({+ key,+ triggerType: AlertTriggerType.Event,+ conditionSchema: EventConditionSchema+ }))],findScheduledTargets,findEventTargets,@@ -246,7 +245,7 @@ export const certManagerApplicationAlertProviderFactory = ({resolveProjectId,getResourceNames: async ({ orgId, resourceIds }) =>new Map(- (await certManagerApplicationAlertDAL.findApplicationNamesByIds(resourceIds, orgId)).map((app) => [+ (await certManagerCertificateAlertDAL.findApplicationNamesByIds(resourceIds, orgId)).map((app) => [app.id,app.name])diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-dal.test.ts b/backend/src/services/alert/providers/cert-manager-certificate-alert-dal.test.tssimilarity index 98%rename from backend/src/services/alert/providers/cert-manager-application-alert-dal.test.tsrename to backend/src/services/alert/providers/cert-manager-certificate-alert-dal.test.tsindex aa694fe0ce..26a81980d7 100644--- a/backend/src/services/alert/providers/cert-manager-application-alert-dal.test.ts+++ b/backend/src/services/alert/providers/cert-manager-certificate-alert-dal.test.ts@@ -3,7 +3,7 @@ import knex, { Knex } from "knex";import { TDbClient } from "@app/db";import { CertificateSource } from "@app/ee/services/pki-discovery/pki-discovery-types";-import { certManagerApplicationAlertDALFactory } from "./cert-manager-application-alert-dal";+import { certManagerCertificateAlertDALFactory } from "./cert-manager-certificate-alert-dal";const PROJECT_ID = "3f2d7a4e-1b6c-4d8e-9a0f-5c7b2e1d4a6b";const APPLICATION_ID = "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90";@@ -24,7 +24,7 @@ const buildDAL = (firstQueryRows: unknown[] = []) => {}) as unknown as Knex;const db = Object.assign(reader, { replicaNode: () => reader }) as unknown as TDbClient;- return { dal: certManagerApplicationAlertDALFactory(db), queries };+ return { dal: certManagerCertificateAlertDALFactory(db), queries };};describe("cert manager certificate alert DAL", () => {diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts b/backend/src/services/alert/providers/cert-manager-certificate-alert-dal.tssimilarity index 61%rename from backend/src/services/alert/providers/cert-manager-application-alert-dal.tsrename to backend/src/services/alert/providers/cert-manager-certificate-alert-dal.tsindex 9d8c6a5563..e34b6b6e1b 100644--- a/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts+++ b/backend/src/services/alert/providers/cert-manager-certificate-alert-dal.ts@@ -4,12 +4,12 @@ import { TDbClient } from "@app/db";import { TableName } from "@app/db/schemas";import { CertificateSource } from "@app/ee/services/pki-discovery/pki-discovery-types";import { DatabaseError } from "@app/lib/errors";-import { AlertRunStatus, TAlreadyAlertedFilter } from "@app/services/alert/alert-types";-import { CertStatus } from "@app/services/certificate/certificate-types";-export type TCertManagerApplicationAlertDALFactory = ReturnType<typeof certManagerApplicationAlertDALFactory>;+import { scanExpiringCertificates, TExpiringCertificatesScan } from "./cert-manager-expiring-certificates-fns";-export type TApplicationAlertCertificate = {+export type TCertManagerCertificateAlertDALFactory = ReturnType<typeof certManagerCertificateAlertDALFactory>;++export type TAlertCertificate = {id: string;serialNumber: string;commonName: string;@@ -25,13 +25,6 @@ export type TApplicationAlertCertificate = {applicationName: string | null;};-type TExpiryWindow = {- alertBeforeInterval: string;- leadInterval: string;- asOf: Date;- alreadyAlerted: TAlreadyAlertedFilter;-};-type TCertificateScope = {projectId: string;applicationId?: string | null;@@ -40,9 +33,7 @@ type TCertificateScope = {sources?: CertificateSource[];};-const MAX_EXPIRING_CERTIFICATES_PER_RUN = 1000;--export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {+export const certManagerCertificateAlertDALFactory = (db: TDbClient) => {const $selectCertificates = (reader: Knex,{ projectId, applicationId, applicationIds, profileIds, sources }: TCertificateScope@@ -79,69 +70,16 @@ export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {);const findExpiringCertificates = async (- scope: TCertificateScope & TExpiryWindow,+ scope: TCertificateScope & TExpiringCertificatesScan,tx?: Knex- ): Promise<TApplicationAlertCertificate[]> => {+ ): Promise<TAlertCertificate[]> => {try {const reader = tx || db.replicaNode();- const { alertId, channelIds, since } = scope.alreadyAlerted;-- const deliveredOnEveryChannel = reader(`${TableName.AlertHistory} as deliveredHist`)- .join(`${TableName.AlertHistoryTarget} as deliveredTgt`, "deliveredHist.id", "deliveredTgt.alertHistoryId")- .where("deliveredHist.alertId", alertId)- .where("deliveredTgt.status", AlertRunStatus.SUCCESS)- .whereIn("deliveredTgt.channelId", channelIds)- .groupBy("deliveredTgt.targetId")- .havingRaw(`count(distinct "deliveredTgt"."channelId") >= ?`, [channelIds.length]);-- const notFullyNotified = (await $selectCertificates(reader, scope)- .whereNull(`${TableName.Certificate}.renewedByCertificateId`)- .whereNot(`${TableName.Certificate}.status`, CertStatus.REVOKED)- .whereRaw(`"${TableName.Certificate}"."notAfter" > ?::timestamptz`, [scope.asOf])- .whereRaw(`"${TableName.Certificate}"."notAfter" <= ?::timestamptz + ?::interval + ?::interval`, [- scope.asOf,- scope.alertBeforeInterval,- scope.leadInterval- ])- .whereRaw(`"${TableName.Certificate}".id::text not in (?)`, [- deliveredOnEveryChannel.clone().select("deliveredTgt.targetId")- ])- .orderBy(`${TableName.Certificate}.notAfter`, "asc")- .limit(MAX_EXPIRING_CERTIFICATES_PER_RUN)) as TApplicationAlertCertificate[];- if (notFullyNotified.length >= MAX_EXPIRING_CERTIFICATES_PER_RUN) return notFullyNotified;-- const deliveredChannelCountSince = reader(`${TableName.AlertHistory} as hist`)- .join(`${TableName.AlertHistoryTarget} as tgt`, "hist.id", "tgt.alertHistoryId")- .where("hist.alertId", alertId)- .where("hist.triggeredAt", ">=", since)- .where("tgt.status", AlertRunStatus.SUCCESS)- .whereIn("tgt.channelId", channelIds)- .whereRaw(`"tgt"."targetId" = "${TableName.Certificate}".id::text`)- .countDistinct("tgt.channelId");- const leastRecentlyNotified = (await $selectCertificates(reader, scope)- .joinRaw(- `inner join (?) as "lastDelivered" on "lastDelivered"."targetId" = "${TableName.Certificate}".id::text`,- [- deliveredOnEveryChannel- .clone()- .select("deliveredTgt.targetId")- .max("deliveredHist.triggeredAt as lastDeliveredAt")- ]- )- .whereNull(`${TableName.Certificate}.renewedByCertificateId`)- .whereNot(`${TableName.Certificate}.status`, CertStatus.REVOKED)- .whereRaw(`"${TableName.Certificate}"."notAfter" > ?::timestamptz`, [scope.asOf])- .whereRaw(`"${TableName.Certificate}"."notAfter" <= ?::timestamptz + ?::interval + ?::interval`, [- scope.asOf,- scope.alertBeforeInterval,- scope.leadInterval- ])- .whereRaw("(?) < ?", [deliveredChannelCountSince, channelIds.length])- .orderBy("lastDelivered.lastDeliveredAt", "asc")- .orderBy(`${TableName.Certificate}.notAfter`, "asc")- .limit(MAX_EXPIRING_CERTIFICATES_PER_RUN - notFullyNotified.length)) as TApplicationAlertCertificate[];-- return [...notFullyNotified, ...leastRecentlyNotified];+ return await scanExpiringCertificates<TAlertCertificate>(+ reader,+ () => $selectCertificates(reader, scope).whereNull(`${TableName.Certificate}.renewedByCertificateId`),+ scope+ );} catch (error) {throw new DatabaseError({ error, name: "FindExpiringCertificates" });}@@ -150,12 +88,12 @@ export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {const findCertificatesByIds = async (scope: TCertificateScope & { certificateIds: string[] },tx?: Knex- ): Promise<TApplicationAlertCertificate[]> => {+ ): Promise<TAlertCertificate[]> => {try {const certificates = (await $selectCertificates(tx || db, scope).whereIn(`${TableName.Certificate}.id`,scope.certificateIds- )) as TApplicationAlertCertificate[];+ )) as TAlertCertificate[];return certificates;} catch (error) {diff --git a/backend/src/services/alert/providers/cert-manager-expiring-certificates-fns.ts b/backend/src/services/alert/providers/cert-manager-expiring-certificates-fns.tsnew file mode 100644index 0000000000..08673ddc68--- /dev/null+++ b/backend/src/services/alert/providers/cert-manager-expiring-certificates-fns.ts@@ -0,0 +1,70 @@+import { Knex } from "knex";++import { TableName } from "@app/db/schemas";+import { AlertRunStatus, TAlreadyAlertedFilter } from "@app/services/alert/alert-types";+import { CertStatus } from "@app/services/certificate/certificate-types";++export const MAX_EXPIRING_CERTIFICATES_PER_RUN = 1000;++export type TExpiringCertificatesScan = {+ alertBeforeInterval: string;+ leadInterval: string;+ asOf: Date;+ alreadyAlerted: TAlreadyAlertedFilter;+};++export const scanExpiringCertificates = async <T>(+ reader: Knex,+ selectCertificates: () => Knex.QueryBuilder,+ { alertBeforeInterval, leadInterval, asOf, alreadyAlerted }: TExpiringCertificatesScan+): Promise<T[]> => {+ const { alertId, channelIds, since } = alreadyAlerted;++ const selectDue = () =>+ selectCertificates()+ .whereNot(`${TableName.Certificate}.status`, CertStatus.REVOKED)+ .whereRaw(`"${TableName.Certificate}"."notAfter" > ?::timestamptz`, [asOf])+ .whereRaw(`"${TableName.Certificate}"."notAfter" <= ?::timestamptz + ?::interval + ?::interval`, [+ asOf,+ alertBeforeInterval,+ leadInterval+ ]);++ const deliveredOnEveryChannel = reader(`${TableName.AlertHistory} as deliveredHist`)+ .join(`${TableName.AlertHistoryTarget} as deliveredTgt`, "deliveredHist.id", "deliveredTgt.alertHistoryId")+ .where("deliveredHist.alertId", alertId)+ .where("deliveredTgt.status", AlertRunStatus.SUCCESS)+ .whereIn("deliveredTgt.channelId", channelIds)+ .groupBy("deliveredTgt.targetId")+ .havingRaw(`count(distinct "deliveredTgt"."channelId") >= ?`, [channelIds.length]);++ const notFullyNotified = (await selectDue()+ .whereRaw(`"${TableName.Certificate}".id::text not in (?)`, [+ deliveredOnEveryChannel.clone().select("deliveredTgt.targetId")+ ])+ .orderBy(`${TableName.Certificate}.notAfter`, "asc")+ .limit(MAX_EXPIRING_CERTIFICATES_PER_RUN)) as T[];+ if (notFullyNotified.length >= MAX_EXPIRING_CERTIFICATES_PER_RUN) return notFullyNotified;++ const deliveredChannelCountSince = reader(`${TableName.AlertHistory} as hist`)+ .join(`${TableName.AlertHistoryTarget} as tgt`, "hist.id", "tgt.alertHistoryId")+ .where("hist.alertId", alertId)+ .where("hist.triggeredAt", ">=", since)+ .where("tgt.status", AlertRunStatus.SUCCESS)+ .whereIn("tgt.channelId", channelIds)+ .whereRaw(`"tgt"."targetId" = "${TableName.Certificate}".id::text`)+ .countDistinct("tgt.channelId");+ const leastRecentlyNotified = (await selectDue()+ .joinRaw(`inner join (?) as "lastDelivered" on "lastDelivered"."targetId" = "${TableName.Certificate}".id::text`, [+ deliveredOnEveryChannel+ .clone()+ .select("deliveredTgt.targetId")+ .max("deliveredHist.triggeredAt as lastDeliveredAt")+ ])+ .whereRaw("(?) < ?", [deliveredChannelCountSince, channelIds.length])+ .orderBy("lastDelivered.lastDeliveredAt", "asc")+ .orderBy(`${TableName.Certificate}.notAfter`, "asc")+ .limit(MAX_EXPIRING_CERTIFICATES_PER_RUN - notFullyNotified.length)) as T[];++ return [...notFullyNotified, ...leastRecentlyNotified];+};diff --git a/backend/src/services/alert/providers/cert-manager-signer-alert-dal.ts b/backend/src/services/alert/providers/cert-manager-signer-alert-dal.tsindex 184322415c..9fe2ed3c44 100644--- a/backend/src/services/alert/providers/cert-manager-signer-alert-dal.ts+++ b/backend/src/services/alert/providers/cert-manager-signer-alert-dal.ts@@ -3,10 +3,10 @@ import { Knex } from "knex";import { TDbClient } from "@app/db";import { TableName } from "@app/db/schemas";import { DatabaseError } from "@app/lib/errors";-import { AlertRunStatus, TAlreadyAlertedFilter } from "@app/services/alert/alert-types";-import { CertStatus } from "@app/services/certificate/certificate-types";import { SignerStatus } from "@app/services/signer/signer-enums";+import { scanExpiringCertificates, TExpiringCertificatesScan } from "./cert-manager-expiring-certificates-fns";+export type TCertManagerSignerAlertDALFactory = ReturnType<typeof certManagerSignerAlertDALFactory>;export type TSignerAlertCertificate = {@@ -21,8 +21,6 @@ export type TSignerAlertCertificate = {signerNames: string[];};-const MAX_EXPIRING_SIGNER_CERTIFICATES_PER_RUN = 1000;-export const certManagerSignerAlertDALFactory = (db: TDbClient) => {const $selectSignerCertificates = (reader: Knex, projectId: string) =>reader(TableName.Certificate)@@ -58,73 +56,16 @@ export const certManagerSignerAlertDALFactory = (db: TDbClient) => {);const findExpiringSignerCertificates = async (- scope: {- projectId: string;- alertBeforeInterval: string;- leadInterval: string;- asOf: Date;- alreadyAlerted: TAlreadyAlertedFilter;- },+ scope: { projectId: string } & TExpiringCertificatesScan,tx?: Knex): Promise<TSignerAlertCertificate[]> => {try {const reader = tx || db.replicaNode();- const { alertId, channelIds, since } = scope.alreadyAlerted;-- const deliveredOnEveryChannel = reader(`${TableName.AlertHistory} as deliveredHist`)- .join(`${TableName.AlertHistoryTarget} as deliveredTgt`, "deliveredHist.id", "deliveredTgt.alertHistoryId")- .where("deliveredHist.alertId", alertId)- .where("deliveredTgt.status", AlertRunStatus.SUCCESS)- .whereIn("deliveredTgt.channelId", channelIds)- .groupBy("deliveredTgt.targetId")- .havingRaw(`count(distinct "deliveredTgt"."channelId") >= ?`, [channelIds.length]);-- const notFullyNotified = (await $selectSignerCertificates(reader, scope.projectId)- .whereNot(`${TableName.Certificate}.status`, CertStatus.REVOKED)- .whereRaw(`"${TableName.Certificate}"."notAfter" > ?::timestamptz`, [scope.asOf])- .whereRaw(`"${TableName.Certificate}"."notAfter" <= ?::timestamptz + ?::interval + ?::interval`, [- scope.asOf,- scope.alertBeforeInterval,- scope.leadInterval- ])- .whereRaw(`"${TableName.Certificate}".id::text not in (?)`, [- deliveredOnEveryChannel.clone().select("deliveredTgt.targetId")- ])- .orderBy(`${TableName.Certificate}.notAfter`, "asc")- .limit(MAX_EXPIRING_SIGNER_CERTIFICATES_PER_RUN)) as TSignerAlertCertificate[];- if (notFullyNotified.length >= MAX_EXPIRING_SIGNER_CERTIFICATES_PER_RUN) return notFullyNotified;-- const deliveredChannelCountSince = reader(`${TableName.AlertHistory} as hist`)- .join(`${TableName.AlertHistoryTarget} as tgt`, "hist.id", "tgt.alertHistoryId")- .where("hist.alertId", alertId)- .where("hist.triggeredAt", ">=", since)- .where("tgt.status", AlertRunStatus.SUCCESS)- .whereIn("tgt.channelId", channelIds)- .whereRaw(`"tgt"."targetId" = "${TableName.Certificate}".id::text`)- .countDistinct("tgt.channelId");- const leastRecentlyNotified = (await $selectSignerCertificates(reader, scope.projectId)- .joinRaw(- `inner join (?) as "lastDelivered" on "lastDelivered"."targetId" = "${TableName.Certificate}".id::text`,- [- deliveredOnEveryChannel- .clone()- .select("deliveredTgt.targetId")- .max("deliveredHist.triggeredAt as lastDeliveredAt")- ]- )- .whereNot(`${TableName.Certificate}.status`, CertStatus.REVOKED)- .whereRaw(`"${TableName.Certificate}"."notAfter" > ?::timestamptz`, [scope.asOf])- .whereRaw(`"${TableName.Certificate}"."notAfter" <= ?::timestamptz + ?::interval + ?::interval`, [- scope.asOf,- scope.alertBeforeInterval,- scope.leadInterval- ])- .whereRaw("(?) < ?", [deliveredChannelCountSince, channelIds.length])- .orderBy("lastDelivered.lastDeliveredAt", "asc")- .orderBy(`${TableName.Certificate}.notAfter`, "asc")- .limit(MAX_EXPIRING_SIGNER_CERTIFICATES_PER_RUN - notFullyNotified.length)) as TSignerAlertCertificate[];-- return [...notFullyNotified, ...leastRecentlyNotified];+ return await scanExpiringCertificates<TSignerAlertCertificate>(+ reader,+ () => $selectSignerCertificates(reader, scope.projectId),+ scope+ );} catch (error) {throw new DatabaseError({ error, name: "FindExpiringSignerCertificates" });}diff --git a/backend/src/services/alert/providers/cert-manager-signer-alert-provider.test.ts b/backend/src/services/alert/providers/cert-manager-signer-alert-provider.test.tsindex 4666f2c6e3..b084244227 100644--- a/backend/src/services/alert/providers/cert-manager-signer-alert-provider.test.ts+++ b/backend/src/services/alert/providers/cert-manager-signer-alert-provider.test.ts@@ -194,21 +194,23 @@ describe("cert manager signer alert provider", () => {expect(payload.items[0].fields?.[0]).toEqual({ label: "Signers", value: "build-signer, release-signer" });});- test("logs Certificate Manager alert audit events and PKI alert telemetry", () => {+ test("logs its own signer alert audit events and PKI alert telemetry", () => {const provider = buildProvider();const alert = { ...signerAlert, enabled: true, channels: [] } as never;expect(provider.getAuditEvent?.({ action: AlertAuditAction.Create, alert })).toEqual({- type: EventType.CREATE_CERTIFICATE_MANAGER_ALERT,- metadata: {- alertId: "alert-1",- name: "signer-expiry",- eventType: EXPIRY_EVENT,- applications: [],- profiles: [],- sources: []- }+ type: EventType.CREATE_SIGNER_ALERT,+ metadata: { alertId: "alert-1", name: "signer-expiry", eventType: EXPIRY_EVENT }});+ expect(provider.getAuditEvent?.({ action: AlertAuditAction.Delete, alert })?.type).toBe(+ EventType.DELETE_SIGNER_ALERT+ );+ expect(+ provider.getAuditEvent?.({+ action: AlertAuditAction.TestChannel,+ test: { resourceType: RESOURCE_TYPE, alertId: "alert-1", channelType: "email", success: true }+ })+ ).toMatchObject({ type: EventType.TEST_SIGNER_ALERT_CHANNEL, metadata: { alertId: "alert-1", success: true } });expect(provider.getTelemetryEvent?.({action: AlertTelemetryAction.Create,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 8f518b605c..4ca4710883 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,3 +1,4 @@+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 { getConfig } from "@app/lib/config/env";@@ -10,8 +11,10 @@ import { TAlertPayload } from "../alert-channel-types";import { durationToDays, expirySeverity, formatUtcDate, humanizeDays } from "../alert-format-fns";import {ALERT_SCAN_LEAD_INTERVAL,+ AlertAuditAction,AlertTriggerType,IScheduledAlertProvider,+ TAlertAuditInput,TAlertContext,TAlertPermissionInput,TAlertTelemetryInput,@@ -21,13 +24,14 @@ import {assertCertManagerAdminAlertPermission,assertCertManagerAlertChannelTypesAllowed,assertNoAlertResource,- buildCertificateManagerAlertAuditEvent,buildPkiAlertTelemetryEvent,certificateDisplayName,expiryDedupWindowHours,ExpiryFieldsSchema,+ getScopeWideAlertWebhookSource,resolveCertManagerProjectId,- splitAltNames+ splitAltNames,+ toAlertChannelTestAuditMetadata} from "./cert-manager-alert-fns";import { TCertManagerSignerAlertDALFactory, TSignerAlertCertificate } from "./cert-manager-signer-alert-dal";@@ -39,8 +43,6 @@ const assertNoResource = (resourceId?: string | null) =>"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}`;-const formatSigners = (signerNames: string[]) =>`${signerNames.length === 1 ? "signer" : "signers"} ${signerNames.map((name) => `'${name}'`).join(", ")}`;@@ -89,7 +91,7 @@ export const certManagerSignerAlertProviderFactory = ({eventKey: SignerAlertEvent.CertificateExpiry,eventLabel: "Expiration",webhookType: `com.infisical.${SignerAlertEvent.CertificateExpiry}`,- webhookSource: getWebhookSource({ alertId: alert.id }),+ webhookSource: getScopeWideAlertWebhookSource({ alertId: alert.id }),resourceKind: "Signer Certificate",resourceOwnerKind: "Certificate Manager",severity: expirySeverity(targets.map((target) => target.notAfter)),@@ -139,6 +141,16 @@ export const certManagerSignerAlertProviderFactory = ({);};+ const getAuditEvent = (input: TAlertAuditInput): TAuditEvent => {+ if (input.action === AlertAuditAction.TestChannel) {+ return { type: EventType.TEST_SIGNER_ALERT_CHANNEL, metadata: toAlertChannelTestAuditMetadata(input) };+ }+ const metadata = { alertId: input.alert.id, name: input.alert.name, eventType: input.alert.eventType };+ if (input.action === AlertAuditAction.Create) return { type: EventType.CREATE_SIGNER_ALERT, metadata };+ if (input.action === AlertAuditAction.Update) return { type: EventType.UPDATE_SIGNER_ALERT, metadata };+ return { type: EventType.DELETE_SIGNER_ALERT, metadata };+ };+const getTelemetryEvent = ({ action, orgId, projectId }: TAlertTelemetryInput) => {if (!projectId) return undefined;return buildPkiAlertTelemetryEvent(@@ -168,9 +180,8 @@ export const certManagerSignerAlertProviderFactory = ({assertChannelTypesAllowed: (input) => assertCertManagerAlertChannelTypesAllowed(licenseService, input),recipientPolicy: { atOrgScope: true, allowEmailAddresses: true },includeLastRun: true,- getAuditEvent: (input) =>- buildCertificateManagerAlertAuditEvent(input, { applications: [], profiles: [], sources: [] }),- getWebhookSource,+ getAuditEvent,+ getWebhookSource: getScopeWideAlertWebhookSource,getTelemetryEvent,resolveProjectId: async ({ orgId, resourceId }) => {assertNoResource(resourceId);diff --git a/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts b/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.tsindex 3cca1dc8ab..d8f8981f6d 100644--- a/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts+++ b/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts@@ -7,7 +7,7 @@ import { logger } from "@app/lib/logger";import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";import { ActorType } from "@app/services/auth/auth-type";import {- CertificateAlertEvent,+ CertificateApplicationAlertEvent,TCertificateAlertEventEmitter} from "@app/services/certificate/certificate-alert-events";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";@@ -72,7 +72,7 @@ export const digicertRevocationSyncQueueFactory = ({await certificateAlertEventEmitter.notify({certificateId: cert.id,projectId: cert.projectId,- eventType: CertificateAlertEvent.Revocation,+ eventType: CertificateApplicationAlertEvent.Revocation,applicationId: cert.applicationId ?? null});diff --git a/backend/src/services/certificate-v3/certificate-approval-fns.ts b/backend/src/services/certificate-v3/certificate-approval-fns.tsindex 07617738e1..d11ad945d4 100644--- a/backend/src/services/certificate-v3/certificate-approval-fns.ts+++ b/backend/src/services/certificate-v3/certificate-approval-fns.ts@@ -15,7 +15,7 @@ import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/import { logger } from "@app/lib/logger";import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";import {- CertificateAlertEvent,+ CertificateApplicationAlertEvent,TCertificateAlertEventEmitter,TCertificateAlertEventInput} from "@app/services/certificate/certificate-alert-events";@@ -238,7 +238,7 @@ export const certificateApprovalServiceFactory = (} = deps;const $emitIssuanceAlert = (input: Omit<TCertificateAlertEventInput, "eventType">, tx: Knex) =>- certificateAlertEventEmitter.emit({ ...input, eventType: CertificateAlertEvent.Issuance }, tx);+ certificateAlertEventEmitter.emit({ ...input, eventType: CertificateApplicationAlertEvent.Issuance }, tx);const $queueIssuanceAlert = async (certificateId: string, projectId: string, applicationId?: string | null) => {try {diff --git a/backend/src/services/certificate-v3/certificate-renewal-service.ts b/backend/src/services/certificate-v3/certificate-renewal-service.tsindex e73988435c..29c05f253e 100644--- a/backend/src/services/certificate-v3/certificate-renewal-service.ts+++ b/backend/src/services/certificate-v3/certificate-renewal-service.ts@@ -15,7 +15,7 @@ import { logger } from "@app/lib/logger";import { ms } from "@app/lib/ms";import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";import {- CertificateAlertEvent,+ CertificateApplicationAlertEvent,TCertificateAlertEventEmitter} from "@app/services/certificate/certificate-alert-events";import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";@@ -300,7 +300,7 @@ export const certificateRenewalServiceFactory = ({certificateId: newCert.id,projectId: originalCert.projectId,orgId,- eventType: CertificateAlertEvent.Renewal,+ eventType: CertificateApplicationAlertEvent.Renewal,applicationId: originalCert.applicationId ?? null},txdiff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.tsindex b0c3244230..9e9bd45a7e 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts@@ -30,7 +30,7 @@ import {} from "@app/services/approval-policy/cert-request/cert-request-policy-types";import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";import {- CertificateAlertEvent,+ CertificateApplicationAlertEvent,TCertificateAlertEventEmitter,TCertificateAlertEventInput} from "@app/services/certificate/certificate-alert-events";@@ -367,7 +367,7 @@ export const certificateV3ServiceFactory = ({const $quotaDeps = { projectDAL, licenseService, usageCounterDAL, keyStore };const $emitIssuanceAlert = (input: Omit<TCertificateAlertEventInput, "eventType">, tx: Knex) =>- certificateAlertEventEmitter.emit({ ...input, eventType: CertificateAlertEvent.Issuance }, tx);+ certificateAlertEventEmitter.emit({ ...input, eventType: CertificateApplicationAlertEvent.Issuance }, tx);// Called once the certificate row exists, never at the check.const $recordQuotaUsage = async (usage?: { orgId: string; isNewQuotaKey: boolean; isWildcard: boolean }) => {diff --git a/backend/src/services/certificate/certificate-alert-events.test.ts b/backend/src/services/certificate/certificate-alert-events.test.tsindex b2c98d8f97..0bae382ab2 100644--- a/backend/src/services/certificate/certificate-alert-events.test.ts+++ b/backend/src/services/certificate/certificate-alert-events.test.ts@@ -1,7 +1,7 @@import {CERT_MANAGER_APPLICATION_RESOURCE_TYPE,- CertificateAlertEvent,- certificateAlertEventEmitterFactory+ certificateAlertEventEmitterFactory,+ CertificateApplicationAlertEvent} from "./certificate-alert-events";const buildEmitter = () => {@@ -21,13 +21,13 @@ describe("certificate alert event emitter", () => {test("emits one event without a resource for a certificate outside any application", async () => {const { emitter, emitted } = buildEmitter();await emitter.emit(- { certificateId: "cert-1", projectId: "proj-1", eventType: CertificateAlertEvent.Issuance },+ { certificateId: "cert-1", projectId: "proj-1", eventType: CertificateApplicationAlertEvent.Issuance },{} as never);expect(emitted).toEqual([{- eventType: CertificateAlertEvent.Issuance,+ eventType: CertificateApplicationAlertEvent.Issuance,payload: {orgId: "org-1",projectId: "proj-1",@@ -47,13 +47,13 @@ describe("certificate alert event emitter", () => {projectId: "proj-1",orgId: "org-1",applicationId: "app-1",- eventType: CertificateAlertEvent.Revocation+ eventType: CertificateApplicationAlertEvent.Revocation},{} as never);expect(emitted.map((event) => [event.eventType, event.payload.resourceType, event.payload.resourceId])).toEqual([- [CertificateAlertEvent.Revocation, CERT_MANAGER_APPLICATION_RESOURCE_TYPE, "app-1"]+ [CertificateApplicationAlertEvent.Revocation, CERT_MANAGER_APPLICATION_RESOURCE_TYPE, "app-1"]]);});});diff --git a/backend/src/services/certificate/certificate-alert-events.ts b/backend/src/services/certificate/certificate-alert-events.tsindex e7b2d8d6f0..6c06c79de1 100644--- a/backend/src/services/certificate/certificate-alert-events.ts+++ b/backend/src/services/certificate/certificate-alert-events.ts@@ -6,7 +6,7 @@ import { TProjectDALFactory } from "@app/services/project/project-dal";export const CERT_MANAGER_APPLICATION_RESOURCE_TYPE = "cert-manager.application";-export enum CertificateAlertEvent {+export enum CertificateApplicationAlertEvent {Expiry = "cert-manager.application.certificate.expiry",Issuance = "cert-manager.application.certificate.issuance",Renewal = "cert-manager.application.certificate.renewal",@@ -23,14 +23,14 @@ export enum CertificateManagerAlertEvent {}export const getIssuanceAlertEvent = (isRenewal?: boolean) =>- isRenewal ? CertificateAlertEvent.Renewal : CertificateAlertEvent.Issuance;+ isRenewal ? CertificateApplicationAlertEvent.Renewal : CertificateApplicationAlertEvent.Issuance;export type TCertificateAlertEventInput = {certificateId: string;projectId: string;orgId?: string;applicationId?: string | null;- eventType: CertificateAlertEvent;+ eventType: CertificateApplicationAlertEvent;};type TCertificateAlertEventEmitterDep = {diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.tsindex bed0d97adc..d79fa8f7e5 100644--- a/backend/src/services/certificate/certificate-service.ts+++ b/backend/src/services/certificate/certificate-service.ts@@ -22,7 +22,7 @@ import { crypto } from "@app/lib/crypto/cryptography";import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import {- CertificateAlertEvent,+ CertificateApplicationAlertEvent,TCertificateAlertEventEmitter} from "@app/services/certificate/certificate-alert-events";import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";@@ -775,7 +775,7 @@ export const certificateServiceFactory = ({certificateId: revokedCertId,projectId: ca.projectId,orgId: actorOrgId,- eventType: CertificateAlertEvent.Revocation,+ eventType: CertificateApplicationAlertEvent.Revocation,applicationId: revokedCertApplicationId});diff --git a/docs/api-reference/endpoints/alerts/create.mdx b/docs/api-reference/endpoints/alerts/create.mdxnew file mode 100644index 0000000000..b097cc550c--- /dev/null+++ b/docs/api-reference/endpoints/alerts/create.mdx@@ -0,0 +1,4 @@+---+title: "Create alert"+openapi: "POST /api/v1/alerts"+---diff --git a/docs/api-reference/endpoints/alerts/delete.mdx b/docs/api-reference/endpoints/alerts/delete.mdxnew file mode 100644index 0000000000..79cdc7d851--- /dev/null+++ b/docs/api-reference/endpoints/alerts/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete alert"+openapi: "DELETE /api/v1/alerts/{alertId}"+---diff --git a/docs/api-reference/endpoints/alerts/get.mdx b/docs/api-reference/endpoints/alerts/get.mdxnew file mode 100644index 0000000000..1abc74eccc--- /dev/null+++ b/docs/api-reference/endpoints/alerts/get.mdx@@ -0,0 +1,4 @@+---+title: "Get alert"+openapi: "GET /api/v1/alerts/{alertId}"+---diff --git a/docs/api-reference/endpoints/alerts/list.mdx b/docs/api-reference/endpoints/alerts/list.mdxnew file mode 100644index 0000000000..338f0bb629--- /dev/null+++ b/docs/api-reference/endpoints/alerts/list.mdx@@ -0,0 +1,4 @@+---+title: "List alerts"+openapi: "GET /api/v1/alerts"+---diff --git a/docs/api-reference/endpoints/alerts/test-channel.mdx b/docs/api-reference/endpoints/alerts/test-channel.mdxnew file mode 100644index 0000000000..3fe10b34d8--- /dev/null+++ b/docs/api-reference/endpoints/alerts/test-channel.mdx@@ -0,0 +1,4 @@+---+title: "Test alert channel"+openapi: "POST /api/v1/alerts/channels/test"+---diff --git a/docs/api-reference/endpoints/alerts/update.mdx b/docs/api-reference/endpoints/alerts/update.mdxnew file mode 100644index 0000000000..8cb73f6ccb--- /dev/null+++ b/docs/api-reference/endpoints/alerts/update.mdx@@ -0,0 +1,4 @@+---+title: "Update alert"+openapi: "PATCH /api/v1/alerts/{alertId}"+---diff --git a/docs/api-reference/endpoints/pki-alerts/create.mdx b/docs/api-reference/endpoints/pki-alerts/create.mdxdeleted file mode 100644index e339dd425d..0000000000--- a/docs/api-reference/endpoints/pki-alerts/create.mdx+++ /dev/null@@ -1,4 +0,0 @@-----title: "Create"-openapi: "POST /api/v1/cert-manager/alerts"----diff --git a/docs/api-reference/endpoints/pki-alerts/delete.mdx b/docs/api-reference/endpoints/pki-alerts/delete.mdxdeleted file mode 100644index 8cf3b8e40f..0000000000--- a/docs/api-reference/endpoints/pki-alerts/delete.mdx+++ /dev/null@@ -1,4 +0,0 @@-----title: "Delete"-openapi: "DELETE /api/v1/cert-manager/alerts/{alertId}"----diff --git a/docs/api-reference/endpoints/pki-alerts/read.mdx b/docs/api-reference/endpoints/pki-alerts/read.mdxdeleted file mode 100644index b408e17097..0000000000--- a/docs/api-reference/endpoints/pki-alerts/read.mdx+++ /dev/null@@ -1,4 +0,0 @@-----title: "Retrieve"-openapi: "GET /api/v1/cert-manager/alerts/{alertId}"----diff --git a/docs/api-reference/endpoints/pki-alerts/update.mdx b/docs/api-reference/endpoints/pki-alerts/update.mdxdeleted file mode 100644index 8e4dbb574c..0000000000--- a/docs/api-reference/endpoints/pki-alerts/update.mdx+++ /dev/null@@ -1,4 +0,0 @@-----title: "Update"-openapi: "PATCH /api/v1/cert-manager/alerts/{alertId}"----diff --git a/docs/api-reference/endpoints/pki/applications/alerts/create.mdx b/docs/api-reference/endpoints/pki/applications/alerts/create.mdxdeleted file mode 100644index 87829509d9..0000000000--- a/docs/api-reference/endpoints/pki/applications/alerts/create.mdx+++ /dev/null@@ -1,4 +0,0 @@-----title: "Create application alert"-openapi: "POST /api/v1/cert-manager/applications/{applicationId}/alerts"----diff --git a/docs/api-reference/endpoints/pki/applications/alerts/delete.mdx b/docs/api-reference/endpoints/pki/applications/alerts/delete.mdxdeleted file mode 100644index c2e7e46fe2..0000000000--- a/docs/api-reference/endpoints/pki/applications/alerts/delete.mdx+++ /dev/null@@ -1,4 +0,0 @@-----title: "Delete application alert"-openapi: "DELETE /api/v1/cert-manager/applications/{applicationId}/alerts/{alertId}"----diff --git a/docs/api-reference/endpoints/pki/applications/alerts/list.mdx b/docs/api-reference/endpoints/pki/applications/alerts/list.mdxdeleted file mode 100644index bb1f793687..0000000000--- a/docs/api-reference/endpoints/pki/applications/alerts/list.mdx+++ /dev/null@@ -1,4 +0,0 @@-----title: "List application alerts"-openapi: "GET /api/v1/cert-manager/applications/{applicationId}/alerts"----diff --git a/docs/api-reference/endpoints/pki/applications/alerts/update.mdx b/docs/api-reference/endpoints/pki/applications/alerts/update.mdxdeleted file mode 100644index f0f3a55fee..0000000000--- a/docs/api-reference/endpoints/pki/applications/alerts/update.mdx+++ /dev/null@@ -1,4 +0,0 @@-----title: "Update application alert"-openapi: "PATCH /api/v1/cert-manager/applications/{applicationId}/alerts/{alertId}"----diff --git a/docs/docs.json b/docs/docs.jsonindex e330bc42f9..e17d4006da 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -3925,15 +3925,6 @@"api-reference/endpoints/pki/applications/members/remove-identity"]},- {- "group": "Application alerts",- "pages": [- "api-reference/endpoints/pki/applications/alerts/list",- "api-reference/endpoints/pki/applications/alerts/create",- "api-reference/endpoints/pki/applications/alerts/update",- "api-reference/endpoints/pki/applications/alerts/delete"- ]- },{"group": "Enrollment methods","pages": [@@ -3971,12 +3962,14 @@]},{- "group": "Alerting",+ "group": "Alerts","pages": [- "api-reference/endpoints/pki-alerts/create",- "api-reference/endpoints/pki-alerts/read",- "api-reference/endpoints/pki-alerts/update",- "api-reference/endpoints/pki-alerts/delete"+ "api-reference/endpoints/alerts/list",+ "api-reference/endpoints/alerts/create",+ "api-reference/endpoints/alerts/get",+ "api-reference/endpoints/alerts/update",+ "api-reference/endpoints/alerts/delete",+ "api-reference/endpoints/alerts/test-channel"]},{@@ -5071,6 +5064,38 @@"source": "/documentation/platform/pki/est","destination": "/documentation/platform/pki/applications/enrollment-methods/est"},+ {+ "source": "/api-reference/endpoints/pki/applications/alerts/list",+ "destination": "/api-reference/endpoints/alerts/list"+ },+ {+ "source": "/api-reference/endpoints/pki/applications/alerts/create",+ "destination": "/api-reference/endpoints/alerts/create"+ },+ {+ "source": "/api-reference/endpoints/pki/applications/alerts/update",+ "destination": "/api-reference/endpoints/alerts/update"+ },+ {+ "source": "/api-reference/endpoints/pki/applications/alerts/delete",+ "destination": "/api-reference/endpoints/alerts/delete"+ },+ {+ "source": "/api-reference/endpoints/pki-alerts/create",+ "destination": "/api-reference/endpoints/alerts/create"+ },+ {+ "source": "/api-reference/endpoints/pki-alerts/read",+ "destination": "/api-reference/endpoints/alerts/get"+ },+ {+ "source": "/api-reference/endpoints/pki-alerts/update",+ "destination": "/api-reference/endpoints/alerts/update"+ },+ {+ "source": "/api-reference/endpoints/pki-alerts/delete",+ "destination": "/api-reference/endpoints/alerts/delete"+ },{"source": "/documentation/platform/pki/alerting","destination": "/documentation/platform/pki/applications/alerting/overview"diff --git a/docs/documentation/platform/pki/settings/alerts.mdx b/docs/documentation/platform/pki/settings/alerts.mdxindex 51a8914b63..ec4fc424ba 100644--- a/docs/documentation/platform/pki/settings/alerts.mdx+++ b/docs/documentation/platform/pki/settings/alerts.mdx@@ -4,13 +4,13 @@ sidebarTitle: "Alerts"description: "Get notified about certificate events anywhere in Certificate Manager, inside or outside an application."----An alert under **Settings** > **Alerts** covers certificates across Certificate Manager for one event, whether or not they belong to an [Application](/documentation/platform/pki/applications/overview). Without filters, it covers every certificate. Use a Certificate Manager alert when a team needs to hear about certificates across several applications. To alert on a single application, create an [application alert](/documentation/platform/pki/applications/alerting/overview) instead.+An alert under **Settings** > **Alerts** covers certificates across Certificate Manager for one event, whether or not they belong to an [Application](/documentation/platform/pki/applications/overview). Without filters, it covers every certificate. To alert on a single application, create an [application alert](/documentation/platform/pki/applications/alerting/overview) instead.Certificate Manager alerts use the same events and [notification channels](/documentation/platform/pki/applications/alerting/overview#notification-channels) as application alerts. They can also alert on [signer certificate expiration](#signer-certificate-expiration) for **Code Signing**.## Prerequisites-- The Certificate Manager **Admin** role to create or edit an alert, because it sends details of certificates from every application and every signer+- The Certificate Manager **Admin** role to create or edit an alert- For Slack, PagerDuty, and webhook channels, the Enterprise plan. Email channels are available on every plan.- For email alerts, recipients who are organization members, or addresses on one of your organization's [verified email domains](/documentation/platform/email-domain)@@ -27,7 +27,7 @@ Certificate Manager alerts use the same events and [notification channels](/docuSelect the **Alert Type** from the **Certificate Lifecycle** or **Code Signing** group, then enter an **Alert Name** and an optional **Description**. For an expiration alert, enter **Alert Before** as a number and a unit, for example `30d` or `2w`, up to 365 days. Turn on **Repeat daily until expiry** to get a reminder every day. See [how often expiration alerts repeat](/documentation/platform/pki/applications/alerting/overview#faq). Select **Continue**.</Step><Step>- On the **Filters** step, optionally select **Add Filter** to narrow the alert by **Applications**, **Certificate Profiles**, or **Source**. See [which certificates an alert covers](#which-certificates-an-alert-covers). **Matched Certificates** lists the active certificates the alert covers. The list updates as you change filters. Select **Continue**.+ On the **Filters** step, optionally select **Add Filter** to narrow the alert by **Applications**, **Certificate Profiles**, or **Source**. See [which certificates an alert covers](#which-certificates-an-alert-covers). **Matched Certificates** lists the active certificates the alert covers. Select **Continue**.</Step><Step>Select **Add Channel** and choose where to send notifications. You can add up to 10 channels. Select **Continue**.@@ -63,23 +63,110 @@ Only each signer's current certificate counts. When you reissue a signer's certi<Accordion title="What happens to an alert when I delete an application or profile it lists?">The alert keeps the deleted application or profile in its list, and the deleted one matches no certificates. When you edit the alert, the **Filters** step shows it as **Unknown application** or **Unknown profile**, so you can remove it.</Accordion>- <Accordion title="Why did I get two notifications for the same certificate?">- If a certificate is covered by a Certificate Manager alert and an older alert under **Legacy** > **Alerts** in the sidebar, each alert sends its own notification. Older alerts keep running until you delete them. You can also get one notification from a Certificate Manager alert and one from an application alert if both cover the certificate.- </Accordion><Accordion title="What do webhook receivers get from Certificate Manager alerts?">- The [application alert webhook payload](/documentation/platform/pki/applications/alerting/webhook-alerts#webhook-payload-format), with these differences:-- | Field | Certificate Manager alert |- |-------|---------------------------|- | `type` | `com.infisical.cert-manager.certificate.<event>`, for example `com.infisical.cert-manager.certificate.issuance` |- | `subject` | `cert-manager.certificate.<event>`, for example `cert-manager.certificate.issuance` |- | `source` | `/alerts/<alert-id>` |- | `data.alert.resourceType` | `cert-manager`, with no `resourceId` |- | `data.metadata.viewUrl` | Opens the certificate inventory |- | `data.items[].fields` | Includes an entry labelled `Application` when the certificate belongs to an application |- | `data.items[].resource.applicationId` | `null` for a certificate outside an application |-- A **Signer Certificate Expiration** alert has `cert-manager.signer` as its `data.alert.resourceType` and sends `cert-manager.signer.certificate.expiry` as its `subject` (`type` is `com.infisical.cert-manager.signer.certificate.expiry`). It opens **Code Signing** from `data.metadata.viewUrl` and sends one item per certificate. Each item's `fields` are `Signer` (`Signers` when several signers share the certificate), `Serial Number`, `SANs` when the certificate has any, and `Expires`. Its `resource` has `id`, `serialNumber`, `commonName`, `altNames`, `status`, `notBefore`, `notAfter`, `signerIds`, and `signerNames`, with no application, profile, or revocation keys.+ The same [webhook payload format](/documentation/platform/pki/applications/alerting/webhook-alerts#webhook-payload-format) as application alerts. These examples show one alert of each type:++ <CodeGroup>+ ```json Certificate alert+ {+ "specversion": "1.0",+ "type": "com.infisical.cert-manager.certificate.revocation",+ "source": "/alerts/453421e2-2e73-4700-92c8-60ccd3e7073e",+ "id": "8360c717-097a-4592-a2b0-63c494c3b558",+ "time": "2026-10-05T21:37:35.935Z",+ "datacontenttype": "application/json",+ "subject": "cert-manager.certificate.revocation",+ "data": {+ "alert": {+ "id": "453421e2-2e73-4700-92c8-60ccd3e7073e",+ "name": "prod-revocations",+ "resourceType": "cert-manager"+ },+ "items": [+ {+ "id": "4f70e08e-ad7a-4f94-ac16-241126ab88ed",+ "title": "api.example.com",+ "summary": "Certificate 'api.example.com' was revoked in application 'payments-api'",+ "severity": "warning",+ "fields": [+ { "label": "Serial Number", "value": "77c2b1368a7dd4a8442c61d51d20cbdb2060a1e5" },+ { "label": "Profile", "value": "tls-server" },+ { "label": "Application", "value": "payments-api" },+ { "label": "Expires", "value": "November 4, 2026 at 09:37 PM UTC" },+ { "label": "Revocation Reason", "value": "Unspecified" }+ ],+ "resource": {+ "id": "4f70e08e-ad7a-4f94-ac16-241126ab88ed",+ "serialNumber": "77c2b1368a7dd4a8442c61d51d20cbdb2060a1e5",+ "commonName": "api.example.com",+ "altNames": [],+ "status": "revoked",+ "notBefore": "2026-10-05T21:37:28.426Z",+ "notAfter": "2026-11-04T21:37:28.426Z",+ "revokedAt": "2026-10-05T21:37:30.299Z",+ "revocationReason": 0,+ "profileId": "8d04ef1b-67cd-4021-8da4-b3096d11133b",+ "profileName": "tls-server",+ "applicationId": "d6e7232b-ffa5-48bf-9133-4731c6d001a0",+ "applicationName": "payments-api"+ }+ }+ ],+ "metadata": {+ "totalItems": 1,+ "viewUrl": "https://app.infisical.com/organizations/<org-id>/projects/cert-manager/<project-id>/inventory"+ }+ }+ }+ ```++ ```json Signer certificate expiration+ {+ "specversion": "1.0",+ "type": "com.infisical.cert-manager.signer.certificate.expiry",+ "source": "/alerts/9b3c1d2e-5f6a-4b7c-8d9e-0f1a2b3c4d5e",+ "id": "2c4e6a8b-1d3f-4a5c-9e7b-0d2f4a6c8e1b",+ "time": "2026-10-05T00:05:00.000Z",+ "datacontenttype": "application/json",+ "subject": "cert-manager.signer.certificate.expiry",+ "data": {+ "alert": {+ "id": "9b3c1d2e-5f6a-4b7c-8d9e-0f1a2b3c4d5e",+ "name": "signer-expiry",+ "resourceType": "cert-manager.signer"+ },+ "items": [+ {+ "id": "7e1f3a5c-9b2d-4e6f-8a0c-1d3e5f7a9b2c",+ "title": "release signing",+ "summary": "Certificate 'release signing' of signer 'release-signer' expires on October 25, 2026 at 12:00 AM UTC",+ "severity": "warning",+ "fields": [+ { "label": "Signer", "value": "release-signer" },+ { "label": "Serial Number", "value": "0a1b2c3d4e5f60718293a4b5c6d7e8f901234567" },+ { "label": "Expires", "value": "October 25, 2026 at 12:00 AM UTC" }+ ],+ "resource": {+ "id": "7e1f3a5c-9b2d-4e6f-8a0c-1d3e5f7a9b2c",+ "serialNumber": "0a1b2c3d4e5f60718293a4b5c6d7e8f901234567",+ "commonName": "release signing",+ "altNames": [],+ "status": "active",+ "notBefore": "2025-10-25T00:00:00.000Z",+ "notAfter": "2026-10-25T00:00:00.000Z",+ "signerIds": ["3d5f7a9b-2c4e-4f6a-8b0d-1e3f5a7c9e2b"],+ "signerNames": ["release-signer"]+ }+ }+ ],+ "metadata": {+ "totalItems": 1,+ "viewUrl": "https://app.infisical.com/organizations/<org-id>/projects/cert-manager/<project-id>/code-signing"+ }+ }+ }+ ```+ </CodeGroup></Accordion></AccordionGroup>diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.tsindex b8b1eefa80..a75883b7f6 100644--- a/frontend/src/hooks/api/alerts/types.ts+++ b/frontend/src/hooks/api/alerts/types.ts@@ -36,14 +36,21 @@ export enum CertificateAlertResourceType {Signer = "cert-manager.signer"}-export enum CertificateAlertEventType {+export enum CertificateApplicationAlertEventType {Expiry = "cert-manager.application.certificate.expiry",Issuance = "cert-manager.application.certificate.issuance",Renewal = "cert-manager.application.certificate.renewal",- Revocation = "cert-manager.application.certificate.revocation",- SignerCertificateExpiry = "cert-manager.signer.certificate.expiry"+ Revocation = "cert-manager.application.certificate.revocation"}+export enum SignerAlertEventType {+ CertificateExpiry = "cert-manager.signer.certificate.expiry"+}++export type TCertificateAlertEventType =+ | CertificateApplicationAlertEventType+ | SignerAlertEventType;+export enum CertificateManagerAlertEventType {Expiry = "cert-manager.certificate.expiry",Issuance = "cert-manager.certificate.issuance",diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex 26b89f4db5..258ff4d0c7 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -128,6 +128,10 @@ export const eventToNameMap: { [K in EventType]: string } = {[EventType.UPDATE_CERTIFICATE_MANAGER_ALERT]: "Update Certificate Manager alert",[EventType.DELETE_CERTIFICATE_MANAGER_ALERT]: "Delete Certificate Manager alert",[EventType.TEST_CERTIFICATE_MANAGER_ALERT_CHANNEL]: "Test Certificate Manager alert channel",+ [EventType.CREATE_SIGNER_ALERT]: "Create signer alert",+ [EventType.UPDATE_SIGNER_ALERT]: "Update signer alert",+ [EventType.DELETE_SIGNER_ALERT]: "Delete signer alert",+ [EventType.TEST_SIGNER_ALERT_CHANNEL]: "Test signer alert channel",[EventType.CREATE_PKI_COLLECTION]: "Create PKI collection",[EventType.GET_PKI_COLLECTION]: "Get PKI collection",[EventType.UPDATE_PKI_COLLECTION]: "Update PKI collection",diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsxindex f7a29a00bb..e8b7d35b24 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -144,6 +144,10 @@ export enum EventType {UPDATE_CERTIFICATE_MANAGER_ALERT = "update-certificate-manager-alert",DELETE_CERTIFICATE_MANAGER_ALERT = "delete-certificate-manager-alert",TEST_CERTIFICATE_MANAGER_ALERT_CHANNEL = "test-certificate-manager-alert-channel",+ CREATE_SIGNER_ALERT = "create-signer-alert",+ UPDATE_SIGNER_ALERT = "update-signer-alert",+ DELETE_SIGNER_ALERT = "delete-signer-alert",+ TEST_SIGNER_ALERT_CHANNEL = "test-signer-alert-channel",CREATE_PKI_COLLECTION = "create-pki-collection",GET_PKI_COLLECTION = "get-pki-collection",UPDATE_PKI_COLLECTION = "update-pki-collection",diff --git a/frontend/src/pages/cert-manager/components/CertificateAlerts/CertificateAlertSheet.tsx b/frontend/src/pages/cert-manager/components/CertificateAlerts/CertificateAlertSheet.tsxindex 48a8b1dfe0..bcb230d9d7 100644--- a/frontend/src/pages/cert-manager/components/CertificateAlerts/CertificateAlertSheet.tsx+++ b/frontend/src/pages/cert-manager/components/CertificateAlerts/CertificateAlertSheet.tsx@@ -26,8 +26,8 @@ import {import { useGetOrgUsers } from "@app/hooks/api";import {AlertChannelType,- CertificateAlertEventType,TAlert,+ TCertificateAlertEventType,toChannelInput,useCreateAlert,useUpdateAlert@@ -46,6 +46,7 @@ import {emptyCertificateAlertForm,getAlertResourceId,getAlertResourceType,+ getScopeEventTypes,getSteps,STEP_FIELDS,TCertificateAlertForm,@@ -63,8 +64,7 @@ type Props = {scope: TCertificateAlertScope;alert?: TAlert;isReadOnly?: boolean;- usedEventTypes: CertificateAlertEventType[];- allowedEventTypes: CertificateAlertEventType[];+ usedEventTypes: TCertificateAlertEventType[];};type WizardProps = Omit<Props, "isOpen"> & {@@ -79,7 +79,6 @@ const CertificateAlertWizard = ({alert,isReadOnly = false,usedEventTypes,- allowedEventTypes,members,onDirtyChange}: WizardProps) => {@@ -93,7 +92,7 @@ const CertificateAlertWizard = ({defaultValues: alert? toCertificateAlertForm(alert, members): emptyCertificateAlertForm(- allowedEventTypes.find((event) => !usedEventTypes.includes(event))+ getScopeEventTypes(scope).find((event) => !usedEventTypes.includes(event)))});const eventType = useWatch({ control: form.control, name: "eventType" });@@ -223,7 +222,6 @@ const CertificateAlertWizard = ({scope={scope}isEditing={isEditing}usedEventTypes={usedEventTypes}- allowedEventTypes={allowedEventTypes}/>)}{currentStep.key === CertificateAlertStep.Filters && (diff --git a/frontend/src/pages/cert-manager/components/CertificateAlerts/CertificateAlertsCard.tsx b/frontend/src/pages/cert-manager/components/CertificateAlerts/CertificateAlertsCard.tsxindex 87a931c411..931760b963 100644--- a/frontend/src/pages/cert-manager/components/CertificateAlerts/CertificateAlertsCard.tsx+++ b/frontend/src/pages/cert-manager/components/CertificateAlerts/CertificateAlertsCard.tsx@@ -48,9 +48,9 @@ import {} from "@app/components/v3";import {AlertRunStatus,- CertificateAlertEventType,CertificateAlertResourceType,TAlert,+ TCertificateAlertEventType,useDeleteAlert,useListAlerts,useUpdateAlert@@ -76,17 +76,15 @@ import {const SCOPE_CARD_CONFIG: Record<CertificateAlertScopeKind,- { description: string; emptyDescription: string; docsUrl: string; hasFiltersColumn: boolean }+ { emptyDescription: string; docsUrl: string; hasFiltersColumn: boolean }> = {[CertificateAlertScopeKind.Application]: {- description: "Get notified about certificate events.",emptyDescription:"No alerts configured. Create one to get notified about certificate events for this application.",docsUrl: PkiDocsUrls.applications.alerting.overview,hasFiltersColumn: false},[CertificateAlertScopeKind.CertificateManager]: {- description: "Get notified about certificate events.",emptyDescription:"No alerts configured. Create one to get notified about certificate events across Certificate Manager.",docsUrl: PkiDocsUrls.settings.alerts,@@ -95,59 +93,38 @@ const SCOPE_CARD_CONFIG: Record<};const AlertFiltersSummary = ({ alert }: { alert: TAlert }) => {- const applicationIds = alert.condition?.applicationIds ?? [];- const profileIds = alert.condition?.profileIds ?? [];- const sources = alert.condition?.sources ?? [];const conditionNames = toConditionNames(alert);- const namesOf = (kind: CertificateFilterKind, ids: string[]) =>- ids.map((id) => getFilterName(kind, id, conditionNames)).join(", ");+ const activeFilters = Object.values(CertificateFilterKind).flatMap((kind) => {+ const ids: string[] = alert.condition?.[kind] ?? [];+ return ids.length ? [{ kind, ids }] : [];+ });- if (!isFilterableEventType(alert.eventType as CertificateAlertEventType)) {+ if (!isFilterableEventType(alert.eventType as TCertificateAlertEventType)) {return <span className="text-muted">All signers</span>;}- if (!applicationIds.length && !profileIds.length && !sources.length) {+ if (!activeFilters.length) {return <span className="text-muted">All certificates</span>;}- const summary = [- applicationIds.length ? pluralize(applicationIds.length, "application") : null,- profileIds.length ? pluralize(profileIds.length, "certificate profile") : null,- sources.length ? pluralize(sources.length, "source") : null- ]- .filter(Boolean)- .join(", ");-return (<Tooltip><TooltipTrigger asChild>- <span className="cursor-default text-accent">{summary}</span>+ <span className="cursor-default text-accent">+ {activeFilters+ .map(({ kind, ids }) =>+ pluralize(ids.length, CERTIFICATE_FILTER_DEFINITIONS[kind].noun)+ )+ .join(", ")}+ </span></TooltipTrigger><TooltipContent side="bottom" className="flex max-w-sm flex-col gap-1">- {applicationIds.length > 0 && (- <span>- <span className="text-muted">- {CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Applications].label}:{" "}- </span>- {namesOf(CertificateFilterKind.Applications, applicationIds)}- </span>- )}- {profileIds.length > 0 && (- <span>- <span className="text-muted">- {CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Profiles].label}:{" "}- </span>- {namesOf(CertificateFilterKind.Profiles, profileIds)}- </span>- )}- {sources.length > 0 && (- <span>- <span className="text-muted">- {CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Sources].label}:{" "}- </span>- {namesOf(CertificateFilterKind.Sources, sources)}+ {activeFilters.map(({ kind, ids }) => (+ <span key={kind}>+ <span className="text-muted">{CERTIFICATE_FILTER_DEFINITIONS[kind].label}: </span>+ {ids.map((id) => getFilterName(kind, id, conditionNames)).join(", ")}</span>- )}+ ))}</TooltipContent></Tooltip>);@@ -213,7 +190,7 @@ const AlertRow = ({</div></TableCell><TableCell className="whitespace-nowrap text-accent">- {CERTIFICATE_ALERT_EVENT_LABELS[alert.eventType as CertificateAlertEventType] ??+ {CERTIFICATE_ALERT_EVENT_LABELS[alert.eventType as TCertificateAlertEventType] ??alert.eventType}</TableCell><TableCell className="whitespace-nowrap">@@ -346,7 +323,7 @@ export const CertificateAlertsCard = ({(scope.kind === CertificateAlertScopeKind.CertificateManager && isSignerAlertsError);const usedEventTypes =scope.kind === CertificateAlertScopeKind.Application- ? alerts.map((alert) => alert.eventType as CertificateAlertEventType)+ ? alerts.map((alert) => alert.eventType as TCertificateAlertEventType): [];const creatableEventTypes = getScopeEventTypes(scope);const hasAllEventTypes = creatableEventTypes.every((eventType) =>@@ -381,7 +358,7 @@ export const CertificateAlertsCard = ({Alerts<DocumentationLinkBadge href={config.docsUrl} /></CardTitle>- <CardDescription>{config.description}</CardDescription>+ <CardDescription>Get notified about certificate events.</CardDescription><CardAction><Tooltip><TooltipTrigger asChild>@@ -483,7 +460,6 @@ export const CertificateAlertsCard = ({alert={alerts.find((a) => a.id === alertModal.alertId)}isReadOnly={alertModal.isReadOnly}usedEventTypes={usedEventTypes}- allowedEventTypes={creatableEventTypes}/><DeleteConfirmDialogisOpen={deleteAlertModal.isOpen}diff --git a/frontend/src/pages/cert-manager/components/CertificateAlerts/DetailsStep.tsx b/frontend/src/pages/cert-manager/components/CertificateAlerts/DetailsStep.tsxindex 9b3ad575a6..e770874510 100644--- a/frontend/src/pages/cert-manager/components/CertificateAlerts/DetailsStep.tsx+++ b/frontend/src/pages/cert-manager/components/CertificateAlerts/DetailsStep.tsx@@ -19,7 +19,7 @@ import {TextArea,Toggle} from "@app/components/v3";-import { CertificateAlertEventType } from "@app/hooks/api/alerts";+import { TCertificateAlertEventType } from "@app/hooks/api/alerts";import {CERTIFICATE_ALERT_EVENT_LABELS,@@ -36,22 +36,15 @@ type Props = {form: UseFormReturn<TCertificateAlertForm>;scope: TCertificateAlertScope;isEditing: boolean;- usedEventTypes: CertificateAlertEventType[];- allowedEventTypes: CertificateAlertEventType[];+ usedEventTypes: TCertificateAlertEventType[];};-export const DetailsStep = ({- form,- scope,- isEditing,- usedEventTypes,- allowedEventTypes-}: Props) => {+export const DetailsStep = ({ form, scope, isEditing, usedEventTypes }: Props) => {const eventType = useWatch({ control: form.control, name: "eventType" });const eventGroups = getScopeEventGroups(scope);const onEventTypeChange = (- next: CertificateAlertEventType,+ next: TCertificateAlertEventType,onChange: (value: string) => void) => {onChange(next);@@ -74,7 +67,7 @@ export const DetailsStep = ({<Selectvalue={field.value}onValueChange={(next) =>- onEventTypeChange(next as CertificateAlertEventType, field.onChange)+ onEventTypeChange(next as TCertificateAlertEventType, field.onChange)}disabled={isEditing}>@@ -90,10 +83,7 @@ export const DetailsStep = ({<SelectItemkey={event}value={event}- disabled={- !isEditing &&- (usedEventTypes.includes(event) || !allowedEventTypes.includes(event))- }+ disabled={!isEditing && usedEventTypes.includes(event)}>{CERTIFICATE_ALERT_EVENT_LABELS[event]}</SelectItem>diff --git a/frontend/src/pages/cert-manager/components/CertificateAlerts/ReviewStep.tsx b/frontend/src/pages/cert-manager/components/CertificateAlerts/ReviewStep.tsxindex f032b1fac4..d621c743fb 100644--- a/frontend/src/pages/cert-manager/components/CertificateAlerts/ReviewStep.tsx+++ b/frontend/src/pages/cert-manager/components/CertificateAlerts/ReviewStep.tsx@@ -73,51 +73,29 @@ const describeChannel = (channel: TChannelForm, members: TMemberEmails): string};const FilterDetails = ({- applicationIds,- profileIds,- sources,+ filters,conditionNames}: {- applicationIds: string[];- profileIds: string[];- sources: string[];+ filters: Partial<Record<CertificateFilterKind, string[]>>;conditionNames: Record<string, string>;-}) => {- const getApplicationName = (id: string) =>- getFilterName(CertificateFilterKind.Applications, id, conditionNames);- const getProfileName = (id: string) =>- getFilterName(CertificateFilterKind.Profiles, id, conditionNames);-- return (- <>- <Detail label={CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Applications].label}>- {applicationIds.length ? (- <PkiSyncFilterValueBadges values={applicationIds.map(getApplicationName)} />- ) : (- CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Applications].allLabel- )}- </Detail>- <Detail label={CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Profiles].label}>- {profileIds.length ? (- <PkiSyncFilterValueBadges values={profileIds.map(getProfileName)} />- ) : (- CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Profiles].allLabel- )}- </Detail>- <Detail label={CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Sources].label}>- {sources.length ? (- <PkiSyncFilterValueBadges- values={sources.map((source) =>- getFilterName(CertificateFilterKind.Sources, source, conditionNames)- )}- />- ) : (- CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Sources].allLabel- )}- </Detail>- </>- );-};+}) => (+ <>+ {Object.values(CertificateFilterKind).map((kind) => {+ const ids = filters[kind] ?? [];+ return (+ <Detail key={kind} label={CERTIFICATE_FILTER_DEFINITIONS[kind].label}>+ {ids.length ? (+ <PkiSyncFilterValueBadges+ values={ids.map((id) => getFilterName(kind, id, conditionNames))}+ />+ ) : (+ CERTIFICATE_FILTER_DEFINITIONS[kind].allLabel+ )}+ </Detail>+ );+ })}+ </>+);export const ReviewStep = ({ form, scope, members }: Props) => {const values = useWatch({ control: form.control }) as TCertificateAlertForm;@@ -147,16 +125,9 @@ export const ReviewStep = ({ form, scope, members }: Props) => {{scope.kind === CertificateAlertScopeKind.CertificateManager &&isFilterableEventType(values.eventType) && (<Section title="Certificate Filters">- {values.applicationIds?.length ||- values.profileIds?.length ||- values.sources?.length ? (+ {Object.values(CertificateFilterKind).some((kind) => values[kind]?.length) ? (<div className="grid grid-cols-2 gap-x-6 gap-y-4">- <FilterDetails- applicationIds={values.applicationIds ?? []}- profileIds={values.profileIds ?? []}- sources={values.sources ?? []}- conditionNames={values.conditionNames}- />+ <FilterDetails filters={values} conditionNames={values.conditionNames} /></div>) : (<span className="text-sm text-muted">{NO_FILTERS_DESCRIPTION}</span>diff --git a/frontend/src/pages/cert-manager/components/CertificateAlerts/types.ts b/frontend/src/pages/cert-manager/components/CertificateAlerts/types.tsindex 6d5c85b884..d201664b97 100644--- a/frontend/src/pages/cert-manager/components/CertificateAlerts/types.ts+++ b/frontend/src/pages/cert-manager/components/CertificateAlerts/types.ts@@ -2,14 +2,16 @@ import { z } from "zod";import {AlertPrincipalType,- CertificateAlertEventType,CertificateAlertResourceType,+ CertificateApplicationAlertEventType,CertificateManagerAlertEventType,channelFormSchema,MAX_CERTIFICATE_ALERT_BEFORE_DAYS,MAX_CERTIFICATE_ALERT_FILTER_IDS,+ SignerAlertEventType,TAlert,TAlertChannelRecipient,+ TCertificateAlertEventType,TChannelForm} from "@app/hooks/api/alerts";import { CertSource } from "@app/hooks/api/certificates/enums";@@ -27,32 +29,32 @@ export type TCertificateAlertScope =export const getAlertResourceId = (scope: TCertificateAlertScope) =>scope.kind === CertificateAlertScopeKind.Application ? scope.applicationId : null;-export const CERTIFICATE_ALERT_EVENT_LABELS: Record<CertificateAlertEventType, string> = {- [CertificateAlertEventType.Expiry]: "Certificate Expiration",- [CertificateAlertEventType.Issuance]: "Certificate Issuance",- [CertificateAlertEventType.Renewal]: "Certificate Renewal",- [CertificateAlertEventType.Revocation]: "Certificate Revocation",- [CertificateAlertEventType.SignerCertificateExpiry]: "Signer Certificate Expiration"+export const CERTIFICATE_ALERT_EVENT_LABELS: Record<TCertificateAlertEventType, string> = {+ [CertificateApplicationAlertEventType.Expiry]: "Certificate Expiration",+ [CertificateApplicationAlertEventType.Issuance]: "Certificate Issuance",+ [CertificateApplicationAlertEventType.Renewal]: "Certificate Renewal",+ [CertificateApplicationAlertEventType.Revocation]: "Certificate Revocation",+ [SignerAlertEventType.CertificateExpiry]: "Signer Certificate Expiration"};const CERTIFICATE_ALERT_EVENT_GROUPS: {label: string;- events: CertificateAlertEventType[];+ events: TCertificateAlertEventType[];scopes: CertificateAlertScopeKind[];}[] = [{label: "Certificate Lifecycle",events: [- CertificateAlertEventType.Expiry,- CertificateAlertEventType.Issuance,- CertificateAlertEventType.Renewal,- CertificateAlertEventType.Revocation+ CertificateApplicationAlertEventType.Expiry,+ CertificateApplicationAlertEventType.Issuance,+ CertificateApplicationAlertEventType.Renewal,+ CertificateApplicationAlertEventType.Revocation],scopes: [CertificateAlertScopeKind.Application, CertificateAlertScopeKind.CertificateManager]},{label: "Code Signing",- events: [CertificateAlertEventType.SignerCertificateExpiry],+ events: [SignerAlertEventType.CertificateExpiry],scopes: [CertificateAlertScopeKind.CertificateManager]}];@@ -63,20 +65,20 @@ export const getScopeEventGroups = (scope: TCertificateAlertScope) =>export const getScopeEventTypes = (scope: TCertificateAlertScope) =>getScopeEventGroups(scope).flatMap((group) => group.events);-export const isExpiryEventType = (eventType: CertificateAlertEventType) =>- eventType === CertificateAlertEventType.Expiry ||- eventType === CertificateAlertEventType.SignerCertificateExpiry;+export const isExpiryEventType = (eventType: TCertificateAlertEventType) =>+ eventType === CertificateApplicationAlertEventType.Expiry ||+ eventType === SignerAlertEventType.CertificateExpiry;-export const isFilterableEventType = (eventType: CertificateAlertEventType) =>- eventType !== CertificateAlertEventType.SignerCertificateExpiry;+export const isFilterableEventType = (eventType: TCertificateAlertEventType) =>+ eventType !== SignerAlertEventType.CertificateExpiry;const CERTIFICATE_MANAGER_EVENT_TYPES: Partial<- Record<CertificateAlertEventType, CertificateManagerAlertEventType>+ Record<TCertificateAlertEventType, CertificateManagerAlertEventType>> = {- [CertificateAlertEventType.Expiry]: CertificateManagerAlertEventType.Expiry,- [CertificateAlertEventType.Issuance]: CertificateManagerAlertEventType.Issuance,- [CertificateAlertEventType.Renewal]: CertificateManagerAlertEventType.Renewal,- [CertificateAlertEventType.Revocation]: CertificateManagerAlertEventType.Revocation+ [CertificateApplicationAlertEventType.Expiry]: CertificateManagerAlertEventType.Expiry,+ [CertificateApplicationAlertEventType.Issuance]: CertificateManagerAlertEventType.Issuance,+ [CertificateApplicationAlertEventType.Renewal]: CertificateManagerAlertEventType.Renewal,+ [CertificateApplicationAlertEventType.Revocation]: CertificateManagerAlertEventType.Revocation};const EVENT_TYPES_BY_CERTIFICATE_MANAGER_EVENT = Object.fromEntries(@@ -84,13 +86,13 @@ const EVENT_TYPES_BY_CERTIFICATE_MANAGER_EVENT = Object.fromEntries(apiEventType,eventType])-) as Record<string, CertificateAlertEventType>;+) as Record<string, TCertificateAlertEventType>;export const getAlertResourceType = (scope: TCertificateAlertScope,- eventType: CertificateAlertEventType+ eventType: TCertificateAlertEventType) => {- if (eventType === CertificateAlertEventType.SignerCertificateExpiry)+ if (eventType === SignerAlertEventType.CertificateExpiry)return CertificateAlertResourceType.Signer;return scope.kind === CertificateAlertScopeKind.CertificateManager? CertificateAlertResourceType.CertificateManager@@ -99,7 +101,7 @@ export const getAlertResourceType = (export const toApiEventType = (scope: TCertificateAlertScope,- eventType: CertificateAlertEventType+ eventType: TCertificateAlertEventType): string =>(scope.kind === CertificateAlertScopeKind.CertificateManager &&CERTIFICATE_MANAGER_EVENT_TYPES[eventType]) ||@@ -108,20 +110,22 @@ export const toApiEventType = (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.",- [CertificateAlertEventType.Issuance]: (where) =>+const ALERT_EVENT_DESCRIPTIONS: Record<TCertificateAlertEventType, (where: string) => string> = {+ [CertificateApplicationAlertEventType.Expiry]: () =>+ "Fires ahead of a certificate's expiry date.",+ [CertificateApplicationAlertEventType.Issuance]: (where) =>`Fires when Infisical issues a certificate ${where}.`,- [CertificateAlertEventType.Renewal]: (where) => `Fires when a certificate ${where} is renewed.`,- [CertificateAlertEventType.Revocation]: (where) =>+ [CertificateApplicationAlertEventType.Renewal]: (where) =>+ `Fires when a certificate ${where} is renewed.`,+ [CertificateApplicationAlertEventType.Revocation]: (where) =>`Fires when a certificate ${where} is revoked.`,- [CertificateAlertEventType.SignerCertificateExpiry]: () =>+ [SignerAlertEventType.CertificateExpiry]: () =>"Fires ahead of the expiry date of the certificate each signer currently signs with."};export const getAlertEventDescription = (scope: TCertificateAlertScope,- eventType: CertificateAlertEventType+ eventType: TCertificateAlertEventType) =>ALERT_EVENT_DESCRIPTIONS[eventType](scope.kind === CertificateAlertScopeKind.Application@@ -185,22 +189,25 @@ export enum CertificateFilterKind {export const CERTIFICATE_FILTER_DEFINITIONS: Record<CertificateFilterKind,- { label: string; hint: string; allLabel: string; unknownLabel: string }+ { label: string; noun: string; hint: string; allLabel: string; unknownLabel: string }> = {[CertificateFilterKind.Applications]: {label: "Applications",+ noun: "application",hint: "Certificates in one of these applications",allLabel: "All applications",unknownLabel: "Unknown application"},[CertificateFilterKind.Profiles]: {label: "Certificate Profiles",+ noun: "certificate profile",hint: "Issued from one of these profiles",allLabel: "All certificate profiles",unknownLabel: "Unknown profile"},[CertificateFilterKind.Sources]: {label: "Source",+ noun: "source",hint: "Managed, imported, or discovered certificates",allLabel: "All sources",unknownLabel: "Unknown source"@@ -267,7 +274,7 @@ const STEP_DEFINITIONS = {}};-export const getSteps = (scope: TCertificateAlertScope, eventType: CertificateAlertEventType) =>+export const getSteps = (scope: TCertificateAlertScope, eventType: TCertificateAlertEventType) =>(scope.kind === CertificateAlertScopeKind.CertificateManager && isFilterableEventType(eventType)? [CertificateAlertStep.Details,@@ -280,7 +287,10 @@ export const getSteps = (scope: TCertificateAlertScope, eventType: CertificateAlexport const certificateAlertFormSchema = z.object({- eventType: z.nativeEnum(CertificateAlertEventType),+ eventType: z.union([+ z.nativeEnum(CertificateApplicationAlertEventType),+ z.nativeEnum(SignerAlertEventType)+ ]),name: z.string().trim().min(1, "Name is required").max(255),description: z.string().trim().max(1000),alertBefore: z.string().trim(),@@ -342,7 +352,7 @@ export const STEP_FIELDS: Partial<Record<CertificateAlertStep, (keyof TCertifica};export const emptyCertificateAlertForm = (- eventType = CertificateAlertEventType.Expiry+ eventType: TCertificateAlertEventType = CertificateApplicationAlertEventType.Expiry): TCertificateAlertForm => ({eventType,name: "",@@ -358,7 +368,7 @@ export const toCertificateAlertForm = (alert: TAlert,{ emailByUserId, isAvailable }: Pick<TMemberEmails, "emailByUserId" | "isAvailable">): TCertificateAlertForm => ({- eventType: alert.eventType as CertificateAlertEventType,+ eventType: alert.eventType as TCertificateAlertEventType,name: alert.name,description: alert.description ?? "",alertBefore: alert.condition?.alertBefore ?? "30d",