Skip to content

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

Address PR comments

Carlos Monastyrskif9d05e046f74
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index cfc4619226..108240ddfe 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -707,7 +707,7 @@ Invariants worth knowing before extending it:
- **The alert module owns no CASL subject.** Each provider reuses its own resource's existing permissions inside `assertPermission`, so authorization stays with the domain that owns the resource.
- **New delivery mediums are channel definitions**, not providers: add one under `src/services/alert/channels/` and register it in `ALERT_CHANNEL_REGISTRY`. `directed: true` means the channel addresses principals and needs recipients (email); undirected channels carry their destination in config. `secretFields` drives masking on read and merge-from-stored on update.
- **Channel configs are encrypted** with the org/project KMS cipher (`alert-channel-crypto-fns.ts`) — never store or return them in plaintext.
-- **One alert per `(scope, resource, event)` for resource-bound alerts**, enforced by the partial `alert_unique_scope_resource_event_bound` index. A provider that sets `supportsScopeWideAlerts` also accepts alerts with no `resourceId`: such an alert watches every resource of its type in scope (`findEnabledForEvent` matches it for any `resourceId`), several can watch the same event because they differ by condition, and `assertConditionInScope` is where the provider checks the IDs inside a condition, on create and on update (newly added IDs only). Certificate Manager-wide alerts are `cert-manager.application` alerts with no `resourceId`, narrowed by `applicationIds` and `profileIds`; creating or editing one requires unconditional certificate read, since it sends details from every application. Signer certificate expiration (`cert-manager.signer-certificate.expiry`, `CodeSigningAlertEvent`) is a scheduled event on the same provider that only exists scope-wide: it scans the certificate each active signer points at through `pki_signers.certificateId` (so a reissue moves the alert to the new certificate), takes no filters, and creating or editing one requires the project Admin role instead (unconditional `code-signers` read only opens the signer list; non-admins see only signers they are members of), which is why `TAlertPermissionInput` carries an optional `eventType`. **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 (`findEnabledForEvent` matches it for any `resourceId`), several can watch the same event because they differ by condition, and `assertConditionInScope` is where the provider checks the IDs inside a condition, on create and on update (newly added IDs only). Certificate Manager-wide alerts are `cert-manager.application` alerts with no `resourceId`, narrowed by `applicationIds` and `profileIds`; creating or editing one requires unconditional certificate read, since it sends details from every application. Signer certificate expiration has its own provider, `cert-manager.signer` (`cert-manager-signer-alert-provider.ts`, event `cert-manager.signer.certificate.expiry`), that only exists scope-wide: it scans one row per certificate an active signer points at through `pki_signers.certificateId`, naming every signer that shares it (so a reissue moves the alert to the new certificate), takes no filters, and creating or editing one requires the project Admin role (unconditional `code-signers` read only opens the signer list; non-admins see only signers they are members of). Helpers both Certificate Manager providers share (expiry schema, dedup windows, license gate, audit and telemetry builders) live in `cert-manager-alert-fns.ts`. **Every provider hook is opt-in, and its absence must reproduce the behaviour identity alerts had before any other provider existed.** `recipientPolicy` decides who can receive: `atOrgScope` validates and resolves user and group recipients against the org instead of the alert's project, and `allowEmailAddresses` accepts plain `EMAIL` recipients and makes test sends validate recipients like create and update do, instead of silently dropping out-of-scope ones (application alerts set both). `includeLastRun` adds `lastRun` to alert responses, and `resourceName` is only returned by providers that implement `getResourceNames`, and `filters` (read-only `{ id, name }` lists for the IDs inside a condition, keyed by kind, such as `applications` and `profiles` on a Certificate Manager-wide alert, with a null name for deleted IDs, matching how approval policies return approvers) only by providers that implement `getFilters`. Resolve such names there rather than adding ID filters to another domain's list endpoint. `assertChannelTypesAllowed` is where a provider gates paid channel types on create and on update (new, retyped, or re-enabled channels only, so a downgraded org can still edit the alert). `getResourceNames` (batched) supplies the resource's display name for alert responses and for a provider's own audit events. `resolveProjectId` lets create, list and test sends omit `projectId` when the resource already belongs to one project (`resolveAlertProjectId` in `alert-provider-registry.ts`). `getTelemetryEvent` lets a provider map alert create, update and delete to its own PostHog event, so the shared router never branches on a resource type. `getAuditEvent` does the same for audit logs: a provider that needs distinct event types (application alerts log `create-pki-application-alert` and its siblings, with the application's ID and name) returns its own event, and every other provider falls back to the generic `create-alert` family via `buildGenericAlertAuditEvent`. Add a provider's own event interfaces next to the generic ones; never widen the generic ones. The deprecated `pki/alerts` and `applications/:applicationId/alerts` routes only serve legacy PKI Alerts V2 rows. Add features to `/api/v1/alerts`, not to them.
- **Email channels accept plain addresses as `EMAIL` recipients when the provider opts in** (`recipientPolicy.allowEmailAddresses`), with the address as `principalId`, besides users and groups. Every address must be on one of the org's verified email domains, checked on create, update and test sends (`alert-channel-service.ts`), and again at send time, so an address on a domain the org has since removed stops receiving alerts. The resolver sends to them directly and skips an address that a user recipient on the same channel already covers.
- **`findScheduledTargets` must return most-urgent-first.** The engine's per-channel `maxTargetsPerRun` cap keeps the head of the list and defers the tail, so ordering is what guarantees the closest-to-expiry targets are never the dropped ones.
- **A `findScheduledTargets` that caps its own row count must honour `alreadyAlerted`.** The engine passes `{ alertId, channelIds, since }` (the alert's enabled channels and its dedup cutoff), and the provider drops targets every one of those channels already delivered since then, in SQL before the limit. Dedup otherwise runs after the fetch, so once more targets are due than the cap, the same head of the list comes back every run, is deduped, and nothing past it is ever alerted. That filter alone is not enough when the dedup window is shorter than the scan interval (a daily reminder), because yesterday's head is due again, so such a provider also orders the targets this alert notified least recently first, then by expiry. The certificate alert DAL does both in `findExpiringCertificates`.
diff --git a/backend/e2e-test/cert-manager-application-alert-dal.spec.ts b/backend/e2e-test/cert-manager-application-alert-dal.spec.ts
index e042d9361d..825bf53555 100644
--- a/backend/e2e-test/cert-manager-application-alert-dal.spec.ts
+++ b/backend/e2e-test/cert-manager-application-alert-dal.spec.ts
@@ -60,7 +60,7 @@ const insertDelivery = async (
);
};
-const scan = (alreadyAlerted?: { alertId: string; channelIds: string[]; since: Date }) =>
+const scan = (alreadyAlerted: { alertId: string; channelIds: string[]; since: Date }) =>
dal.findExpiringCertificates({
projectId: PROJECT_ID,
alertBeforeInterval: "30 days",
@@ -144,8 +144,14 @@ describe("cert manager certificate alert DAL (postgres)", () => {
await testDb(TableName.Certificate).whereIn("id", allCertificateIds()).del();
});
- test("without an already-alerted filter every due certificate comes back", async () => {
- expect(ownIds(await scan()).sort()).toEqual(allCertificateIds().sort());
+ test("an alert with no deliveries yet gets every due certificate", async () => {
+ const found = ownIds(await scan({ alertId: randomUUID(), channelIds, since }));
+ expect(found.sort()).toEqual(allCertificateIds().sort());
+ });
+
+ test("certificates still owed to a channel come before ones already delivered on every channel", async () => {
+ const found = ownIds(await scan({ alertId, channelIds, since }));
+ expect(found[found.length - 1]).toBe(certificateIds.beforeWindow);
});
test("a certificate is dropped only when every enabled channel delivered it inside the window", async () => {
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index c8bfa1c580..39309a84ad 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2416,7 +2416,6 @@ export const ALERTING = {
resourceId: "The ID of the resource the alert watches.",
projectId: "The ID of the project the alert belongs to.",
alertId: "The ID of the saved alert the channel belongs to.",
- eventType: "The event of the alert being created. Ignored when `alertId` is set.",
channelId: "The ID of the saved channel to test."
},
LIST: {
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 01edfaa49f..dccdfa45fd 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -251,6 +251,8 @@ import { alertRecipientResolverFactory } from "@app/services/alert/alert-recipie
import { alertServiceFactory } from "@app/services/alert/alert-service";
import { certManagerApplicationAlertDALFactory } from "@app/services/alert/providers/cert-manager-application-alert-dal";
import { certManagerApplicationAlertProviderFactory } from "@app/services/alert/providers/cert-manager-application-alert-provider";
+import { 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";
import { identityCredentialAlertProviderFactory } from "@app/services/alert/providers/identity-credential-alert-provider";
import { announcementServiceFactory } from "@app/services/announcement/announcement-service";
@@ -1103,6 +1105,14 @@ export const registerRoutes = async (
certManagerProjectResolver
})
);
+ alertProviderRegistry.register(
+ certManagerSignerAlertProviderFactory({
+ certManagerSignerAlertDAL: certManagerSignerAlertDALFactory(db),
+ permissionService,
+ licenseService,
+ certManagerProjectResolver
+ })
+ );
const alertRecipientResolver = alertRecipientResolverFactory({
userDAL,
userGroupMembershipDAL,
diff --git a/backend/src/server/routes/v1/alert-router.ts b/backend/src/server/routes/v1/alert-router.ts
index 6d0d9901f3..3b73c5fae6 100644
--- a/backend/src/server/routes/v1/alert-router.ts
+++ b/backend/src/server/routes/v1/alert-router.ts
@@ -146,7 +146,6 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
resourceId: z.string().uuid().nullable().optional().describe(ALERTING.TEST_CHANNEL.resourceId),
projectId: z.string().nullable().optional().describe(ALERTING.TEST_CHANNEL.projectId),
alertId: z.string().uuid().optional().describe(ALERTING.TEST_CHANNEL.alertId),
- eventType: z.string().trim().min(1).max(255).optional().describe(ALERTING.TEST_CHANNEL.eventType),
channelId: z.string().uuid().optional().describe(ALERTING.TEST_CHANNEL.channelId),
channelType: z.nativeEnum(AlertChannelType),
config: z.record(z.unknown()).default({}),
diff --git a/backend/src/services/alert/alert-channel-test-service.test.ts b/backend/src/services/alert/alert-channel-test-service.test.ts
index 993c883e29..6ee09d0c66 100644
--- a/backend/src/services/alert/alert-channel-test-service.test.ts
+++ b/backend/src/services/alert/alert-channel-test-service.test.ts
@@ -97,8 +97,7 @@ const OWNING_ALERT = {
orgId: ORG_ID,
projectId: null,
resourceType: RESOURCE_TYPE,
- resourceId: "resource-1",
- eventType: "test.resource.saved"
+ resourceId: "resource-1"
};
const buildDeps = (overrides?: {
@@ -392,37 +391,6 @@ describe("alertChannelTestService", () => {
expect(actions).toEqual(["edit", "create"]);
});
- test("checks the permission for the event being set up, and the saved alert's event when there is one", async () => {
- const eventTypes: (string | undefined)[] = [];
- const restore = stubSend("slack", async () => ({ success: true }));
- const newService = () =>
- alertChannelTestServiceFactory(
- buildDeps({
- registry: buildProvider({
- assertPermission: async (input) => {
- eventTypes.push(input.eventType);
- }
- })
- }).deps
- );
- const dto = {
- ...actor,
- resourceType: RESOURCE_TYPE,
- resourceId: OWNING_ALERT.resourceId,
- channelType: "slack" as never,
- config: { webhookUrl: "https://hooks.slack.com/services/T/B/new" }
- };
-
- await newService().testChannel({ ...dto, eventType: "test.resource.expiration" });
- await newService().testChannel({ ...dto, alertId: OWNING_ALERT.id, eventType: "test.resource.expiration" });
- await newService().testChannel({ ...dto, alertId: OWNING_ALERT.id, eventType: "test.resource.unknown" });
- await expect(newService().testChannel({ ...dto, eventType: "test.resource.unknown" })).rejects.toThrow(
- "Event type 'test.resource.unknown' is not supported by resource type"
- );
- restore();
- expect(eventTypes).toEqual(["test.resource.expiration", "test.resource.saved", "test.resource.saved"]);
- });
-
test("rejects an alert id from another resource or that does not exist", async () => {
const { deps } = buildDeps();
const service = alertChannelTestServiceFactory(deps);
diff --git a/backend/src/services/alert/alert-channel-test-service.ts b/backend/src/services/alert/alert-channel-test-service.ts
index 13036bcfac..16d192f068 100644
--- a/backend/src/services/alert/alert-channel-test-service.ts
+++ b/backend/src/services/alert/alert-channel-test-service.ts
@@ -15,12 +15,7 @@ import { TAlertChannelServiceFactory } from "./alert-channel-service";
import { TAlertChannelDeps, TAlertRecipient } from "./alert-channel-types";
import { TAlertDALFactory } from "./alert-dal";
import { getRecipientScope } from "./alert-principal-scope-fns";
-import {
- getAlertEvent,
- getAlertResourceName,
- resolveAlertProjectId,
- TAlertProviderRegistry
-} from "./alert-provider-registry";
+import { getAlertResourceName, resolveAlertProjectId, TAlertProviderRegistry } from "./alert-provider-registry";
import { TAlertRecipientResolver } from "./alert-recipient-resolver";
import { TTestAlertChannelDTO, TTestAlertChannelResponse, TTestAlertChannelResult } from "./alert-service-types";
import { buildTestAlertPayload } from "./alert-test-payload-fns";
@@ -89,7 +84,6 @@ export const alertChannelTestServiceFactory = ({
orgId: owner.orgId,
projectId: owner.projectId,
resourceId: owner.resourceId,
- eventType: owner.eventType,
actor: toAlertActor(dto)
});
}
@@ -216,7 +210,6 @@ export const alertChannelTestServiceFactory = ({
});
let alertName: string | null = null;
- let alertEventType = dto.eventType;
if (dto.alertId) {
const alert = await alertDAL.findActiveById(dto.alertId);
if (
@@ -229,9 +222,6 @@ export const alertChannelTestServiceFactory = ({
throw new NotFoundError({ message: `Alert with ID '${dto.alertId}' was not found in this scope` });
}
alertName = alert.name;
- alertEventType = alert.eventType;
- } else if (dto.eventType) {
- getAlertEvent(provider, dto.eventType);
}
await provider.assertPermission({
@@ -239,7 +229,6 @@ export const alertChannelTestServiceFactory = ({
orgId: dto.actorOrgId,
projectId,
resourceId: dto.resourceId,
- eventType: alertEventType,
actor: toAlertActor(dto)
});
await provider.assertResourceInScope({ orgId: dto.actorOrgId, projectId, resourceId: dto.resourceId });
diff --git a/backend/src/services/alert/alert-service-types.ts b/backend/src/services/alert/alert-service-types.ts
index 91f5909ae7..d768945ef2 100644
--- a/backend/src/services/alert/alert-service-types.ts
+++ b/backend/src/services/alert/alert-service-types.ts
@@ -43,7 +43,6 @@ export type TTestAlertChannelDTO = TGenericPermission & {
resourceId?: string | null;
projectId?: string | null;
alertId?: string;
- eventType?: string;
channelId?: string;
channelType: AlertChannelType;
config?: Record<string, unknown>;
diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.ts
index bb3ba6451a..dfaeb152b6 100644
--- a/backend/src/services/alert/alert-service.ts
+++ b/backend/src/services/alert/alert-service.ts
@@ -108,7 +108,7 @@ export const alertServiceFactory = ({
const $assertAlertPermission = (
provider: IResourceAlertProvider,
action: AlertPermissionAction,
- scope: { orgId: string; projectId?: string | null; resourceId?: string | null; eventType?: string },
+ scope: { orgId: string; projectId?: string | null; resourceId?: string | null },
dto: TGenericPermission
) =>
provider.assertPermission({
@@ -116,7 +116,6 @@ export const alertServiceFactory = ({
orgId: scope.orgId,
projectId: scope.projectId,
resourceId: scope.resourceId,
- eventType: scope.eventType,
actor: toAlertActor(dto)
});
@@ -212,7 +211,7 @@ export const alertServiceFactory = ({
await $assertAlertPermission(
provider,
AlertPermissionAction.Create,
- { orgId: dto.actorOrgId, projectId, resourceId: dto.resourceId, eventType: dto.eventType },
+ { orgId: dto.actorOrgId, projectId, resourceId: dto.resourceId },
dto
);
@@ -461,7 +460,7 @@ export const alertServiceFactory = ({
await $assertAlertPermission(
provider,
AlertPermissionAction.Edit,
- { orgId: alert.orgId, projectId: alert.projectId, resourceId: alert.resourceId, eventType: alert.eventType },
+ { orgId: alert.orgId, projectId: alert.projectId, resourceId: alert.resourceId },
dto
);
diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.ts
index 46b747bba0..9d7f17a7c2 100644
--- a/backend/src/services/alert/alert-types.ts
+++ b/backend/src/services/alert/alert-types.ts
@@ -41,7 +41,6 @@ export type TAlertPermissionInput = {
orgId: string;
projectId?: string | null;
resourceId?: string | null;
- eventType?: string;
actor: TGenericPermission;
};
@@ -191,9 +190,9 @@ 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 puts the targets this
- // alert notified least recently ahead of that, so a cap below the due count rotates instead of
- // re-sending the same head every run.
+ // 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.
// Required for any Scheduled event; the registry enforces that at boot.
findScheduledTargets?(input: TFindScheduledTargetsInput): Promise<TTarget[]>;
diff --git a/backend/src/services/alert/channels/alert-channel-email-fns.ts b/backend/src/services/alert/channels/alert-channel-email-fns.ts
index 750dc65336..e7cf47ee8e 100644
--- a/backend/src/services/alert/channels/alert-channel-email-fns.ts
+++ b/backend/src/services/alert/channels/alert-channel-email-fns.ts
@@ -8,6 +8,8 @@ import {
TChannelResult
} from "../alert-channel-types";
+const MAX_ITEMS_DISPLAYED = 50;
+
const buildSubstitutions = (payload: TAlertPayload) => ({
alertName: payload.alert.name,
eventLabel: payload.eventLabel,
@@ -16,12 +18,13 @@ const buildSubstitutions = (payload: TAlertPayload) => ({
summary: payload.summary,
severity: payload.severity,
viewUrl: payload.alert.viewUrl,
- items: payload.items.map((item) => ({
+ items: payload.items.slice(0, MAX_ITEMS_DISPLAYED).map((item) => ({
id: item.id,
title: item.title,
identifier: item.identifier,
fields: item.fields ?? []
- }))
+ })),
+ remainingCount: Math.max(payload.items.length - MAX_ITEMS_DISPLAYED, 0)
});
const sendEmail = async (
diff --git a/backend/src/services/alert/channels/alert-channels.test.ts b/backend/src/services/alert/channels/alert-channels.test.ts
index 96ce0353bc..60e9269abe 100644
--- a/backend/src/services/alert/channels/alert-channels.test.ts
+++ b/backend/src/services/alert/channels/alert-channels.test.ts
@@ -267,6 +267,54 @@ describe("sendEmailNotification (directed)", () => {
expect(sentTo).toEqual(["[email protected]"]);
});
+ test("lists at most 50 items and counts the rest so a large run renders quickly", async () => {
+ let substitutions: { items: unknown[]; remainingCount: number } | undefined;
+ const payload = samplePayload();
+ payload.items = Array.from({ length: 120 }, (_, index) => ({
+ id: `cert-${index}`,
+ title: `cert-${index}.example.com`
+ }));
+ const ctx = {
+ ...baseCtx(),
+ payload,
+ config: {},
+ recipient: { email: "[email protected]" },
+ deps: {
+ smtpService: {
+ sendMail: async (opts: { substitutions: object }) => {
+ substitutions = opts.substitutions as { items: unknown[]; remainingCount: number };
+ }
+ }
+ }
+ };
+
+ await sendEmailNotification(ctx);
+
+ expect(substitutions?.items).toHaveLength(50);
+ expect(substitutions?.remainingCount).toBe(70);
+ });
+
+ test("shows every item and no remainder when the run is small", async () => {
+ let substitutions: { items: unknown[]; remainingCount: number } | undefined;
+ const ctx = {
+ ...baseCtx(),
+ config: {},
+ recipient: { email: "[email protected]" },
+ deps: {
+ smtpService: {
+ sendMail: async (opts: { substitutions: object }) => {
+ substitutions = opts.substitutions as { items: unknown[]; remainingCount: number };
+ }
+ }
+ }
+ };
+
+ await sendEmailNotification(ctx);
+
+ expect(substitutions?.items).toHaveLength(2);
+ expect(substitutions?.remainingCount).toBe(0);
+ });
+
test("fails when there is no recipient", async () => {
const result = await sendEmailNotification({ ...baseCtx(), config: {} });
expect(result.success).toBe(false);
diff --git a/backend/src/services/alert/providers/cert-manager-alert-fns.ts b/backend/src/services/alert/providers/cert-manager-alert-fns.ts
new file mode 100644
index 0000000000..2daf4a27ee
--- /dev/null
+++ b/backend/src/services/alert/providers/cert-manager-alert-fns.ts
@@ -0,0 +1,137 @@
+import { z } from "zod";
+
+import { Event as TAuditEvent, EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
+import { ProjectPermissionActions } from "@app/ee/services/permission/project-permission";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { TCertManagerProjectResolverFactory } from "@app/services/cert-manager-instance/cert-manager-project-resolver";
+import { PkiAlertScope, PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+
+import { AlertChannelType } from "../alert-channel-types";
+import { durationToDays } from "../alert-format-fns";
+import {
+ AlertAuditAction,
+ AlertPermissionAction,
+ AlertTelemetryAction,
+ TAlertAuditInput,
+ TAlertTelemetryEvent
+} from "../alert-types";
+
+const MIN_ALERT_BEFORE_DAYS = 1;
+const MAX_ALERT_BEFORE_DAYS = 365;
+
+const isValidAlertBefore = (alertBefore: string): boolean => {
+ const days = durationToDays(alertBefore);
+ return days >= MIN_ALERT_BEFORE_DAYS && days <= MAX_ALERT_BEFORE_DAYS;
+};
+
+export const ExpiryFieldsSchema = z.object({
+ alertBefore: z
+ .string()
+ .refine(
+ isValidAlertBefore,
+ `Must be a number of days, weeks, months or years adding up to ${MIN_ALERT_BEFORE_DAYS} to ${MAX_ALERT_BEFORE_DAYS} days, e.g. '30d' or '2w'`
+ ),
+ dailyReminder: z.boolean().optional()
+});
+
+const DAILY_SCAN_DEDUP_MARGIN_HOURS = 4;
+
+const dayMultipleDedupWindowHours = (days: number): number => days * 24 - DAILY_SCAN_DEDUP_MARGIN_HOURS;
+
+export const expirationDedupWindowHours = (days: number, dailyReminder?: boolean): number => {
+ if (dailyReminder || days <= 7) return dayMultipleDedupWindowHours(1);
+ if (days <= 30) return dayMultipleDedupWindowHours(2);
+ if (days <= 90) return dayMultipleDedupWindowHours(7);
+ return dayMultipleDedupWindowHours(30);
+};
+
+export const CERT_MANAGER_ALERT_PERMISSION_ACTIONS: Record<AlertPermissionAction, ProjectPermissionActions> = {
+ [AlertPermissionAction.Read]: ProjectPermissionActions.Read,
+ [AlertPermissionAction.Create]: ProjectPermissionActions.Create,
+ [AlertPermissionAction.Edit]: ProjectPermissionActions.Edit,
+ [AlertPermissionAction.Delete]: ProjectPermissionActions.Delete
+};
+
+export const splitAltNames = (altNames: string | null): string[] =>
+ (altNames ?? "")
+ .split(",")
+ .map((name) => name.trim())
+ .filter(Boolean);
+
+export const certificateDisplayName = (certificate: {
+ commonName: string;
+ altNames: string | null;
+ serialNumber: string;
+}): string => certificate.commonName || splitAltNames(certificate.altNames)[0] || certificate.serialNumber;
+
+export const assertCertManagerAlertChannelTypesAllowed = async (
+ licenseService: Pick<TLicenseServiceFactory, "getPlan">,
+ { orgId, channelTypes }: { orgId: string; channelTypes: string[] }
+) => {
+ const gatedType = channelTypes.find((channelType) => channelType !== AlertChannelType.EMAIL);
+ if (!gatedType) return;
+
+ const plan = await licenseService.getPlan(orgId);
+ if (!plan.pkiEnterpriseAlerting) {
+ throw new BadRequestError({
+ message: `Failed to save a ${gatedType} channel due to plan restriction. Upgrade plan to alert on channels other than email, or disable or remove the ${gatedType} channel.`
+ });
+ }
+};
+
+export const resolveCertManagerProjectId = async (
+ certManagerProjectResolver: Pick<TCertManagerProjectResolverFactory, "getActiveProjectId">,
+ orgId: string
+) => {
+ const projectId = await certManagerProjectResolver.getActiveProjectId(orgId);
+ if (!projectId) {
+ throw new NotFoundError({ message: "Certificate Manager isn't set up for this organization" });
+ }
+ return projectId;
+};
+
+type TAlertFilterNames = { id: string; name: string | null }[];
+
+export const buildCertificateManagerAlertAuditEvent = (
+ input: TAlertAuditInput,
+ { applications, profiles }: { applications: TAlertFilterNames; profiles: TAlertFilterNames }
+): 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
+ }
+ };
+ }
+
+ const { alert } = input;
+ const metadata = { alertId: alert.id, name: alert.name, eventType: alert.eventType, applications, profiles };
+ if (input.action === AlertAuditAction.Create) return { type: EventType.CREATE_CERTIFICATE_MANAGER_ALERT, metadata };
+ if (input.action === AlertAuditAction.Update) return { type: EventType.UPDATE_CERTIFICATE_MANAGER_ALERT, metadata };
+ return { type: EventType.DELETE_CERTIFICATE_MANAGER_ALERT, metadata };
+};
+
+export const buildPkiAlertTelemetryEvent = (
+ action: AlertTelemetryAction,
+ properties: { orgId: string; projectId: string; applicationId?: string; alertScope: PkiAlertScope },
+ alertType: string
+): TAlertTelemetryEvent => {
+ switch (action) {
+ case AlertTelemetryAction.Create:
+ return { event: PostHogEventTypes.PkiAlertCreated, properties: { ...properties, alertType } };
+ case AlertTelemetryAction.Update:
+ return { event: PostHogEventTypes.PkiAlertUpdated, properties };
+ default:
+ return { event: PostHogEventTypes.PkiAlertDeleted, properties };
+ }
+};
diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-dal.test.ts b/backend/src/services/alert/providers/cert-manager-application-alert-dal.test.ts
index 8ed3abee1b..29df8d0879 100644
--- a/backend/src/services/alert/providers/cert-manager-application-alert-dal.test.ts
+++ b/backend/src/services/alert/providers/cert-manager-application-alert-dal.test.ts
@@ -21,7 +21,6 @@ const buildDAL = (firstQueryRows: unknown[] = []) => {
}
});
}) as unknown as Knex;
- Object.assign(reader, { raw: builder.raw.bind(builder) });
const db = Object.assign(reader, { replicaNode: () => reader }) as unknown as TDbClient;
return { dal: certManagerApplicationAlertDALFactory(db), queries };
@@ -37,7 +36,8 @@ describe("cert manager certificate alert DAL", () => {
applicationId: APPLICATION_ID,
alertBeforeInterval: "30 days",
leadInterval: "1 hour",
- asOf
+ asOf,
+ alreadyAlerted: { alertId: "alert-1", channelIds: ["channel-1"], since: asOf }
});
const [{ sql, bindings }] = queries;
@@ -68,19 +68,22 @@ describe("cert manager certificate alert DAL", () => {
expect(queries).toHaveLength(2);
const [notFullyNotified, leastRecentlyNotified] = queries;
- expect(notFullyNotified.sql).toContain('count(distinct "tgt"."channelId")');
- expect(notFullyNotified.sql).toContain('"tgt"."targetId" = "certificates".id::text');
- expect(notFullyNotified.sql).toContain('count(distinct "everTgt"."channelId")');
+ expect(notFullyNotified.sql).toContain('"certificates".id::text not in ((select "deliveredTgt"."targetId"');
+ expect(notFullyNotified.sql).toContain('having count(distinct "deliveredTgt"."channelId") >= ?');
+ expect(notFullyNotified.sql).not.toContain('"deliveredTgt"."targetId" = "certificates".id::text');
expect(notFullyNotified.sql).toMatch(/order by "certificates"\."notAfter" asc limit \?$/);
expect(notFullyNotified.bindings).toEqual(
- expect.arrayContaining(["alert-1", since, "success", "channel-1", "channel-2", 2, 1000])
+ expect.arrayContaining(["alert-1", "success", "channel-1", "channel-2", 2, 1000])
);
- expect(leastRecentlyNotified.sql).toContain('max("lastHist"."triggeredAt") as "lastDeliveredAt"');
- expect(leastRecentlyNotified.sql).toContain('group by "lastTgt"."targetId"');
+ expect(leastRecentlyNotified.sql).toContain('count(distinct "tgt"."channelId")');
+ expect(leastRecentlyNotified.sql).toContain('"hist"."triggeredAt" >= ?');
+ expect(leastRecentlyNotified.bindings).toEqual(expect.arrayContaining([since]));
+ expect(leastRecentlyNotified.sql).toContain('max("deliveredHist"."triggeredAt") as "lastDeliveredAt"');
+ expect(leastRecentlyNotified.sql).toContain('group by "deliveredTgt"."targetId"');
expect(leastRecentlyNotified.sql).toContain(
'order by "lastDelivered"."lastDeliveredAt" asc, "certificates"."notAfter" asc limit ?'
);
- expect(leastRecentlyNotified.sql).toContain('having count(distinct "lastTgt"."channelId") >= ?');
+ expect(leastRecentlyNotified.sql).toContain('having count(distinct "deliveredTgt"."channelId") >= ?');
});
test("findExpiringCertificates stops after the never-notified query when it fills the cap", async () => {
@@ -98,30 +101,6 @@ describe("cert manager certificate alert DAL", () => {
expect(queries).toHaveLength(1);
});
- test("findExpiringSignerCertificates scans each active signer's current certificate", async () => {
- const { dal, queries } = buildDAL();
-
- await dal.findExpiringSignerCertificates({
- projectId: PROJECT_ID,
- alertBeforeInterval: "30 days",
- leadInterval: "1 day",
- asOf: new Date("2026-01-02T00:00:00Z"),
- alreadyAlerted: { alertId: "alert-1", channelIds: ["channel-1"], since: new Date("2026-01-01T00:00:00Z") }
- });
-
- const [{ sql, bindings }] = queries;
- expect(sql).toContain('group by "pki_signers"."certificateId"');
- expect(sql).toContain('array_agg("pki_signers".name order by "pki_signers".name) as "signerNames"');
- expect(sql).toContain('as "signers" on "signers"."certificateId" = "certificates"."id"');
- expect(sql).toContain('"pki_signers"."projectId" = ?');
- expect(sql).toContain('"pki_signers"."status" = ?');
- expect(sql).toContain('not "certificates"."status" = ?');
- expect(sql).toContain('count(distinct "everTgt"."channelId")');
- expect(bindings).toEqual(expect.arrayContaining([PROJECT_ID, "active", "alert-1"]));
- expect(queries[1].sql).toContain('as "signers" on "signers"."certificateId" = "certificates"."id"');
- expect(queries[1].sql).toContain('"lastDelivered"."lastDeliveredAt" asc');
- });
-
test("findCertificatesByIds keeps event targets inside the alert's project and application", async () => {
const { dal, queries } = buildDAL();
@@ -164,7 +143,8 @@ describe("cert manager certificate alert DAL", () => {
profileIds: ["prof-1"],
alertBeforeInterval: "30 days",
leadInterval: "1 day",
- asOf: new Date("2026-01-01T00:00:00Z")
+ asOf: new Date("2026-01-01T00:00:00Z"),
+ alreadyAlerted: { alertId: "alert-1", channelIds: ["channel-1"], since: new Date("2026-01-01T00:00:00Z") }
});
const [{ sql, bindings }] = queries;
@@ -175,21 +155,6 @@ describe("cert manager certificate alert DAL", () => {
expect(bindings).toEqual(expect.arrayContaining(["app-1", "app-2", "prof-1"]));
});
- test("findExpiringCertificates adds no exclusion when the alert has no enabled channels", async () => {
- const { dal, queries } = buildDAL();
-
- await dal.findExpiringCertificates({
- projectId: PROJECT_ID,
- applicationId: APPLICATION_ID,
- alertBeforeInterval: "30 days",
- leadInterval: "1 day",
- asOf: new Date("2026-01-02T00:00:00Z"),
- alreadyAlerted: { alertId: "alert-1", channelIds: [], since: new Date() }
- });
-
- expect(queries[0].sql).not.toContain("count(distinct");
- });
-
test("findCertificatesByIds narrows a project-wide lookup by the profile list", async () => {
const { dal, queries } = buildDAL();
diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts b/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts
index 057d5702be..69a5657aab 100644
--- a/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts
+++ b/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts
@@ -5,7 +5,6 @@ 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";
export type TCertManagerApplicationAlertDALFactory = ReturnType<typeof certManagerApplicationAlertDALFactory>;
@@ -23,15 +22,13 @@ export type TApplicationAlertCertificate = {
revocationReason: number | null;
applicationId: string | null;
applicationName: string | null;
- signerIds?: string[];
- signerNames?: string[];
};
type TExpiryWindow = {
alertBeforeInterval: string;
leadInterval: string;
asOf: Date;
- alreadyAlerted?: TAlreadyAlertedFilter;
+ alreadyAlerted: TAlreadyAlertedFilter;
};
type TCertificateScope = {
@@ -43,120 +40,35 @@ type TCertificateScope = {
const MAX_EXPIRING_CERTIFICATES_PER_RUN = 1000;
-const applyCertificateScope = <TQuery extends Knex.QueryBuilder>(
- query: TQuery,
- { projectId, applicationId, applicationIds, profileIds }: TCertificateScope
-): TQuery => {
- void query.where(`${TableName.Certificate}.projectId`, projectId);
- if (applicationId) void query.where(`${TableName.Certificate}.applicationId`, applicationId);
- if (applicationIds?.length) void query.whereIn(`${TableName.Certificate}.applicationId`, applicationIds);
- if (profileIds?.length) void query.whereIn(`${TableName.Certificate}.profileId`, profileIds);
- return query;
-};
-
-const CERTIFICATE_TARGET_COLUMNS = [
- `${TableName.Certificate}.id`,
- `${TableName.Certificate}.serialNumber`,
- `${TableName.Certificate}.commonName`,
- `${TableName.Certificate}.altNames`,
- `${TableName.Certificate}.status`,
- `${TableName.Certificate}.notBefore`,
- `${TableName.Certificate}.notAfter`,
- `${TableName.Certificate}.revokedAt`,
- `${TableName.Certificate}.revocationReason`,
- `${TableName.Certificate}.applicationId`,
- `${TableName.Certificate}.profileId`,
- "profile.slug as profileName",
- `${TableName.PkiApplication}.name as applicationName`
-];
-
-const applyExpiryWindow = <TQuery extends Knex.QueryBuilder>(
- reader: Knex,
- query: TQuery,
- { alertBeforeInterval, leadInterval, asOf, alreadyAlerted }: TExpiryWindow
-): TQuery => {
- if (alreadyAlerted?.channelIds.length) {
- const deliveredChannelCount = reader(`${TableName.AlertHistory} as hist`)
- .join(`${TableName.AlertHistoryTarget} as tgt`, "hist.id", "tgt.alertHistoryId")
- .where("hist.alertId", alreadyAlerted.alertId)
- .where("hist.triggeredAt", ">=", alreadyAlerted.since)
- .where("tgt.status", AlertRunStatus.SUCCESS)
- .whereIn("tgt.channelId", alreadyAlerted.channelIds)
- .whereRaw(`"tgt"."targetId" = "${TableName.Certificate}".id::text`)
- .countDistinct("tgt.channelId");
- void query.whereRaw("(?) < ?", [deliveredChannelCount, alreadyAlerted.channelIds.length]);
- }
-
- void query
- .whereNot(`${TableName.Certificate}.status`, CertStatus.REVOKED)
- .whereRaw(`"${TableName.Certificate}"."notAfter" > ?::timestamptz`, [asOf])
- .whereRaw(`"${TableName.Certificate}"."notAfter" <= ?::timestamptz + ?::interval + ?::interval`, [
- asOf,
- alertBeforeInterval,
- leadInterval
- ]);
- return query;
-};
-
-const selectExpiring = async (
- reader: Knex,
- buildQuery: () => Knex.QueryBuilder,
- window: TExpiryWindow
-): Promise<TApplicationAlertCertificate[]> => {
- const { alreadyAlerted } = window;
- const dueQuery = () => applyExpiryWindow(reader, buildQuery(), window);
-
- if (!alreadyAlerted?.channelIds.length) {
- return (await dueQuery()
- .orderBy(`${TableName.Certificate}.notAfter`, "asc")
- .limit(MAX_EXPIRING_CERTIFICATES_PER_RUN)) as TApplicationAlertCertificate[];
- }
-
- const channelCount = alreadyAlerted.channelIds.length;
- const everDeliveredChannelCount = reader(`${TableName.AlertHistory} as everHist`)
- .join(`${TableName.AlertHistoryTarget} as everTgt`, "everHist.id", "everTgt.alertHistoryId")
- .where("everHist.alertId", alreadyAlerted.alertId)
- .where("everTgt.status", AlertRunStatus.SUCCESS)
- .whereIn("everTgt.channelId", alreadyAlerted.channelIds)
- .whereRaw(`"everTgt"."targetId" = "${TableName.Certificate}".id::text`)
- .countDistinct("everTgt.channelId");
- const notFullyNotified = (await dueQuery()
- .whereRaw("(?) < ?", [everDeliveredChannelCount, channelCount])
- .orderBy(`${TableName.Certificate}.notAfter`, "asc")
- .limit(MAX_EXPIRING_CERTIFICATES_PER_RUN)) as TApplicationAlertCertificate[];
- if (notFullyNotified.length >= MAX_EXPIRING_CERTIFICATES_PER_RUN) return notFullyNotified;
-
- const lastDelivered = reader(`${TableName.AlertHistory} as lastHist`)
- .join(`${TableName.AlertHistoryTarget} as lastTgt`, "lastHist.id", "lastTgt.alertHistoryId")
- .where("lastHist.alertId", alreadyAlerted.alertId)
- .where("lastTgt.status", AlertRunStatus.SUCCESS)
- .whereIn("lastTgt.channelId", alreadyAlerted.channelIds)
- .groupBy("lastTgt.targetId")
- .havingRaw(`count(distinct "lastTgt"."channelId") >= ?`, [channelCount])
- .select("lastTgt.targetId")
- .max("lastHist.triggeredAt as lastDeliveredAt");
- const leastRecentlyNotified = (await dueQuery()
- .joinRaw(`inner join (?) as "lastDelivered" on "lastDelivered"."targetId" = "${TableName.Certificate}".id::text`, [
- lastDelivered
- ])
- .orderBy("lastDelivered.lastDeliveredAt", "asc")
- .orderBy(`${TableName.Certificate}.notAfter`, "asc")
- .limit(MAX_EXPIRING_CERTIFICATES_PER_RUN - notFullyNotified.length)) as TApplicationAlertCertificate[];
-
- return [...notFullyNotified, ...leastRecentlyNotified];
-};
-
export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {
- const $selectCertificates = (reader: Knex, scope: TCertificateScope) => {
- const query = applyCertificateScope(
- reader(TableName.Certificate)
- .leftJoin(`${TableName.PkiCertificateProfile} as profile`, `${TableName.Certificate}.profileId`, "profile.id")
- .leftJoin(TableName.PkiApplication, `${TableName.Certificate}.applicationId`, `${TableName.PkiApplication}.id`),
- scope
- );
-
- return query.select(CERTIFICATE_TARGET_COLUMNS);
- };
+ const $selectCertificates = (
+ reader: Knex,
+ { projectId, applicationId, applicationIds, profileIds }: TCertificateScope
+ ) =>
+ reader(TableName.Certificate)
+ .leftJoin(`${TableName.PkiCertificateProfile} as profile`, `${TableName.Certificate}.profileId`, "profile.id")
+ .leftJoin(TableName.PkiApplication, `${TableName.Certificate}.applicationId`, `${TableName.PkiApplication}.id`)
+ .where(`${TableName.Certificate}.projectId`, projectId)
+ .modify((query) => {
+ if (applicationId) void query.where(`${TableName.Certificate}.applicationId`, applicationId);
+ if (applicationIds?.length) void query.whereIn(`${TableName.Certificate}.applicationId`, applicationIds);
+ if (profileIds?.length) void query.whereIn(`${TableName.Certificate}.profileId`, profileIds);
+ })
+ .select(
+ `${TableName.Certificate}.id`,
+ `${TableName.Certificate}.serialNumber`,
+ `${TableName.Certificate}.commonName`,
+ `${TableName.Certificate}.altNames`,
+ `${TableName.Certificate}.status`,
+ `${TableName.Certificate}.notBefore`,
+ `${TableName.Certificate}.notAfter`,
+ `${TableName.Certificate}.revokedAt`,
+ `${TableName.Certificate}.revocationReason`,
+ `${TableName.Certificate}.applicationId`,
+ `${TableName.Certificate}.profileId`,
+ "profile.slug as profileName",
+ `${TableName.PkiApplication}.name as applicationName`
+ );
const findExpiringCertificates = async (
scope: TCertificateScope & TExpiryWindow,
@@ -164,50 +76,69 @@ export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {
): Promise<TApplicationAlertCertificate[]> => {
try {
const reader = tx || db.replicaNode();
- return await selectExpiring(
- reader,
- () => $selectCertificates(reader, scope).whereNull(`${TableName.Certificate}.renewedByCertificateId`),
- scope
- );
+ 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];
} catch (error) {
throw new DatabaseError({ error, name: "FindExpiringCertificates" });
}
};
- const findExpiringSignerCertificates = async (
- scope: { projectId: string } & TExpiryWindow,
- tx?: Knex
- ): Promise<TApplicationAlertCertificate[]> => {
- try {
- const reader = tx || db.replicaNode();
- const activeSigners = reader(TableName.PkiSigners)
- .where(`${TableName.PkiSigners}.projectId`, scope.projectId)
- .where(`${TableName.PkiSigners}.status`, SignerStatus.Active)
- .whereNotNull(`${TableName.PkiSigners}.certificateId`)
- .groupBy(`${TableName.PkiSigners}.certificateId`)
- .select(`${TableName.PkiSigners}.certificateId`)
- .select(
- reader.raw(`array_agg("${TableName.PkiSigners}".id order by "${TableName.PkiSigners}".name) as "signerIds"`),
- reader.raw(
- `array_agg("${TableName.PkiSigners}".name order by "${TableName.PkiSigners}".name) as "signerNames"`
- )
- );
- const buildQuery = () =>
- reader(TableName.Certificate)
- .join(activeSigners.clone().as("signers"), "signers.certificateId", `${TableName.Certificate}.id`)
- .leftJoin(`${TableName.PkiCertificateProfile} as profile`, `${TableName.Certificate}.profileId`, "profile.id")
- .leftJoin(
- TableName.PkiApplication,
- `${TableName.Certificate}.applicationId`,
- `${TableName.PkiApplication}.id`
- )
- .select([...CERTIFICATE_TARGET_COLUMNS, "signers.signerIds", "signers.signerNames"]);
- return await selectExpiring(reader, buildQuery, scope);
- } catch (error) {
- throw new DatabaseError({ error, name: "FindExpiringSignerCertificates" });
- }
- };
-
const findCertificatesByIds = async (
scope: TCertificateScope & { certificateIds: string[] },
tx?: Knex
@@ -306,7 +237,6 @@ export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {
return {
findExpiringCertificates,
- findExpiringSignerCertificates,
findCertificatesByIds,
findApplicationById,
findApplicationNamesByIds,
diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-provider.test.ts b/backend/src/services/alert/providers/cert-manager-application-alert-provider.test.ts
index 35d8e798bf..c05e7afc50 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
@@ -19,7 +19,6 @@ const RESOURCE_TYPE = "cert-manager.application";
const EXPIRY_EVENT = "cert-manager.application.certificate.expiry";
const ISSUANCE_EVENT = "cert-manager.application.certificate.issuance";
const REVOCATION_EVENT = "cert-manager.application.certificate.revocation";
-const SIGNER_EXPIRY_EVENT = "cert-manager.signer-certificate.expiry";
const APPLICATION_ID = "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90";
const OTHER_APPLICATION_ID = "6c8e4a1f-9b2d-4f3c-8e7a-2b3c4d5e6f70";
const PROFILE_ID = "7d9f5b2a-0c3e-4a4d-9f8b-3c4d5e6f7081";
@@ -59,7 +58,6 @@ const buildProvider = (opts?: {
application?: { id: string; name: string; projectId: string; orgId: string };
certificates?: TApplicationAlertCertificate[];
onFindExpiring?: (args: Record<string, unknown>) => void;
- onFindExpiringSigners?: (args: Record<string, unknown>) => void;
onFindByIds?: (args: Record<string, unknown>) => void;
onFindNames?: (ids: string[], orgId: string) => void;
onFindApplicationIds?: (ids: string[]) => void;
@@ -85,10 +83,6 @@ const buildProvider = (opts?: {
opts?.onFindExpiring?.(args);
return opts?.certificates ?? [];
},
- findExpiringSignerCertificates: async (args: Record<string, unknown>) => {
- opts?.onFindExpiringSigners?.(args);
- return opts?.certificates ?? [];
- },
findCertificatesByIds: async (args: Record<string, unknown>) => {
opts?.onFindByIds?.(args);
return opts?.certificates ?? [];
@@ -203,6 +197,28 @@ describe("cert manager application alert provider", () => {
});
});
+ test("findScheduledTargets scans nothing when the alert has no channel to deliver to", async () => {
+ let scanned = false;
+ const { provider } = buildProvider({
+ onFindExpiring: () => {
+ scanned = true;
+ }
+ });
+
+ const targets = await provider.findScheduledTargets({
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: null,
+ eventType: EXPIRY_EVENT,
+ condition: { alertBefore: "2w" },
+ asOf: new Date(),
+ alreadyAlerted: { alertId: "alert-1", channelIds: [], since: new Date() }
+ });
+
+ expect(targets).toEqual([]);
+ expect(scanned).toBe(false);
+ });
+
test("findScheduledTargets converts alertBefore to days and scopes the scan to the alert's application", async () => {
let args: Record<string, unknown> | undefined;
const { provider } = buildProvider({
@@ -216,7 +232,8 @@ describe("cert manager application alert provider", () => {
resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",
eventType: EXPIRY_EVENT,
condition: { alertBefore: "2w" },
- asOf: new Date()
+ asOf: new Date(),
+ alreadyAlerted: { alertId: "alert-1", channelIds: ["channel-1"], since: new Date() }
});
expect(args).toMatchObject({
projectId: "proj-1",
@@ -242,7 +259,8 @@ describe("cert manager application alert provider", () => {
resourceId: null,
eventType: EXPIRY_EVENT,
condition: { alertBefore: "2w", profileIds: [PROFILE_ID] },
- asOf: new Date()
+ asOf: new Date(),
+ alreadyAlerted: { alertId: "alert-1", channelIds: ["channel-1"], since: new Date() }
});
await provider.findEventTargets({
orgId: "org-1",
@@ -287,6 +305,7 @@ describe("cert manager application alert provider", () => {
expect(payload.webhookType).toBe(`com.infisical.${EXPIRY_EVENT}`);
expect(payload.eventKey).toBe(EXPIRY_EVENT);
expect(payload.webhookSource).toBe(`/applications/${alertContext().resourceId}/alerts/alert-1`);
+ expect(payload.alert.resourceType).toBe(RESOURCE_TYPE);
expect(payload.alert.resourceId).toBe(alertContext().resourceId);
expect(payload.severity).toBe("critical");
expect(payload.items[0]).toMatchObject({ id: "cert-1", title: "api.example.com" });
@@ -429,6 +448,8 @@ describe("cert manager application alert provider", () => {
);
expect(payload.resourceOwnerKind).toBe("Certificate Manager");
+ expect(payload.alert.resourceType).toBe("cert-manager");
+ expect(payload.alert).not.toHaveProperty("resourceId");
expect(payload.webhookSource).toBe("/alerts/alert-1");
expect(payload.eventKey).toBe("cert-manager.certificate.expiry");
expect(payload.webhookType).toBe("com.infisical.cert-manager.certificate.expiry");
@@ -771,145 +792,4 @@ describe("cert manager application alert provider", () => {
}
});
});
-
- describe("signer certificate expiration", () => {
- const signerCertificate = sampleCertificate({
- id: "cert-signer",
- commonName: "release signing",
- altNames: null,
- applicationId: null,
- applicationName: null,
- signerIds: ["signer-1"],
- signerNames: ["release-signer"]
- });
- const signerAlert = alertContext({
- resourceId: null,
- eventType: SIGNER_EXPIRY_EVENT,
- condition: { alertBefore: "30d" }
- });
-
- test("is a scheduled event that takes only alertBefore and dailyReminder", () => {
- const event = buildProvider().provider.events.find((candidate) => candidate.key === SIGNER_EXPIRY_EVENT)!;
- expect(event.triggerType).toBe("scheduled");
- expect(event.conditionSchema.safeParse({ alertBefore: "30d", dailyReminder: true }).success).toBe(true);
- expect(event.conditionSchema.safeParse({ alertBefore: "30d", applicationIds: [APPLICATION_ID] }).success).toBe(
- false
- );
- expect(event.conditionSchema.safeParse({ alertBefore: "400d" }).success).toBe(false);
- });
-
- test("scans the active certificate of every signer and never an application", async () => {
- let signerArgs: Record<string, unknown> | undefined;
- let certificateScan = false;
- const { provider } = buildProvider({
- certificates: [signerCertificate],
- onFindExpiringSigners: (args) => {
- signerArgs = args;
- },
- onFindExpiring: () => {
- certificateScan = true;
- }
- });
- const asOf = new Date("2026-10-01T00:00:00.000Z");
-
- const targets = await provider.findScheduledTargets({
- orgId: "org-1",
- projectId: "proj-1",
- resourceId: null,
- eventType: SIGNER_EXPIRY_EVENT,
- condition: { alertBefore: "2w" },
- asOf
- });
-
- expect(targets).toEqual([signerCertificate]);
- expect(certificateScan).toBe(false);
- expect(signerArgs).toMatchObject({ projectId: "proj-1", alertBeforeInterval: "14 days", asOf });
- await expect(
- provider.findScheduledTargets({
- orgId: "org-1",
- projectId: "proj-1",
- resourceId: APPLICATION_ID,
- eventType: SIGNER_EXPIRY_EVENT,
- condition: { alertBefore: "2w" },
- asOf
- })
- ).resolves.toEqual([]);
- });
-
- test("creating or editing one requires a project admin and refuses an application", async () => {
- const create = {
- action: AlertPermissionAction.Create,
- orgId: "org-1",
- projectId: "proj-1",
- eventType: SIGNER_EXPIRY_EVENT,
- actor
- };
- const alertRules = [
- { action: "create", subject: "pki-alerts" },
- { action: "edit", subject: "pki-alerts" },
- { action: "read", subject: "pki-alerts" }
- ];
-
- await expect(
- buildProvider({ abilityRules: alertRules, projectRoles: ["admin"] }).provider.assertPermission(create)
- ).resolves.toBeUndefined();
- await expect(
- buildProvider({
- abilityRules: [...alertRules, { action: "read", subject: "code-signers" }],
- projectRoles: ["member"]
- }).provider.assertPermission(create)
- ).rejects.toThrow("only Certificate Manager admins");
- await expect(
- buildProvider({
- abilityRules: [...alertRules, { action: "read", subject: "code-signers" }]
- }).provider.assertPermission({ ...create, action: AlertPermissionAction.Edit })
- ).rejects.toThrow("only Certificate Manager admins");
- await expect(
- buildProvider({ abilityRules: alertRules }).provider.assertPermission({
- ...create,
- action: AlertPermissionAction.Read
- })
- ).resolves.toBeUndefined();
- await expect(
- buildProvider({ abilityRules: alertRules, projectRoles: ["admin"] }).provider.assertPermission({
- ...create,
- resourceId: APPLICATION_ID
- })
- ).rejects.toThrow("can't be bound to an application");
- });
-
- test("buildPayload names the signer and links to Code Signing", async () => {
- const { provider } = buildProvider();
- const viewUrl = await provider.buildViewUrl(signerAlert);
- const payload = provider.buildPayload(signerAlert, [signerCertificate], viewUrl);
-
- expect(viewUrl).toBe("https://app.infisical.com/organizations/org-1/projects/cert-manager/proj-1/code-signing");
- expect(payload.resourceKind).toBe("Signer Certificate");
- expect(payload.eventKey).toBe("cert-manager.signer-certificate.expiry");
- expect(payload.webhookType).toBe("com.infisical.cert-manager.signer-certificate.expiry");
- expect(payload.eventLabel).toBe("Expiration");
- expect(payload.resourceOwnerKind).toBe("Certificate Manager");
- expect(payload.summary).toBe("1 signer certificate expiring within 30 days");
- expect(payload.items[0].summary).toMatch(/^Certificate 'release signing' of signer 'release-signer' expires on /);
- expect(payload.items[0].fields?.[0]).toEqual({ label: "Signer", value: "release-signer" });
- expect(payload.items[0].resource).toMatchObject({ signerIds: ["signer-1"], signerNames: ["release-signer"] });
- expect(provider.dedupWindowHours?.({ alertBefore: "30d" })).toBe(44);
- });
-
- test("a certificate shared by several signers is one item naming every signer", async () => {
- const { provider } = buildProvider();
- const sharedCertificate = {
- ...signerCertificate,
- signerIds: ["signer-1", "signer-2"],
- signerNames: ["build-signer", "release-signer"]
- };
- const payload = provider.buildPayload(signerAlert, [sharedCertificate], await provider.buildViewUrl(signerAlert));
-
- expect(payload.items).toHaveLength(1);
- expect(payload.items[0].summary).toMatch(
- /^Certificate 'release signing' of signers 'build-signer', 'release-signer' expires on /
- );
- expect(payload.items[0].fields?.[0]).toEqual({ label: "Signers", value: "build-signer, release-signer" });
- });
- });
});
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.ts
index e6e50828e1..d53c8c558b 100644
--- a/backend/src/services/alert/providers/cert-manager-application-alert-provider.ts
+++ b/backend/src/services/alert/providers/cert-manager-application-alert-provider.ts
@@ -1,12 +1,11 @@
import { ForbiddenError, MongoAbility } from "@casl/ability";
import { z } from "zod";
-import { ActionProjectType, ProjectMembershipRole, ResourceType } from "@app/db/schemas";
+import { ActionProjectType, ResourceType } from "@app/db/schemas";
import { Event as TAuditEvent, EventType } from "@app/ee/services/audit-log/audit-log-types";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
- ProjectPermissionActions,
ProjectPermissionCertificateActions,
ProjectPermissionSet,
ProjectPermissionSub
@@ -17,19 +16,17 @@ import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/
import { TCertManagerProjectResolverFactory } from "@app/services/cert-manager-instance/cert-manager-project-resolver";
import {
CERT_MANAGER_APPLICATION_RESOURCE_TYPE,
- CertificateAlertEvent,
- CodeSigningAlertEvent
+ CertificateAlertEvent
} from "@app/services/certificate/certificate-alert-events";
import { getRevocationReasonLabel } from "@app/services/pki-alert-v2/pki-alert-v2-types";
-import { PkiAlertScope, PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+import { PkiAlertScope } from "@app/services/telemetry/telemetry-types";
-import { AlertChannelType, TAlertPayload, TAlertSeverity } from "../alert-channel-types";
+import { TAlertPayload, TAlertSeverity } from "../alert-channel-types";
import { durationToDays, expirySeverity, formatUtcDate, humanizeDays } from "../alert-format-fns";
import {
ALERT_SCAN_LEAD_INTERVAL,
AlertAuditAction,
AlertPermissionAction,
- AlertTelemetryAction,
AlertTriggerType,
DEFAULT_DEDUP_WINDOW_HOURS,
IEventAlertProvider,
@@ -43,6 +40,17 @@ import {
TFindEventTargetsInput,
TFindScheduledTargetsInput
} from "../alert-types";
+import {
+ assertCertManagerAlertChannelTypesAllowed,
+ buildCertificateManagerAlertAuditEvent,
+ buildPkiAlertTelemetryEvent,
+ CERT_MANAGER_ALERT_PERMISSION_ACTIONS,
+ certificateDisplayName,
+ expirationDedupWindowHours,
+ ExpiryFieldsSchema,
+ resolveCertManagerProjectId,
+ splitAltNames
+} from "./cert-manager-alert-fns";
import {
TApplicationAlertCertificate,
TCertManagerApplicationAlertDALFactory
@@ -50,28 +58,16 @@ import {
const MAX_CERTIFICATE_ALERT_FILTER_IDS = 100;
-type TCertManagerAlertEvent = CertificateAlertEvent | CodeSigningAlertEvent;
-
-const toCertificateManagerEventKey = (eventType: TCertManagerAlertEvent) =>
- eventType.replace(`${CERT_MANAGER_APPLICATION_RESOURCE_TYPE}.`, "cert-manager.");
+const CERT_MANAGER_DELIVERY_RESOURCE_TYPE = "cert-manager";
-const isExpiryEvent = (eventType: TCertManagerAlertEvent) =>
- eventType === CertificateAlertEvent.Expiry || eventType === CodeSigningAlertEvent.SignerCertificateExpiry;
+const toCertificateManagerEventKey = (eventType: CertificateAlertEvent) =>
+ eventType.replace(`${CERT_MANAGER_APPLICATION_RESOURCE_TYPE}.`, `${CERT_MANAGER_DELIVERY_RESOURCE_TYPE}.`);
-const TELEMETRY_ALERT_TYPE_BY_EVENT: Record<TCertManagerAlertEvent, string> = {
+const TELEMETRY_ALERT_TYPE_BY_EVENT: Record<CertificateAlertEvent, string> = {
[CertificateAlertEvent.Expiry]: "expiration",
[CertificateAlertEvent.Issuance]: "issuance",
[CertificateAlertEvent.Renewal]: "renewal",
- [CertificateAlertEvent.Revocation]: "revocation",
- [CodeSigningAlertEvent.SignerCertificateExpiry]: "signer-certificate-expiration"
-};
-
-const MIN_CERTIFICATE_ALERT_BEFORE_DAYS = 1;
-const MAX_CERTIFICATE_ALERT_BEFORE_DAYS = 365;
-
-const isValidAlertBefore = (alertBefore: string): boolean => {
- const days = durationToDays(alertBefore);
- return days >= MIN_CERTIFICATE_ALERT_BEFORE_DAYS && days <= MAX_CERTIFICATE_ALERT_BEFORE_DAYS;
+ [CertificateAlertEvent.Revocation]: "revocation"
};
const filterIdsSchema = (field: string, noun: string) =>
@@ -101,22 +97,8 @@ const CertificateFilterSchema = z.object({
profileIds: filterIdsSchema("profileIds", "profile")
});
-const ExpiryFieldsSchema = z.object({
- alertBefore: z
- .string()
- .refine(
- isValidAlertBefore,
- `Must be a number of days, weeks, months or years adding up to ${MIN_CERTIFICATE_ALERT_BEFORE_DAYS} to ${MAX_CERTIFICATE_ALERT_BEFORE_DAYS} days, e.g. '30d' or '2w'`
- ),
- dailyReminder: z.boolean().optional()
-});
-
const ExpirationConditionSchema = ExpiryFieldsSchema.merge(CertificateFilterSchema).strict();
-const SignerExpirationConditionSchema = ExpiryFieldsSchema.strict(
- "Signer certificate expiration alerts cover every signer and take no filters. Remove applicationIds and profileIds."
-);
-
const EventConditionSchema = CertificateFilterSchema.strict().nullish();
const assertValidApplicationId = (applicationId: string) => {
@@ -125,56 +107,37 @@ const assertValidApplicationId = (applicationId: string) => {
}
};
-const EVENT_LABELS: Record<TCertManagerAlertEvent, string> = {
+const EVENT_LABELS: Record<CertificateAlertEvent, string> = {
[CertificateAlertEvent.Expiry]: "Expiration",
[CertificateAlertEvent.Issuance]: "Issuance",
[CertificateAlertEvent.Renewal]: "Renewal",
- [CertificateAlertEvent.Revocation]: "Revocation",
- [CodeSigningAlertEvent.SignerCertificateExpiry]: "Expiration"
+ [CertificateAlertEvent.Revocation]: "Revocation"
};
-const EVENT_VERBS: Record<TCertManagerAlertEvent, string> = {
+const EVENT_VERBS: Record<CertificateAlertEvent, string> = {
[CertificateAlertEvent.Expiry]: "is expiring",
[CertificateAlertEvent.Issuance]: "was issued",
[CertificateAlertEvent.Renewal]: "was renewed",
- [CertificateAlertEvent.Revocation]: "was revoked",
- [CodeSigningAlertEvent.SignerCertificateExpiry]: "is expiring"
+ [CertificateAlertEvent.Revocation]: "was revoked"
};
-const PERMISSION_ACTIONS: Record<AlertPermissionAction, ProjectPermissionActions> = {
- [AlertPermissionAction.Read]: ProjectPermissionActions.Read,
- [AlertPermissionAction.Create]: ProjectPermissionActions.Create,
- [AlertPermissionAction.Edit]: ProjectPermissionActions.Edit,
- [AlertPermissionAction.Delete]: ProjectPermissionActions.Delete
-};
-
-const eventSeverity = (eventType: TCertManagerAlertEvent, targets: TApplicationAlertCertificate[]): TAlertSeverity => {
- if (isExpiryEvent(eventType)) return expirySeverity(targets.map((target) => target.notAfter));
+const eventSeverity = (eventType: CertificateAlertEvent, targets: TApplicationAlertCertificate[]): TAlertSeverity => {
+ if (eventType === CertificateAlertEvent.Expiry) return expirySeverity(targets.map((target) => target.notAfter));
if (eventType === CertificateAlertEvent.Revocation) return "warning";
return "info";
};
-const splitAltNames = (altNames: string | null): string[] =>
- (altNames ?? "")
- .split(",")
- .map((name) => name.trim())
- .filter(Boolean);
-
-const certificateDisplayName = (certificate: TApplicationAlertCertificate): string =>
- certificate.commonName || splitAltNames(certificate.altNames)[0] || certificate.serialNumber;
-
const inApplication = (applicationName?: string | null) =>
applicationName ? ` in application '${applicationName}'` : "";
const buildSummary = (
- eventType: TCertManagerAlertEvent,
+ eventType: CertificateAlertEvent,
targets: TApplicationAlertCertificate[],
applicationName: string | null,
alertBefore?: string
): string => {
if (alertBefore) {
- const noun = eventType === CodeSigningAlertEvent.SignerCertificateExpiry ? "signer certificate" : "certificate";
- const certificates = `${targets.length} ${noun}${targets.length === 1 ? "" : "s"}`;
+ const certificates = `${targets.length} certificate${targets.length === 1 ? "" : "s"}`;
return `${certificates}${inApplication(applicationName)} expiring within ${humanizeDays(durationToDays(alertBefore))}`;
}
if (targets.length === 1) {
@@ -183,30 +146,13 @@ const buildSummary = (
return `${targets.length} certificates ${EVENT_VERBS[eventType]}${inApplication(applicationName)}`;
};
-const formatSigners = (signerNames: string[] = []) =>
- `${signerNames.length === 1 ? "signer" : "signers"} ${signerNames.map((name) => `'${name}'`).join(", ")}`;
-
-const buildItemSummary = (eventType: TCertManagerAlertEvent, certificate: TApplicationAlertCertificate): string => {
- if (eventType === CodeSigningAlertEvent.SignerCertificateExpiry) {
- return `Certificate '${certificateDisplayName(certificate)}' of ${formatSigners(certificate.signerNames)} expires on ${formatUtcDate(certificate.notAfter)}`;
- }
+const buildItemSummary = (eventType: CertificateAlertEvent, certificate: TApplicationAlertCertificate): string => {
if (eventType === CertificateAlertEvent.Expiry) {
return `Certificate '${certificateDisplayName(certificate)}'${inApplication(certificate.applicationName)} expires on ${formatUtcDate(certificate.notAfter)}`;
}
return `Certificate '${certificateDisplayName(certificate)}' ${EVENT_VERBS[eventType]}${inApplication(certificate.applicationName)}`;
};
-const DAILY_SCAN_DEDUP_MARGIN_HOURS = 4;
-
-const dayMultipleDedupWindowHours = (days: number): number => days * 24 - DAILY_SCAN_DEDUP_MARGIN_HOURS;
-
-const expirationDedupWindowHours = (days: number, dailyReminder?: boolean): number => {
- if (dailyReminder || days <= 7) return dayMultipleDedupWindowHours(1);
- if (days <= 30) return dayMultipleDedupWindowHours(2);
- if (days <= 90) return dayMultipleDedupWindowHours(7);
- return dayMultipleDedupWindowHours(30);
-};
-
const formatIds = (ids: string[]) => ids.map((id) => `'${id}'`).join(", ");
const toIdSet = (ids: string[] = []) => new Set(ids.map((id) => id.toLowerCase()));
@@ -235,25 +181,13 @@ export const certManagerApplicationAlertProviderFactory = ({
IEventAlertProvider<TApplicationAlertCertificate> => {
const buildViewUrl = async (alert: TAlertContext): Promise<string> => {
const base = `${getConfig().SITE_URL}/organizations/${alert.orgId}/projects/cert-manager/${alert.projectId}`;
- if (alert.eventType === CodeSigningAlertEvent.SignerCertificateExpiry) return `${base}/code-signing`;
if (!alert.resourceId) return `${base}/inventory`;
const application = await certManagerApplicationAlertDAL.findApplicationById(alert.resourceId);
return application ? `${base}/applications/${encodeURIComponent(application.name)}` : `${base}/applications`;
};
const findScheduledTargets = async (input: TFindScheduledTargetsInput): Promise<TApplicationAlertCertificate[]> => {
- if (!input.projectId) return [];
- if (input.eventType === CodeSigningAlertEvent.SignerCertificateExpiry) {
- if (input.resourceId) return [];
- const { alertBefore } = SignerExpirationConditionSchema.parse(input.condition);
- return certManagerApplicationAlertDAL.findExpiringSignerCertificates({
- projectId: input.projectId,
- alertBeforeInterval: `${durationToDays(alertBefore)} days`,
- leadInterval: ALERT_SCAN_LEAD_INTERVAL,
- asOf: input.asOf,
- alreadyAlerted: input.alreadyAlerted
- });
- }
+ if (!input.projectId || !input.alreadyAlerted?.channelIds.length) return [];
const { alertBefore, applicationIds, profileIds } = ExpirationConditionSchema.parse(input.condition);
return certManagerApplicationAlertDAL.findExpiringCertificates({
@@ -289,13 +223,13 @@ export const certManagerApplicationAlertProviderFactory = ({
targets: TApplicationAlertCertificate[],
viewUrl: string
): TAlertPayload => {
- const eventType = alert.eventType as TCertManagerAlertEvent;
+ const eventType = alert.eventType as CertificateAlertEvent;
const isApplicationAlert = Boolean(alert.resourceId);
- const isSignerAlert = eventType === CodeSigningAlertEvent.SignerCertificateExpiry;
const deliveryEventKey = isApplicationAlert ? eventType : toCertificateManagerEventKey(eventType);
- const alertBefore = isExpiryEvent(eventType)
- ? (alert.condition as { alertBefore?: string } | null)?.alertBefore
- : undefined;
+ const alertBefore =
+ eventType === CertificateAlertEvent.Expiry
+ ? (alert.condition as { alertBefore?: string } | null)?.alertBefore
+ : undefined;
return {
alert: {
@@ -303,7 +237,7 @@ export const certManagerApplicationAlertProviderFactory = ({
name: alert.name,
orgId: alert.orgId,
...(alert.projectId ? { projectId: alert.projectId } : {}),
- resourceType: alert.resourceType,
+ resourceType: isApplicationAlert ? alert.resourceType : CERT_MANAGER_DELIVERY_RESOURCE_TYPE,
...(alert.resourceId ? { resourceId: alert.resourceId } : {}),
...(alertBefore ? { condition: alertBefore } : {}),
viewUrl
@@ -312,7 +246,7 @@ export const certManagerApplicationAlertProviderFactory = ({
eventLabel: EVENT_LABELS[eventType],
webhookType: `com.infisical.${deliveryEventKey}`,
webhookSource: getWebhookSource({ alertId: alert.id, resourceId: alert.resourceId }),
- resourceKind: isSignerAlert ? "Signer Certificate" : "Certificate",
+ resourceKind: "Certificate",
resourceOwnerKind: isApplicationAlert ? "Application" : "Certificate Manager",
severity: eventSeverity(eventType, targets),
summary: buildSummary(
@@ -333,14 +267,6 @@ export const certManagerApplicationAlertProviderFactory = ({
summary: buildItemSummary(eventType, certificate),
severity: eventSeverity(eventType, [certificate]),
fields: [
- ...(isSignerAlert && certificate.signerNames?.length
- ? [
- {
- label: certificate.signerNames.length === 1 ? "Signer" : "Signers",
- value: certificate.signerNames.join(", ")
- }
- ]
- : []),
{ label: "Serial Number", value: certificate.serialNumber },
...(altNames.length ? [{ label: "SANs", value: altNames.join(", ") }] : []),
...(certificate.profileName ? [{ label: "Profile", value: certificate.profileName }] : []),
@@ -363,8 +289,7 @@ export const certManagerApplicationAlertProviderFactory = ({
profileId: certificate.profileId,
profileName: certificate.profileName,
applicationId: certificate.applicationId,
- applicationName: certificate.applicationName,
- ...(isSignerAlert ? { signerIds: certificate.signerIds, signerNames: certificate.signerNames } : {})
+ applicationName: certificate.applicationName
}
};
})
@@ -373,40 +298,19 @@ export const certManagerApplicationAlertProviderFactory = ({
const getCertificateManagerAuditEvent = (input: TAlertAuditInput): 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 buildCertificateManagerAlertAuditEvent(input, { applications: [], profiles: [] });
}
-
- const { alert } = input;
- const { applicationIds = [], profileIds = [] } = parseFilters(alert.condition);
+ const { applicationIds = [], profileIds = [] } = parseFilters(input.alert.condition);
const nameById = new Map(
- Object.values(alert.filters ?? {})
+ Object.values(input.alert.filters ?? {})
.flat()
.map((resource) => [resource.id, resource.name])
);
const withNames = (ids: string[]) => ids.map((id) => ({ id, name: nameById.get(id) ?? null }));
- const metadata = {
- alertId: alert.id,
- name: alert.name,
- eventType: alert.eventType,
+ return buildCertificateManagerAlertAuditEvent(input, {
applications: withNames(applicationIds),
profiles: withNames(profileIds)
- };
- if (input.action === AlertAuditAction.Create) return { type: EventType.CREATE_CERTIFICATE_MANAGER_ALERT, metadata };
- if (input.action === AlertAuditAction.Update) return { type: EventType.UPDATE_CERTIFICATE_MANAGER_ALERT, metadata };
- return { type: EventType.DELETE_CERTIFICATE_MANAGER_ALERT, metadata };
+ });
};
const getAuditEvent = (input: TAlertAuditInput): TAuditEvent => {
@@ -459,29 +363,19 @@ export const certManagerApplicationAlertProviderFactory = ({
? { applicationId: resourceId, alertScope: PkiAlertScope.Application }
: { alertScope: PkiAlertScope.CertificateManager })
};
- switch (action) {
- case AlertTelemetryAction.Create:
- return {
- event: PostHogEventTypes.PkiAlertCreated,
- properties: {
- ...properties,
- alertType: TELEMETRY_ALERT_TYPE_BY_EVENT[eventType as TCertManagerAlertEvent]
- }
- };
- case AlertTelemetryAction.Update:
- return { event: PostHogEventTypes.PkiAlertUpdated, properties };
- default:
- return { event: PostHogEventTypes.PkiAlertDeleted, properties };
- }
+ return buildPkiAlertTelemetryEvent(
+ action,
+ properties,
+ TELEMETRY_ALERT_TYPE_BY_EVENT[eventType as CertificateAlertEvent]
+ );
};
const $assertCertificateManagerPermission = async ({
action,
projectId,
- eventType,
actor
}: TAlertPermissionInput & { projectId: string }) => {
- const { permission, hasRole } = await permissionService.getProjectPermission({
+ const { permission } = await permissionService.getProjectPermission({
actor: actor.actor,
actorId: actor.actorId,
projectId,
@@ -489,21 +383,14 @@ export const certManagerApplicationAlertProviderFactory = ({
actorOrgId: actor.actorOrgId,
actionProjectType: ActionProjectType.CertificateManager
});
- ForbiddenError.from(permission).throwUnlessCan(PERMISSION_ACTIONS[action], ProjectPermissionSub.PkiAlerts);
+ ForbiddenError.from(permission).throwUnlessCan(
+ CERT_MANAGER_ALERT_PERMISSION_ACTIONS[action],
+ ProjectPermissionSub.PkiAlerts
+ );
const definesDelivery = action === AlertPermissionAction.Create || action === AlertPermissionAction.Edit;
if (!definesDelivery) return;
- if (eventType === CodeSigningAlertEvent.SignerCertificateExpiry) {
- if (!hasRole(ProjectMembershipRole.Admin)) {
- throw new ForbiddenRequestError({
- message:
- "Signer certificate expiration alerts send certificate details from every signer, so only Certificate Manager admins can create or edit them."
- });
- }
- return;
- }
-
if (
!isUnconditionalGrant(
permission.rulesFor(ProjectPermissionCertificateActions.Read, ProjectPermissionSub.Certificates)
@@ -517,18 +404,11 @@ export const certManagerApplicationAlertProviderFactory = ({
};
const assertPermission = async (input: TAlertPermissionInput): Promise<void> => {
- const { action, projectId, resourceId, eventType, actor } = input;
+ const { action, projectId, resourceId, actor } = input;
if (!projectId) {
throw new BadRequestError({ message: "Certificate alerts must be created in Certificate Manager" });
}
- if (resourceId && eventType === CodeSigningAlertEvent.SignerCertificateExpiry) {
- throw new BadRequestError({
- message:
- "Signer certificate expiration alerts cover every signer in Certificate Manager and can't be bound to an application. Remove resourceId."
- });
- }
-
if (!resourceId) {
await $assertCertificateManagerPermission({ ...input, projectId });
return;
@@ -544,7 +424,10 @@ export const certManagerApplicationAlertProviderFactory = ({
actorAuthMethod: actor.actorAuthMethod,
actorOrgId: actor.actorOrgId
});
- ForbiddenError.from(permission).throwUnlessCan(PERMISSION_ACTIONS[action], ResourcePermissionSub.PkiAlerts);
+ ForbiddenError.from(permission).throwUnlessCan(
+ CERT_MANAGER_ALERT_PERMISSION_ACTIONS[action],
+ ResourcePermissionSub.PkiAlerts
+ );
};
const assertResourceInScope = async (input: {
@@ -639,13 +522,7 @@ export const certManagerApplicationAlertProviderFactory = ({
};
const resolveProjectId = async ({ orgId, resourceId }: { orgId: string; resourceId?: string | null }) => {
- if (!resourceId) {
- const projectId = await certManagerProjectResolver.getActiveProjectId(orgId);
- if (!projectId) {
- throw new NotFoundError({ message: "Certificate Manager isn't set up for this organization" });
- }
- return projectId;
- }
+ if (!resourceId) return resolveCertManagerProjectId(certManagerProjectResolver, orgId);
assertValidApplicationId(resourceId);
const application = await certManagerApplicationAlertDAL.findApplicationById(resourceId);
if (!application || application.orgId !== orgId) {
@@ -654,18 +531,6 @@ export const certManagerApplicationAlertProviderFactory = ({
return application.projectId;
};
- const assertChannelTypesAllowed = async ({ orgId, channelTypes }: { orgId: string; channelTypes: string[] }) => {
- const gatedType = channelTypes.find((channelType) => channelType !== AlertChannelType.EMAIL);
- if (!gatedType) return;
-
- const plan = await licenseService.getPlan(orgId);
- if (!plan.pkiEnterpriseAlerting) {
- throw new BadRequestError({
- message: `Failed to save a ${gatedType} channel due to plan restriction. Upgrade plan to alert on channels other than email, or disable or remove the ${gatedType} channel.`
- });
- }
- };
-
return {
resourceType: CERT_MANAGER_APPLICATION_RESOURCE_TYPE,
supportsScopeWideAlerts: true,
@@ -675,11 +540,6 @@ export const certManagerApplicationAlertProviderFactory = ({
triggerType: AlertTriggerType.Scheduled,
conditionSchema: ExpirationConditionSchema
},
- {
- key: CodeSigningAlertEvent.SignerCertificateExpiry,
- triggerType: AlertTriggerType.Scheduled,
- conditionSchema: SignerExpirationConditionSchema
- },
...[CertificateAlertEvent.Issuance, CertificateAlertEvent.Renewal, CertificateAlertEvent.Revocation].map(
(key) => ({
key,
@@ -702,7 +562,7 @@ export const certManagerApplicationAlertProviderFactory = ({
assertPermission,
assertResourceInScope,
assertConditionInScope,
- assertChannelTypesAllowed,
+ assertChannelTypesAllowed: (input) => assertCertManagerAlertChannelTypesAllowed(licenseService, input),
recipientPolicy: { atOrgScope: true, allowEmailAddresses: true },
includeLastRun: true,
getAuditEvent,
diff --git a/backend/src/services/alert/providers/cert-manager-signer-alert-dal.test.ts b/backend/src/services/alert/providers/cert-manager-signer-alert-dal.test.ts
new file mode 100644
index 0000000000..425ba6c319
--- /dev/null
+++ b/backend/src/services/alert/providers/cert-manager-signer-alert-dal.test.ts
@@ -0,0 +1,77 @@
+import knex, { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+
+import { certManagerSignerAlertDALFactory } from "./cert-manager-signer-alert-dal";
+
+const PROJECT_ID = "3f2d7a4e-1b6c-4d8e-9a0f-5c7b2e1d4a6b";
+
+const buildDAL = (firstQueryRows: unknown[] = []) => {
+ const builder = knex({ client: "pg" });
+ const queries: { sql: string; bindings: readonly unknown[] }[] = [];
+
+ const reader = ((table: string) => {
+ const query = builder(table);
+ return Object.assign(query, {
+ then: (resolve: (rows: unknown[]) => void) => {
+ const { sql, bindings } = query.toSQL();
+ queries.push({ sql, bindings });
+ resolve(queries.length === 1 ? firstQueryRows : []);
+ }
+ });
+ }) as unknown as Knex;
+ Object.assign(reader, { raw: builder.raw.bind(builder) });
+
+ const db = Object.assign(reader, { replicaNode: () => reader }) as unknown as TDbClient;
+ return { dal: certManagerSignerAlertDALFactory(db), queries };
+};
+
+const scope = {
+ projectId: PROJECT_ID,
+ alertBeforeInterval: "30 days",
+ leadInterval: "1 day",
+ asOf: new Date("2026-01-02T00:00:00Z"),
+ alreadyAlerted: { alertId: "alert-1", channelIds: ["channel-1"], since: new Date("2026-01-01T00:00:00Z") }
+};
+
+describe("cert manager signer alert DAL", () => {
+ test("scans one row per certificate an active signer uses, naming every signer of it", async () => {
+ const { dal, queries } = buildDAL();
+
+ await dal.findExpiringSignerCertificates(scope);
+
+ expect(queries).toHaveLength(2);
+ const [{ sql, bindings }] = queries;
+ expect(sql).toContain('group by "pki_signers"."certificateId"');
+ expect(sql).toContain('array_agg("pki_signers".name order by "pki_signers".name) as "signerNames"');
+ expect(sql).toContain('as "signers" on "signers"."certificateId" = "certificates"."id"');
+ expect(sql).toContain('"pki_signers"."projectId" = ?');
+ expect(sql).toContain('"pki_signers"."status" = ?');
+ expect(sql).toContain('not "certificates"."status" = ?');
+ expect(sql).toContain('"certificates".id::text not in ((select "deliveredTgt"."targetId"');
+ expect(sql).toContain('having count(distinct "deliveredTgt"."channelId") >= ?');
+ expect(sql).toMatch(/order by "certificates"\."notAfter" asc limit \?$/);
+ expect(bindings).toEqual(expect.arrayContaining([PROJECT_ID, "active", "alert-1"]));
+ });
+
+ test("fills the rest of the run with certificates delivered on every channel, least recently first", async () => {
+ const { dal, queries } = buildDAL();
+
+ await dal.findExpiringSignerCertificates(scope);
+
+ const { sql, bindings } = queries[1];
+ expect(sql).toContain('having count(distinct "deliveredTgt"."channelId") >= ?');
+ expect(sql).toContain('"hist"."triggeredAt" >= ?');
+ expect(sql).toContain('order by "lastDelivered"."lastDeliveredAt" asc, "certificates"."notAfter" asc limit ?');
+ expect(bindings).toEqual(expect.arrayContaining([scope.alreadyAlerted.since]));
+ });
+
+ test("stops after the first query when it fills the cap", async () => {
+ const { dal, queries } = buildDAL(Array.from({ length: 1000 }, (_, index) => ({ id: `cert-${index}` })));
+
+ const certificates = await dal.findExpiringSignerCertificates(scope);
+
+ expect(certificates).toHaveLength(1000);
+ expect(queries).toHaveLength(1);
+ });
+});
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.ts
new file mode 100644
index 0000000000..184322415c
--- /dev/null
+++ b/backend/src/services/alert/providers/cert-manager-signer-alert-dal.ts
@@ -0,0 +1,134 @@
+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";
+
+export type TCertManagerSignerAlertDALFactory = ReturnType<typeof certManagerSignerAlertDALFactory>;
+
+export type TSignerAlertCertificate = {
+ id: string;
+ serialNumber: string;
+ commonName: string;
+ altNames: string | null;
+ status: string;
+ notBefore: Date;
+ notAfter: Date;
+ signerIds: string[];
+ signerNames: string[];
+};
+
+const MAX_EXPIRING_SIGNER_CERTIFICATES_PER_RUN = 1000;
+
+export const certManagerSignerAlertDALFactory = (db: TDbClient) => {
+ const $selectSignerCertificates = (reader: Knex, projectId: string) =>
+ reader(TableName.Certificate)
+ .join(
+ reader(TableName.PkiSigners)
+ .where(`${TableName.PkiSigners}.projectId`, projectId)
+ .where(`${TableName.PkiSigners}.status`, SignerStatus.Active)
+ .whereNotNull(`${TableName.PkiSigners}.certificateId`)
+ .groupBy(`${TableName.PkiSigners}.certificateId`)
+ .select(`${TableName.PkiSigners}.certificateId`)
+ .select(
+ reader.raw(
+ `array_agg("${TableName.PkiSigners}".id order by "${TableName.PkiSigners}".name) as "signerIds"`
+ ),
+ reader.raw(
+ `array_agg("${TableName.PkiSigners}".name order by "${TableName.PkiSigners}".name) as "signerNames"`
+ )
+ )
+ .as("signers"),
+ "signers.certificateId",
+ `${TableName.Certificate}.id`
+ )
+ .select(
+ `${TableName.Certificate}.id`,
+ `${TableName.Certificate}.serialNumber`,
+ `${TableName.Certificate}.commonName`,
+ `${TableName.Certificate}.altNames`,
+ `${TableName.Certificate}.status`,
+ `${TableName.Certificate}.notBefore`,
+ `${TableName.Certificate}.notAfter`,
+ "signers.signerIds",
+ "signers.signerNames"
+ );
+
+ const findExpiringSignerCertificates = async (
+ scope: {
+ projectId: string;
+ alertBeforeInterval: string;
+ leadInterval: string;
+ asOf: Date;
+ alreadyAlerted: TAlreadyAlertedFilter;
+ },
+ 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];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindExpiringSignerCertificates" });
+ }
+ };
+
+ return { 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.ts
new file mode 100644
index 0000000000..473515e53f
--- /dev/null
+++ b/backend/src/services/alert/providers/cert-manager-signer-alert-provider.test.ts
@@ -0,0 +1,238 @@
+import { createMongoAbility } from "@casl/ability";
+import { vi } from "vitest";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { PkiAlertScope, PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+
+import { AlertChannelType } from "../alert-channel-types";
+import { AlertAuditAction, AlertPermissionAction, AlertTelemetryAction, TAlertContext } from "../alert-types";
+import { TSignerAlertCertificate } from "./cert-manager-signer-alert-dal";
+import {
+ certManagerSignerAlertProviderFactory,
+ TCertManagerSignerAlertProviderDep
+} from "./cert-manager-signer-alert-provider";
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ SITE_URL: "https://app.infisical.com" })
+}));
+
+const RESOURCE_TYPE = "cert-manager.signer";
+const EXPIRY_EVENT = "cert-manager.signer.certificate.expiry";
+const APPLICATION_ID = "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90";
+
+const NOT_AFTER = new Date(Date.now() + 10 * 24 * 60 * 60 * 1000);
+
+const signerCertificate = (overrides: Partial<TSignerAlertCertificate> = {}): TSignerAlertCertificate => ({
+ id: "cert-signer",
+ serialNumber: "0a1b2c",
+ commonName: "release signing",
+ altNames: null,
+ status: "active",
+ notBefore: new Date("2026-01-01T00:00:00.000Z"),
+ notAfter: NOT_AFTER,
+ signerIds: ["signer-1"],
+ signerNames: ["release-signer"],
+ ...overrides
+});
+
+const signerAlert: TAlertContext = {
+ id: "alert-1",
+ name: "signer-expiry",
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceType: RESOURCE_TYPE,
+ resourceId: null,
+ eventType: EXPIRY_EVENT,
+ condition: { alertBefore: "30d" }
+};
+
+const alreadyAlerted = { alertId: "alert-1", channelIds: ["channel-1"], since: new Date() };
+
+const actor = { actor: "user", actorId: "u1", actorAuthMethod: null, actorOrgId: "org-1" } as never;
+
+const alertRules = [
+ { action: "create", subject: "pki-alerts" },
+ { action: "edit", subject: "pki-alerts" },
+ { action: "read", subject: "pki-alerts" }
+];
+
+const buildProvider = (opts?: {
+ certificates?: TSignerAlertCertificate[];
+ onFindExpiring?: (args: Record<string, unknown>) => void;
+ abilityRules?: { action: string; subject: string }[];
+ projectRoles?: string[];
+ pkiEnterpriseAlerting?: boolean;
+}) =>
+ certManagerSignerAlertProviderFactory({
+ certManagerSignerAlertDAL: {
+ findExpiringSignerCertificates: async (args: Record<string, unknown>) => {
+ opts?.onFindExpiring?.(args);
+ return opts?.certificates ?? [];
+ }
+ },
+ permissionService: {
+ getProjectPermission: async () => ({
+ permission: createMongoAbility((opts?.abilityRules ?? alertRules) as never),
+ hasRole: (role: string) => (opts?.projectRoles ?? []).includes(role)
+ })
+ },
+ licenseService: { getPlan: async () => ({ pkiEnterpriseAlerting: opts?.pkiEnterpriseAlerting ?? false }) },
+ certManagerProjectResolver: { getActiveProjectId: async (orgId: string) => (orgId === "org-1" ? "proj-1" : null) }
+ } as unknown as TCertManagerSignerAlertProviderDep);
+
+describe("cert manager signer alert provider", () => {
+ test("owns one scheduled event that takes only alertBefore and dailyReminder", () => {
+ const provider = buildProvider();
+ expect(provider.resourceType).toBe(RESOURCE_TYPE);
+ expect(provider.events.map((event) => event.key)).toEqual([EXPIRY_EVENT]);
+
+ const [event] = provider.events;
+ expect(event.triggerType).toBe("scheduled");
+ expect(event.conditionSchema.safeParse({ alertBefore: "30d", dailyReminder: true }).success).toBe(true);
+ expect(event.conditionSchema.safeParse({ alertBefore: "30d", applicationIds: [APPLICATION_ID] }).success).toBe(
+ false
+ );
+ expect(event.conditionSchema.safeParse({ alertBefore: "400d" }).success).toBe(false);
+ });
+
+ test("scans every active signer's certificate, and nothing for a bound alert or one with no channels", async () => {
+ let scanArgs: Record<string, unknown> | undefined;
+ const provider = buildProvider({
+ certificates: [signerCertificate()],
+ onFindExpiring: (args) => {
+ scanArgs = args;
+ }
+ });
+ const asOf = new Date("2026-10-01T00:00:00.000Z");
+ const input = {
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: null,
+ eventType: EXPIRY_EVENT,
+ condition: { alertBefore: "2w" },
+ asOf,
+ alreadyAlerted
+ };
+
+ await expect(provider.findScheduledTargets(input)).resolves.toEqual([signerCertificate()]);
+ expect(scanArgs).toMatchObject({ projectId: "proj-1", alertBeforeInterval: "14 days", asOf, alreadyAlerted });
+ await expect(provider.findScheduledTargets({ ...input, resourceId: APPLICATION_ID })).resolves.toEqual([]);
+ await expect(
+ provider.findScheduledTargets({ ...input, alreadyAlerted: { ...alreadyAlerted, channelIds: [] } })
+ ).resolves.toEqual([]);
+ });
+
+ test("creating or editing one requires a project admin, reading and deleting only PKI alert access", async () => {
+ const create = { action: AlertPermissionAction.Create, orgId: "org-1", projectId: "proj-1", actor };
+
+ await expect(buildProvider({ projectRoles: ["admin"] }).assertPermission(create)).resolves.toBeUndefined();
+ await expect(
+ buildProvider({
+ abilityRules: [...alertRules, { action: "read", subject: "code-signers" }],
+ projectRoles: ["member"]
+ }).assertPermission(create)
+ ).rejects.toThrow("only Certificate Manager admins");
+ await expect(buildProvider().assertPermission({ ...create, action: AlertPermissionAction.Edit })).rejects.toThrow(
+ "only Certificate Manager admins"
+ );
+ await expect(
+ buildProvider().assertPermission({ ...create, action: AlertPermissionAction.Read })
+ ).resolves.toBeUndefined();
+ await expect(
+ buildProvider({ abilityRules: [], projectRoles: ["admin"] }).assertPermission(create)
+ ).rejects.toThrow();
+ });
+
+ test("refuses a resource everywhere a caller can name one", async () => {
+ const provider = buildProvider({ projectRoles: ["admin"] });
+ const bound = { action: AlertPermissionAction.Create, orgId: "org-1", projectId: "proj-1", actor };
+
+ await expect(provider.assertPermission({ ...bound, resourceId: APPLICATION_ID })).rejects.toThrow(
+ "can't be bound to a resource"
+ );
+ await expect(provider.assertResourceInScope({ orgId: "org-1", resourceId: APPLICATION_ID })).rejects.toThrow(
+ "can't be bound to a resource"
+ );
+ await expect(provider.resolveProjectId?.({ orgId: "org-1", resourceId: APPLICATION_ID })).rejects.toThrow(
+ "can't be bound to a resource"
+ );
+ await expect(provider.resolveProjectId?.({ orgId: "org-1" })).resolves.toBe("proj-1");
+ await expect(provider.resolveProjectId?.({ orgId: "org-2" })).rejects.toThrow("Certificate Manager isn't set up");
+ });
+
+ test("buildPayload names the signer, links to Code Signing, and delivers under its own key", async () => {
+ const provider = buildProvider();
+ const viewUrl = await provider.buildViewUrl(signerAlert);
+ const payload = provider.buildPayload(signerAlert, [signerCertificate()], viewUrl);
+
+ expect(viewUrl).toBe("https://app.infisical.com/organizations/org-1/projects/cert-manager/proj-1/code-signing");
+ expect(payload.eventKey).toBe(EXPIRY_EVENT);
+ expect(payload.webhookType).toBe(`com.infisical.${EXPIRY_EVENT}`);
+ expect(payload.webhookSource).toBe("/alerts/alert-1");
+ expect(payload.resourceKind).toBe("Signer Certificate");
+ expect(payload.resourceOwnerKind).toBe("Certificate Manager");
+ expect(payload.eventLabel).toBe("Expiration");
+ expect(payload.summary).toBe("1 signer certificate expiring within 30 days");
+ expect(payload.items[0].summary).toMatch(/^Certificate 'release signing' of signer 'release-signer' expires on /);
+ expect(payload.items[0].fields?.[0]).toEqual({ label: "Signer", value: "release-signer" });
+ expect(payload.items[0].resource).toMatchObject({ signerIds: ["signer-1"], signerNames: ["release-signer"] });
+ expect(provider.dedupWindowHours?.({ alertBefore: "30d" })).toBe(44);
+ expect(provider.dedupWindowHours?.({ alertBefore: "30d", dailyReminder: true })).toBe(20);
+ });
+
+ test("a certificate shared by several signers is one item naming every signer", () => {
+ const payload = buildProvider().buildPayload(
+ signerAlert,
+ [signerCertificate({ signerIds: ["signer-1", "signer-2"], signerNames: ["build-signer", "release-signer"] })],
+ "https://example.com"
+ );
+
+ expect(payload.items).toHaveLength(1);
+ expect(payload.items[0].summary).toMatch(
+ /^Certificate 'release signing' of signers 'build-signer', 'release-signer' expires on /
+ );
+ 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", () => {
+ 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: [] }
+ });
+ expect(
+ provider.getTelemetryEvent?.({
+ action: AlertTelemetryAction.Create,
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: null,
+ eventType: EXPIRY_EVENT
+ })
+ ).toEqual({
+ event: PostHogEventTypes.PkiAlertCreated,
+ properties: {
+ orgId: "org-1",
+ projectId: "proj-1",
+ alertScope: PkiAlertScope.CertificateManager,
+ alertType: "signer-certificate-expiration"
+ }
+ });
+ });
+
+ test("gates channels other than email on the enterprise alerting plan", async () => {
+ await expect(
+ buildProvider().assertChannelTypesAllowed?.({ orgId: "org-1", channelTypes: [AlertChannelType.WEBHOOK] })
+ ).rejects.toThrow("plan restriction");
+ await expect(
+ buildProvider().assertChannelTypesAllowed?.({ orgId: "org-1", channelTypes: [AlertChannelType.EMAIL] })
+ ).resolves.toBeUndefined();
+ await expect(
+ buildProvider({ pkiEnterpriseAlerting: true }).assertChannelTypesAllowed?.({
+ orgId: "org-1",
+ channelTypes: [AlertChannelType.WEBHOOK]
+ })
+ ).resolves.toBeUndefined();
+ });
+});
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.ts
new file mode 100644
index 0000000000..0e0dd64723
--- /dev/null
+++ b/backend/src/services/alert/providers/cert-manager-signer-alert-provider.ts
@@ -0,0 +1,206 @@
+import { ForbiddenError } from "@casl/ability";
+
+import { ActionProjectType, ProjectMembershipRole } from "@app/db/schemas";
+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
+import { getConfig } from "@app/lib/config/env";
+import { BadRequestError, ForbiddenRequestError } from "@app/lib/errors";
+import { TCertManagerProjectResolverFactory } from "@app/services/cert-manager-instance/cert-manager-project-resolver";
+import { CERT_MANAGER_SIGNER_RESOURCE_TYPE, SignerAlertEvent } from "@app/services/signer/signer-alert-events";
+import { PkiAlertScope } from "@app/services/telemetry/telemetry-types";
+
+import { TAlertPayload } from "../alert-channel-types";
+import { durationToDays, expirySeverity, formatUtcDate, humanizeDays } from "../alert-format-fns";
+import {
+ ALERT_SCAN_LEAD_INTERVAL,
+ AlertPermissionAction,
+ AlertTriggerType,
+ DEFAULT_DEDUP_WINDOW_HOURS,
+ IScheduledAlertProvider,
+ TAlertContext,
+ TAlertPermissionInput,
+ TAlertTelemetryInput,
+ TFindScheduledTargetsInput
+} from "../alert-types";
+import {
+ assertCertManagerAlertChannelTypesAllowed,
+ buildCertificateManagerAlertAuditEvent,
+ buildPkiAlertTelemetryEvent,
+ CERT_MANAGER_ALERT_PERMISSION_ACTIONS,
+ certificateDisplayName,
+ expirationDedupWindowHours,
+ ExpiryFieldsSchema,
+ resolveCertManagerProjectId,
+ splitAltNames
+} from "./cert-manager-alert-fns";
+import { TCertManagerSignerAlertDALFactory, TSignerAlertCertificate } from "./cert-manager-signer-alert-dal";
+
+const SignerExpirationConditionSchema = ExpiryFieldsSchema.strict();
+
+const assertNoResource = (resourceId?: string | null) => {
+ if (resourceId) {
+ throw new BadRequestError({
+ message:
+ "Signer certificate expiration alerts cover every signer in Certificate Manager and can't be bound to a resource. Remove resourceId."
+ });
+ }
+};
+
+const getWebhookSource = ({ alertId }: { alertId: string }) => `/alerts/${alertId}`;
+
+const formatSigners = (signerNames: string[]) =>
+ `${signerNames.length === 1 ? "signer" : "signers"} ${signerNames.map((name) => `'${name}'`).join(", ")}`;
+
+export type TCertManagerSignerAlertProviderDep = {
+ certManagerSignerAlertDAL: TCertManagerSignerAlertDALFactory;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+ certManagerProjectResolver: Pick<TCertManagerProjectResolverFactory, "getActiveProjectId">;
+};
+
+export const certManagerSignerAlertProviderFactory = ({
+ certManagerSignerAlertDAL,
+ permissionService,
+ licenseService,
+ certManagerProjectResolver
+}: TCertManagerSignerAlertProviderDep): IScheduledAlertProvider<TSignerAlertCertificate> => {
+ const findScheduledTargets = async (input: TFindScheduledTargetsInput): Promise<TSignerAlertCertificate[]> => {
+ if (!input.projectId || input.resourceId || !input.alreadyAlerted?.channelIds.length) return [];
+ const { alertBefore } = SignerExpirationConditionSchema.parse(input.condition);
+
+ return certManagerSignerAlertDAL.findExpiringSignerCertificates({
+ projectId: input.projectId,
+ alertBeforeInterval: `${durationToDays(alertBefore)} days`,
+ leadInterval: ALERT_SCAN_LEAD_INTERVAL,
+ asOf: input.asOf,
+ alreadyAlerted: input.alreadyAlerted
+ });
+ };
+
+ const buildViewUrl = async (alert: TAlertContext): Promise<string> =>
+ `${getConfig().SITE_URL}/organizations/${alert.orgId}/projects/cert-manager/${alert.projectId}/code-signing`;
+
+ const buildPayload = (alert: TAlertContext, targets: TSignerAlertCertificate[], viewUrl: string): TAlertPayload => {
+ const { alertBefore } = alert.condition as { alertBefore: string };
+
+ return {
+ alert: {
+ id: alert.id,
+ name: alert.name,
+ orgId: alert.orgId,
+ ...(alert.projectId ? { projectId: alert.projectId } : {}),
+ resourceType: alert.resourceType,
+ condition: alertBefore,
+ viewUrl
+ },
+ eventKey: SignerAlertEvent.CertificateExpiry,
+ eventLabel: "Expiration",
+ webhookType: `com.infisical.${SignerAlertEvent.CertificateExpiry}`,
+ webhookSource: getWebhookSource({ alertId: alert.id }),
+ resourceKind: "Signer Certificate",
+ resourceOwnerKind: "Certificate Manager",
+ severity: expirySeverity(targets.map((target) => target.notAfter)),
+ summary: `${targets.length} signer certificate${targets.length === 1 ? "" : "s"} expiring within ${humanizeDays(durationToDays(alertBefore))}`,
+ items: targets.map((certificate) => {
+ const altNames = splitAltNames(certificate.altNames);
+ return {
+ id: certificate.id,
+ title: certificateDisplayName(certificate),
+ summary: `Certificate '${certificateDisplayName(certificate)}' of ${formatSigners(certificate.signerNames)} expires on ${formatUtcDate(certificate.notAfter)}`,
+ severity: expirySeverity([certificate.notAfter]),
+ fields: [
+ {
+ label: certificate.signerNames.length === 1 ? "Signer" : "Signers",
+ value: certificate.signerNames.join(", ")
+ },
+ { label: "Serial Number", value: certificate.serialNumber },
+ ...(altNames.length ? [{ label: "SANs", value: altNames.join(", ") }] : []),
+ { label: "Expires", value: formatUtcDate(certificate.notAfter) }
+ ],
+ resource: {
+ id: certificate.id,
+ serialNumber: certificate.serialNumber,
+ commonName: certificate.commonName,
+ altNames,
+ status: certificate.status,
+ notBefore: certificate.notBefore.toISOString(),
+ notAfter: certificate.notAfter.toISOString(),
+ signerIds: certificate.signerIds,
+ signerNames: certificate.signerNames
+ }
+ };
+ })
+ };
+ };
+
+ const assertPermission = async ({ action, projectId, resourceId, actor }: TAlertPermissionInput): Promise<void> => {
+ if (!projectId) {
+ throw new BadRequestError({ message: "Signer alerts must be created in Certificate Manager" });
+ }
+ assertNoResource(resourceId);
+
+ const { permission, hasRole } = await permissionService.getProjectPermission({
+ actor: actor.actor,
+ actorId: actor.actorId,
+ projectId,
+ actorAuthMethod: actor.actorAuthMethod,
+ actorOrgId: actor.actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ CERT_MANAGER_ALERT_PERMISSION_ACTIONS[action],
+ ProjectPermissionSub.PkiAlerts
+ );
+
+ const definesDelivery = action === AlertPermissionAction.Create || action === AlertPermissionAction.Edit;
+ if (definesDelivery && !hasRole(ProjectMembershipRole.Admin)) {
+ throw new ForbiddenRequestError({
+ message:
+ "Signer certificate expiration alerts send certificate details from every signer, so only Certificate Manager admins can create or edit them."
+ });
+ }
+ };
+
+ const getTelemetryEvent = ({ action, orgId, projectId }: TAlertTelemetryInput) => {
+ if (!projectId) return undefined;
+ return buildPkiAlertTelemetryEvent(
+ action,
+ { orgId, projectId, alertScope: PkiAlertScope.CertificateManager },
+ "signer-certificate-expiration"
+ );
+ };
+
+ return {
+ resourceType: CERT_MANAGER_SIGNER_RESOURCE_TYPE,
+ supportsScopeWideAlerts: true,
+ events: [
+ {
+ key: SignerAlertEvent.CertificateExpiry,
+ triggerType: AlertTriggerType.Scheduled,
+ conditionSchema: SignerExpirationConditionSchema
+ }
+ ],
+ findScheduledTargets,
+ buildViewUrl,
+ buildPayload,
+ targetId: (certificate) => certificate.id,
+ dedupWindowHours: (condition) => {
+ const parsed = SignerExpirationConditionSchema.safeParse(condition);
+ if (!parsed.success) return DEFAULT_DEDUP_WINDOW_HOURS;
+ return expirationDedupWindowHours(durationToDays(parsed.data.alertBefore), parsed.data.dailyReminder);
+ },
+ assertPermission,
+ assertResourceInScope: async ({ resourceId }) => assertNoResource(resourceId),
+ assertChannelTypesAllowed: (input) => assertCertManagerAlertChannelTypesAllowed(licenseService, input),
+ recipientPolicy: { atOrgScope: true, allowEmailAddresses: true },
+ includeLastRun: true,
+ getAuditEvent: (input) => buildCertificateManagerAlertAuditEvent(input, { applications: [], profiles: [] }),
+ getWebhookSource,
+ getTelemetryEvent,
+ resolveProjectId: async ({ orgId, resourceId }) => {
+ assertNoResource(resourceId);
+ return resolveCertManagerProjectId(certManagerProjectResolver, orgId);
+ }
+ };
+};
diff --git a/backend/src/services/certificate/certificate-alert-events.ts b/backend/src/services/certificate/certificate-alert-events.ts
index b4ff147b84..9f5feea73e 100644
--- a/backend/src/services/certificate/certificate-alert-events.ts
+++ b/backend/src/services/certificate/certificate-alert-events.ts
@@ -13,10 +13,6 @@ export enum CertificateAlertEvent {
Revocation = "cert-manager.application.certificate.revocation"
}
-export enum CodeSigningAlertEvent {
- SignerCertificateExpiry = "cert-manager.signer-certificate.expiry"
-}
-
export const getIssuanceAlertEvent = (isRenewal?: boolean) =>
isRenewal ? CertificateAlertEvent.Renewal : CertificateAlertEvent.Issuance;
diff --git a/backend/src/services/signer/signer-alert-events.ts b/backend/src/services/signer/signer-alert-events.ts
new file mode 100644
index 0000000000..70436ccde0
--- /dev/null
+++ b/backend/src/services/signer/signer-alert-events.ts
@@ -0,0 +1,5 @@
+export const CERT_MANAGER_SIGNER_RESOURCE_TYPE = "cert-manager.signer";
+
+export enum SignerAlertEvent {
+ CertificateExpiry = "cert-manager.signer.certificate.expiry"
+}
diff --git a/backend/src/services/smtp/emails/AlertNotificationTemplate.tsx b/backend/src/services/smtp/emails/AlertNotificationTemplate.tsx
index a79e854aa0..0391fd67e0 100644
--- a/backend/src/services/smtp/emails/AlertNotificationTemplate.tsx
+++ b/backend/src/services/smtp/emails/AlertNotificationTemplate.tsx
@@ -12,6 +12,7 @@ interface AlertNotificationTemplateProps extends Omit<BaseEmailWrapperProps, "ti
severity?: string;
viewUrl: string;
items: { id: string; title: string; identifier?: string; fields?: { label: string; value: string }[] }[];
+ remainingCount?: number;
}
const SEVERITY_STYLES: Record<string, { label: string; color: string; background: string; border: string }> = {
@@ -30,7 +31,8 @@ export const AlertNotificationTemplate = ({
severity = "info",
viewUrl,
siteUrl,
- items
+ items,
+ remainingCount = 0
}: AlertNotificationTemplateProps) => {
const title = `${resourceKind} ${eventLabel} Notice`;
const sev = SEVERITY_STYLES[severity] ?? SEVERITY_STYLES.info;
@@ -81,6 +83,11 @@ export const AlertNotificationTemplate = ({
))}
</Section>
))}
+ {remainingCount > 0 && (
+ <Text className="text-[13px] text-gray-600 text-center m-0 mt-[4px]">
+ And {remainingCount} more. View them all in Infisical.
+ </Text>
+ )}
</Section>
<Section className="text-center mt-[28px] mb-[4px]">
diff --git a/docs/documentation/platform/pki/settings/alerts.mdx b/docs/documentation/platform/pki/settings/alerts.mdx
index aca4cd7178..b24bb1316b 100644
--- a/docs/documentation/platform/pki/settings/alerts.mdx
+++ b/docs/documentation/platform/pki/settings/alerts.mdx
@@ -75,12 +75,12 @@ Only each signer's current certificate counts. When you reissue a signer's certi
| `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.application`, with no `resourceId` |
+ | `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 sends `cert-manager.signer-certificate.expiry` as its `subject` (`type` is `com.infisical.cert-manager.signer-certificate.expiry`), opens **Code Signing** from `data.metadata.viewUrl`, and adds a `Signer` field (`Signers` when several signers share the certificate) plus `signerIds` and `signerNames` to each item.
+ 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.
</Accordion>
</AccordionGroup>
diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.ts
index 1c9a249811..f14d9a4465 100644
--- a/frontend/src/hooks/api/alerts/types.ts
+++ b/frontend/src/hooks/api/alerts/types.ts
@@ -29,7 +29,8 @@ export enum AlertRunStatus {
}
export enum CertificateAlertResourceType {
- Application = "cert-manager.application"
+ Application = "cert-manager.application",
+ Signer = "cert-manager.signer"
}
export enum CertificateAlertEventType {
@@ -37,7 +38,7 @@ export enum CertificateAlertEventType {
Issuance = "cert-manager.application.certificate.issuance",
Renewal = "cert-manager.application.certificate.renewal",
Revocation = "cert-manager.application.certificate.revocation",
- SignerCertificateExpiry = "cert-manager.signer-certificate.expiry"
+ SignerCertificateExpiry = "cert-manager.signer.certificate.expiry"
}
export const MIN_ALERT_BEFORE_DAYS = 1;
@@ -140,7 +141,6 @@ export type TTestAlertChannelDTO = {
resourceId?: string | null;
projectId?: string | null;
alertId?: string;
- eventType?: string;
channelId?: string;
channelType: AlertChannelType;
config?: Record<string, unknown>;
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx
index f61ca310d6..32bf9c9e4c 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx
@@ -1,5 +1,6 @@
import { useState } from "react";
import {
+ AlertTriangleIcon,
BellIcon,
CircleStopIcon,
EyeIcon,
@@ -13,6 +14,9 @@ import {
import { createNotification } from "@app/components/notifications";
import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
Badge,
Button,
Card,
@@ -300,11 +304,33 @@ export const ApplicationAlertsCard = ({
{ label: "Actions", className: "w-5 text-right" }
];
const resourceId = getAlertResourceId(scope);
- const { data: alerts = [], isLoading: isAlertsLoading } = useListAlerts({
+ const {
+ data: certificateAlerts = [],
+ isLoading: isCertificateAlertsLoading,
+ isError: isCertificateAlertsError
+ } = useListAlerts({
resourceType: CertificateAlertResourceType.Application,
projectId,
...(resourceId ? { resourceId } : {})
});
+ const {
+ data: signerAlerts = [],
+ isLoading: isSignerAlertsLoading,
+ isError: isSignerAlertsError
+ } = useListAlerts(
+ { resourceType: CertificateAlertResourceType.Signer, projectId },
+ { enabled: scope.kind === CertificateAlertScopeKind.CertificateManager }
+ );
+ const alerts =
+ scope.kind === CertificateAlertScopeKind.CertificateManager
+ ? [...certificateAlerts, ...signerAlerts]
+ : certificateAlerts;
+ const isAlertsLoading =
+ isCertificateAlertsLoading ||
+ (scope.kind === CertificateAlertScopeKind.CertificateManager && isSignerAlertsLoading);
+ const isAlertsError =
+ isCertificateAlertsError ||
+ (scope.kind === CertificateAlertScopeKind.CertificateManager && isSignerAlertsError);
const usedEventTypes =
scope.kind === CertificateAlertScopeKind.Application
? alerts.map((alert) => alert.eventType as CertificateAlertEventType)
@@ -381,13 +407,24 @@ export const ApplicationAlertsCard = ({
</CardAction>
</CardHeader>
<CardContent>
+ {isAlertsError && (
+ <Alert variant="warning" className="mb-4">
+ <AlertTriangleIcon />
+ <AlertTitle>Some alerts could not be loaded</AlertTitle>
+ <AlertDescription>
+ Reload the page to try again. Alerts that failed to load aren&apos;t listed below.
+ </AlertDescription>
+ </Alert>
+ )}
{!isAlertsLoading && alerts.length === 0 ? (
- <Empty className="border">
- <EmptyMedia variant="icon">
- <BellIcon />
- </EmptyMedia>
- <EmptyDescription>{config.emptyDescription}</EmptyDescription>
- </Empty>
+ !isAlertsError && (
+ <Empty className="border">
+ <EmptyMedia variant="icon">
+ <BellIcon />
+ </EmptyMedia>
+ <EmptyDescription>{config.emptyDescription}</EmptyDescription>
+ </Empty>
+ )
) : (
<Table>
<TableHeader>
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx
index 121ec99d42..c14fc49148 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx
@@ -27,7 +27,6 @@ import { useGetOrgUsers } from "@app/hooks/api";
import {
AlertChannelType,
CertificateAlertEventType,
- CertificateAlertResourceType,
TAlert,
toChannelInput,
useCreateAlert,
@@ -46,6 +45,7 @@ import {
CertificateAlertStep,
emptyCertificateAlertForm,
getAlertResourceId,
+ getAlertResourceType,
getSteps,
STEP_FIELDS,
TCertificateAlertForm,
@@ -124,7 +124,7 @@ const CertificateAlertWizard = ({
await createAlert.mutateAsync({
name: values.name,
description: values.description || undefined,
- resourceType: CertificateAlertResourceType.Application,
+ resourceType: getAlertResourceType(values.eventType),
resourceId: getAlertResourceId(scope),
eventType: values.eventType,
condition,
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx
index 69763d7470..6a548007be 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx
@@ -13,15 +13,12 @@ import {
} from "@app/components/v3";
import { useSubscription } from "@app/context";
import { isValidEmail } from "@app/helpers/email";
-import {
- AlertChannelType,
- AlertPrincipalType,
- CertificateAlertResourceType
-} from "@app/hooks/api/alerts";
+import { AlertChannelType, AlertPrincipalType } from "@app/hooks/api/alerts";
import { AddChannelMenu, ChannelCard, TChannelRecipientsRenderProps } from "@app/views/Alerts";
import {
getAlertResourceId,
+ getAlertResourceType,
MAX_CHANNELS,
normalizeEmail,
TCertificateAlertForm,
@@ -174,10 +171,9 @@ export const ChannelsStep = ({
key={field.id}
index={index}
projectId={projectId}
- resourceType={CertificateAlertResourceType.Application}
+ resourceType={getAlertResourceType(eventType)}
resourceId={getAlertResourceId(scope)}
alertId={alertId}
- eventType={eventType}
canRemove
onRemove={() => onRemove(index)}
renderRecipients={(props) => <EmailRecipientsField {...props} members={members} />}
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts
index 886ce0eff6..1556572e06 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
import {
AlertPrincipalType,
CertificateAlertEventType,
+ CertificateAlertResourceType,
channelFormSchema,
MAX_CERTIFICATE_ALERT_BEFORE_DAYS,
MAX_CERTIFICATE_ALERT_FILTER_IDS,
@@ -79,6 +80,11 @@ export const isExpiryEventType = (eventType: CertificateAlertEventType) =>
export const isFilterableEventType = (eventType: CertificateAlertEventType) =>
eventType !== CertificateAlertEventType.SignerCertificateExpiry;
+export const getAlertResourceType = (eventType: CertificateAlertEventType) =>
+ eventType === CertificateAlertEventType.SignerCertificateExpiry
+ ? CertificateAlertResourceType.Signer
+ : CertificateAlertResourceType.Application;
+
const ALERT_EVENT_DESCRIPTIONS: Record<CertificateAlertEventType, (where: string) => string> = {
[CertificateAlertEventType.Expiry]: () => "Fires ahead of a certificate's expiry date.",
[CertificateAlertEventType.Issuance]: (where) =>
diff --git a/frontend/src/views/Alerts/ChannelCard.tsx b/frontend/src/views/Alerts/ChannelCard.tsx
index 29a5ab7d49..7ef4deb6a8 100644
--- a/frontend/src/views/Alerts/ChannelCard.tsx
+++ b/frontend/src/views/Alerts/ChannelCard.tsx
@@ -43,7 +43,6 @@ type Props = {
resourceType: string;
resourceId?: string | null;
alertId?: string;
- eventType?: string;
onRemove: () => void;
canRemove: boolean;
renderRecipients?: (props: TChannelRecipientsRenderProps) => ReactElement;
@@ -92,7 +91,6 @@ export const ChannelCard = ({
resourceType,
resourceId,
alertId,
- eventType,
onRemove,
canRemove,
renderRecipients
@@ -125,7 +123,6 @@ export const ChannelCard = ({
resourceId,
projectId: projectId ?? null,
alertId,
- eventType,
channelId: channel?.id,
channelType,
config,