Skip to content

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

add signer certificate expiration alerts and address PR review feedback

Carlos Monastyrskiab0c2274e10b
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index ccc8bceb7e..cfc4619226 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. **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 (`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.
- **Email channels accept plain addresses as `EMAIL` recipients when the provider opts in** (`recipientPolicy.allowEmailAddresses`), with the address as `principalId`, besides users and groups. Every address must be on one of the org's verified email domains, checked on create, update and test sends (`alert-channel-service.ts`), and again at send time, so an address on a domain the org has since removed stops receiving alerts. The resolver sends to them directly and skips an address that a user recipient on the same channel already covers.
- **`findScheduledTargets` must return most-urgent-first.** The engine's per-channel `maxTargetsPerRun` cap keeps the head of the list and defers the tail, so ordering is what guarantees the closest-to-expiry targets are never the dropped ones.
- **A `findScheduledTargets` that caps its own row count must honour `alreadyAlerted`.** The engine passes `{ alertId, channelIds, since }` (the alert's enabled channels and its dedup cutoff), and the provider drops targets every one of those channels already delivered since then, in SQL before the limit. Dedup otherwise runs after the fetch, so once more targets are due than the cap, the same head of the list comes back every run, is deduped, and nothing past it is ever alerted. That filter alone is not enough when the dedup window is shorter than the scan interval (a daily reminder), because yesterday's head is due again, so such a provider also orders the targets this alert notified least recently first, then by expiry. The certificate alert DAL does both in `findExpiringCertificates`.
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 5c5ed98e85..6f3a3b07d9 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -963,10 +963,10 @@ export enum EventType {
UPDATE_PKI_APPLICATION_ALERT = "update-pki-application-alert",
DELETE_PKI_APPLICATION_ALERT = "delete-pki-application-alert",
TEST_PKI_APPLICATION_ALERT_CHANNEL = "test-pki-application-alert-channel",
- CREATE_PKI_CERTIFICATE_ALERT = "create-pki-certificate-alert",
- UPDATE_PKI_CERTIFICATE_ALERT = "update-pki-certificate-alert",
- DELETE_PKI_CERTIFICATE_ALERT = "delete-pki-certificate-alert",
- TEST_PKI_CERTIFICATE_ALERT_CHANNEL = "test-pki-certificate-alert-channel"
+ CREATE_CERTIFICATE_MANAGER_ALERT = "create-certificate-manager-alert",
+ UPDATE_CERTIFICATE_MANAGER_ALERT = "update-certificate-manager-alert",
+ DELETE_CERTIFICATE_MANAGER_ALERT = "delete-certificate-manager-alert",
+ TEST_CERTIFICATE_MANAGER_ALERT_CHANNEL = "test-certificate-manager-alert-channel"
}
// Maps each actor type to the JSONB key that holds the actor's primary ID in actorMetadata.
@@ -7935,7 +7935,7 @@ interface TestPkiApplicationAlertEvent {
};
}
-type TPkiCertificateAlertEventMetadata = {
+type TCertificateManagerAlertEventMetadata = {
alertId: string;
name: string;
eventType: string;
@@ -7943,23 +7943,23 @@ type TPkiCertificateAlertEventMetadata = {
profiles: { id: string; name: string | null }[];
};
-interface CreatePkiCertificateAlertEvent {
- type: EventType.CREATE_PKI_CERTIFICATE_ALERT;
- metadata: TPkiCertificateAlertEventMetadata;
+interface CreateCertificateManagerAlertEvent {
+ type: EventType.CREATE_CERTIFICATE_MANAGER_ALERT;
+ metadata: TCertificateManagerAlertEventMetadata;
}
-interface UpdatePkiCertificateAlertEvent {
- type: EventType.UPDATE_PKI_CERTIFICATE_ALERT;
- metadata: TPkiCertificateAlertEventMetadata;
+interface UpdateCertificateManagerAlertEvent {
+ type: EventType.UPDATE_CERTIFICATE_MANAGER_ALERT;
+ metadata: TCertificateManagerAlertEventMetadata;
}
-interface DeletePkiCertificateAlertEvent {
- type: EventType.DELETE_PKI_CERTIFICATE_ALERT;
- metadata: TPkiCertificateAlertEventMetadata;
+interface DeleteCertificateManagerAlertEvent {
+ type: EventType.DELETE_CERTIFICATE_MANAGER_ALERT;
+ metadata: TCertificateManagerAlertEventMetadata;
}
-interface TestPkiCertificateAlertEvent {
- type: EventType.TEST_PKI_CERTIFICATE_ALERT_CHANNEL;
+interface TestCertificateManagerAlertEvent {
+ type: EventType.TEST_CERTIFICATE_MANAGER_ALERT_CHANNEL;
metadata: {
alertId?: string;
alertName?: string | null;
@@ -7981,10 +7981,10 @@ export type Event =
| UpdatePkiApplicationAlertEvent
| DeletePkiApplicationAlertEvent
| TestPkiApplicationAlertEvent
- | CreatePkiCertificateAlertEvent
- | UpdatePkiCertificateAlertEvent
- | DeletePkiCertificateAlertEvent
- | TestPkiCertificateAlertEvent
+ | CreateCertificateManagerAlertEvent
+ | UpdateCertificateManagerAlertEvent
+ | DeleteCertificateManagerAlertEvent
+ | TestCertificateManagerAlertEvent
| CreateSubOrganizationEvent
| UpdateSubOrganizationEvent
| DeleteSubOrganizationEvent
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 3c849310c1..c8bfa1c580 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2398,32 +2398,50 @@ export const CA_CRLS = {
};
export const ALERTING = {
- ROUTES: {
- create: "Create an alert that notifies its channels when an event happens to a resource.",
- testChannel: "Send a test notification through a channel, either a saved one or one described in the request.",
- list: "List the alerts on a resource type, optionally narrowed to one resource.",
- get: "Get an alert by ID.",
- update: "Update an alert's name, description, condition, status, or channels.",
- delete: "Delete an alert and its channels."
- },
- name: "The name of the alert.",
- description: "An optional description of the alert.",
- resourceType:
- "The kind of resource the alert watches, such as `identity.authentication` or `cert-manager.application`.",
- resourceId:
- "The ID of the resource the alert watches. For `cert-manager.application`, set it to an application ID to watch that application, or null to watch every certificate in Certificate Manager.",
- listResourceId:
- "Only return alerts on this resource. For `cert-manager.application`, leave it out to list the alerts that cover all of Certificate Manager.",
- eventType: "The event that triggers the alert, such as `cert-manager.application.certificate.expiry`.",
- condition:
- "When the alert fires. Expiry alerts take `alertBefore` (for example `30d`) and an optional `dailyReminder`. Certificate Manager alerts with no `resourceId` also accept `applicationIds` and `profileIds`, which narrow the alert to certificates in those applications and profiles.",
- enabled: "Whether the alert sends notifications.",
- projectId: "The ID of the project the alert belongs to. Optional when the resource already belongs to one.",
- channels: "Where the alert is delivered. Each channel is email, Slack, webhook, or PagerDuty.",
- alertId: "The ID of the alert.",
- channelId: "The ID of a saved channel to test.",
- filters:
- "Read-only. The resources named in the alert's condition, as `{ id, name }` lists keyed by kind (for example `applications` and `profiles`). `name` is null when the resource no longer exists."
+ CREATE: {
+ name: "The name of the alert.",
+ description: "The description of the alert.",
+ resourceType: "The type of resource the alert watches, for example `cert-manager.application`.",
+ resourceId:
+ "The ID of the resource the alert watches. Set to null to watch every resource of this type, where the resource type supports it.",
+ eventType: "The event that triggers the alert, for example `cert-manager.application.certificate.expiry`.",
+ condition:
+ "The settings of the alert's event, for example `alertBefore` on an expiry event. The accepted fields depend on `eventType`.",
+ enabled: "Whether the alert is enabled. Defaults to true.",
+ projectId: "The ID of the project to create the alert in. Optional when the resource belongs to a project.",
+ channels: "The channels the alert notifies. Each is email, Slack, webhook, or PagerDuty."
+ },
+ TEST_CHANNEL: {
+ resourceType: "The type of resource the alert watches.",
+ 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: {
+ resourceType: "The type of resource to list alerts for.",
+ resourceId:
+ "The ID of the resource to list alerts for. If omitted, lists every alert on the resource type. For resource types that support alerts covering all of their resources, such as `cert-manager.application`, lists only those alerts.",
+ projectId: "The ID of the project to list alerts in.",
+ enabled: "Whether to list only enabled or only disabled alerts."
+ },
+ GET: {
+ alertId: "The ID of the alert to get.",
+ filters:
+ "The resources named in the alert's condition, such as applications and certificate profiles, each as `{ id, name }`. `name` is null for a deleted resource."
+ },
+ UPDATE: {
+ alertId: "The ID of the alert to update.",
+ name: "The new name of the alert.",
+ description: "The new description of the alert. Set to null to remove it.",
+ condition: "The new settings of the alert's event. The accepted fields depend on the alert's `eventType`.",
+ enabled: "Whether the alert is enabled.",
+ channels: "The alert's channels. Replaces the current channels, so channels left out are deleted."
+ },
+ DELETE: {
+ alertId: "The ID of the alert to delete."
+ }
};
export const ALERTS = {
diff --git a/backend/src/server/routes/v1/alert-router.ts b/backend/src/server/routes/v1/alert-router.ts
index 5ae83a53d2..6d0d9901f3 100644
--- a/backend/src/server/routes/v1/alert-router.ts
+++ b/backend/src/server/routes/v1/alert-router.ts
@@ -54,7 +54,7 @@ const AlertResponseSchema = z.object({
filters: z
.record(z.array(z.object({ id: z.string(), name: z.string().nullable() })))
.optional()
- .describe(ALERTING.filters),
+ .describe(ALERTING.GET.filters),
channels: z.array(
z.object({
id: z.string().uuid(),
@@ -94,17 +94,21 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
config: { rateLimit: writeLimit },
schema: {
operationId: "createAlert",
- description: ALERTING.ROUTES.create,
+ description: "Create an alert that notifies its channels when an event happens to a resource.",
body: z.object({
- name: z.string().min(1).max(255).describe(ALERTING.name),
- description: z.string().max(1000).optional().describe(ALERTING.description),
- resourceType: z.string().min(1).describe(ALERTING.resourceType),
- resourceId: z.string().uuid().nullable().optional().describe(ALERTING.resourceId),
- eventType: z.string().min(1).describe(ALERTING.eventType),
- condition: z.unknown().optional().describe(ALERTING.condition),
- enabled: z.boolean().optional().describe(ALERTING.enabled),
- projectId: z.string().nullable().optional().describe(ALERTING.projectId),
- channels: z.array(CreateChannelInputSchema).min(1).max(MAX_CHANNELS_PER_ALERT).describe(ALERTING.channels)
+ name: z.string().min(1).max(255).describe(ALERTING.CREATE.name),
+ description: z.string().max(1000).optional().describe(ALERTING.CREATE.description),
+ resourceType: z.string().min(1).describe(ALERTING.CREATE.resourceType),
+ resourceId: z.string().uuid().nullable().optional().describe(ALERTING.CREATE.resourceId),
+ eventType: z.string().min(1).describe(ALERTING.CREATE.eventType),
+ condition: z.unknown().optional().describe(ALERTING.CREATE.condition),
+ enabled: z.boolean().optional().describe(ALERTING.CREATE.enabled),
+ projectId: z.string().nullable().optional().describe(ALERTING.CREATE.projectId),
+ channels: z
+ .array(CreateChannelInputSchema)
+ .min(1)
+ .max(MAX_CHANNELS_PER_ALERT)
+ .describe(ALERTING.CREATE.channels)
}),
response: { 200: z.object({ alert: AlertResponseSchema }) }
},
@@ -136,13 +140,14 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
config: { rateLimit: writeLimit },
schema: {
operationId: "testAlertChannel",
- description: ALERTING.ROUTES.testChannel,
+ description: "Send a test notification through a saved channel or a channel described in the request.",
body: z.object({
- resourceType: z.string().min(1).describe(ALERTING.resourceType),
- resourceId: z.string().uuid().nullable().optional().describe(ALERTING.resourceId),
- projectId: z.string().nullable().optional().describe(ALERTING.projectId),
- alertId: z.string().uuid().optional().describe(ALERTING.alertId),
- channelId: z.string().uuid().optional().describe(ALERTING.channelId),
+ resourceType: z.string().min(1).describe(ALERTING.TEST_CHANNEL.resourceType),
+ 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({}),
recipients: z.array(ChannelRecipientSchema).max(MAX_RECIPIENTS_PER_CHANNEL).optional()
@@ -197,16 +202,16 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
config: { rateLimit: readLimit },
schema: {
operationId: "listAlerts",
- description: ALERTING.ROUTES.list,
+ description: "List the alerts on a resource type.",
querystring: z.object({
- resourceType: z.string().min(1).describe(ALERTING.resourceType),
- resourceId: z.string().uuid().optional().describe(ALERTING.listResourceId),
- projectId: z.string().optional().describe(ALERTING.projectId),
+ resourceType: z.string().min(1).describe(ALERTING.LIST.resourceType),
+ resourceId: z.string().uuid().optional().describe(ALERTING.LIST.resourceId),
+ projectId: z.string().optional().describe(ALERTING.LIST.projectId),
enabled: z
.enum(["true", "false"])
.transform((value) => value === "true")
.optional()
- .describe(ALERTING.enabled)
+ .describe(ALERTING.LIST.enabled)
}),
response: { 200: z.object({ alerts: AlertResponseSchema.array() }) }
},
@@ -229,8 +234,8 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
config: { rateLimit: readLimit },
schema: {
operationId: "getAlertById",
- description: ALERTING.ROUTES.get,
- params: z.object({ alertId: z.string().uuid().describe(ALERTING.alertId) }),
+ description: "Get an alert by ID.",
+ params: z.object({ alertId: z.string().uuid().describe(ALERTING.GET.alertId) }),
response: { 200: z.object({ alert: AlertResponseSchema }) }
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
@@ -252,19 +257,19 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
config: { rateLimit: writeLimit },
schema: {
operationId: "updateAlert",
- description: ALERTING.ROUTES.update,
- params: z.object({ alertId: z.string().uuid().describe(ALERTING.alertId) }),
+ description: "Update an alert.",
+ params: z.object({ alertId: z.string().uuid().describe(ALERTING.UPDATE.alertId) }),
body: z.object({
- name: z.string().min(1).max(255).optional().describe(ALERTING.name),
- description: z.string().max(1000).nullable().optional().describe(ALERTING.description),
- condition: z.unknown().optional().describe(ALERTING.condition),
- enabled: z.boolean().optional().describe(ALERTING.enabled),
+ name: z.string().min(1).max(255).optional().describe(ALERTING.UPDATE.name),
+ description: z.string().max(1000).nullable().optional().describe(ALERTING.UPDATE.description),
+ condition: z.unknown().optional().describe(ALERTING.UPDATE.condition),
+ enabled: z.boolean().optional().describe(ALERTING.UPDATE.enabled),
channels: z
.array(UpdateChannelInputSchema)
.min(1)
.max(MAX_CHANNELS_PER_ALERT)
.optional()
- .describe(ALERTING.channels)
+ .describe(ALERTING.UPDATE.channels)
}),
response: { 200: z.object({ alert: AlertResponseSchema }) }
},
@@ -297,8 +302,8 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
config: { rateLimit: writeLimit },
schema: {
operationId: "deleteAlert",
- description: ALERTING.ROUTES.delete,
- params: z.object({ alertId: z.string().uuid().describe(ALERTING.alertId) }),
+ description: "Delete an alert and its channels.",
+ params: z.object({ alertId: z.string().uuid().describe(ALERTING.DELETE.alertId) }),
response: { 200: z.object({ alert: z.object({ id: z.string().uuid() }) }) }
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
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 6ee09d0c66..993c883e29 100644
--- a/backend/src/services/alert/alert-channel-test-service.test.ts
+++ b/backend/src/services/alert/alert-channel-test-service.test.ts
@@ -97,7 +97,8 @@ const OWNING_ALERT = {
orgId: ORG_ID,
projectId: null,
resourceType: RESOURCE_TYPE,
- resourceId: "resource-1"
+ resourceId: "resource-1",
+ eventType: "test.resource.saved"
};
const buildDeps = (overrides?: {
@@ -391,6 +392,37 @@ 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 16d192f068..13036bcfac 100644
--- a/backend/src/services/alert/alert-channel-test-service.ts
+++ b/backend/src/services/alert/alert-channel-test-service.ts
@@ -15,7 +15,12 @@ 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 { getAlertResourceName, resolveAlertProjectId, TAlertProviderRegistry } from "./alert-provider-registry";
+import {
+ getAlertEvent,
+ 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";
@@ -84,6 +89,7 @@ export const alertChannelTestServiceFactory = ({
orgId: owner.orgId,
projectId: owner.projectId,
resourceId: owner.resourceId,
+ eventType: owner.eventType,
actor: toAlertActor(dto)
});
}
@@ -210,6 +216,7 @@ export const alertChannelTestServiceFactory = ({
});
let alertName: string | null = null;
+ let alertEventType = dto.eventType;
if (dto.alertId) {
const alert = await alertDAL.findActiveById(dto.alertId);
if (
@@ -222,6 +229,9 @@ 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({
@@ -229,6 +239,7 @@ 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-provider-registry.ts b/backend/src/services/alert/alert-provider-registry.ts
index 68287e92d1..b8338a97b9 100644
--- a/backend/src/services/alert/alert-provider-registry.ts
+++ b/backend/src/services/alert/alert-provider-registry.ts
@@ -1,4 +1,6 @@
-import { AlertTriggerType, IResourceAlertProvider } from "./alert-types";
+import { BadRequestError } from "@app/lib/errors";
+
+import { AlertTriggerType, IResourceAlertProvider, TAlertEventDefinition } from "./alert-types";
export const resolveAlertProjectId = async (
provider: IResourceAlertProvider,
@@ -17,6 +19,16 @@ export const getAlertResourceName = async (
return (await provider.getResourceNames({ orgId, resourceIds: [resourceId] })).get(resourceId) ?? null;
};
+export const getAlertEvent = (provider: IResourceAlertProvider, eventType: string): TAlertEventDefinition => {
+ const event = provider.events.find((candidate) => candidate.key === eventType);
+ if (!event) {
+ throw new BadRequestError({
+ message: `Event type '${eventType}' is not supported by resource type '${provider.resourceType}'`
+ });
+ }
+ return event;
+};
+
export type TAlertProviderRegistry = ReturnType<typeof alertProviderRegistryFactory>;
export const alertProviderRegistryFactory = () => {
diff --git a/backend/src/services/alert/alert-service-types.ts b/backend/src/services/alert/alert-service-types.ts
index d768945ef2..91f5909ae7 100644
--- a/backend/src/services/alert/alert-service-types.ts
+++ b/backend/src/services/alert/alert-service-types.ts
@@ -43,6 +43,7 @@ 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 4499912774..bb3ba6451a 100644
--- a/backend/src/services/alert/alert-service.ts
+++ b/backend/src/services/alert/alert-service.ts
@@ -15,7 +15,12 @@ import { TAlertChannelEmbedded, TAlertChannelInput } from "./alert-channel-servi
import { TAlertDALFactory } from "./alert-dal";
import { TAlertHistoryDALFactory } from "./alert-history-dal";
import { getRecipientScope } from "./alert-principal-scope-fns";
-import { getAlertResourceName, resolveAlertProjectId, TAlertProviderRegistry } from "./alert-provider-registry";
+import {
+ getAlertEvent,
+ getAlertResourceName,
+ resolveAlertProjectId,
+ TAlertProviderRegistry
+} from "./alert-provider-registry";
import {
TAlertLastRun,
TAlertResponse,
@@ -103,7 +108,7 @@ export const alertServiceFactory = ({
const $assertAlertPermission = (
provider: IResourceAlertProvider,
action: AlertPermissionAction,
- scope: { orgId: string; projectId?: string | null; resourceId?: string | null },
+ scope: { orgId: string; projectId?: string | null; resourceId?: string | null; eventType?: string },
dto: TGenericPermission
) =>
provider.assertPermission({
@@ -111,19 +116,10 @@ export const alertServiceFactory = ({
orgId: scope.orgId,
projectId: scope.projectId,
resourceId: scope.resourceId,
+ eventType: scope.eventType,
actor: toAlertActor(dto)
});
- const $getEvent = (provider: IResourceAlertProvider, eventType: string): TAlertEventDefinition => {
- const event = provider.events.find((candidate) => candidate.key === eventType);
- if (!event) {
- throw new BadRequestError({
- message: `Event type '${eventType}' is not supported by resource type '${provider.resourceType}'`
- });
- }
- return event;
- };
-
const $parseCondition = (event: TAlertEventDefinition, condition: unknown): unknown => {
try {
return event.conditionSchema.parse(condition);
@@ -210,13 +206,13 @@ export const alertServiceFactory = ({
resourceId: dto.resourceId
});
- const event = $getEvent(provider, dto.eventType);
+ const event = getAlertEvent(provider, dto.eventType);
const condition = $parseCondition(event, dto.condition);
await $assertAlertPermission(
provider,
AlertPermissionAction.Create,
- { orgId: dto.actorOrgId, projectId, resourceId: dto.resourceId },
+ { orgId: dto.actorOrgId, projectId, resourceId: dto.resourceId, eventType: dto.eventType },
dto
);
@@ -465,13 +461,13 @@ export const alertServiceFactory = ({
await $assertAlertPermission(
provider,
AlertPermissionAction.Edit,
- { orgId: alert.orgId, projectId: alert.projectId, resourceId: alert.resourceId },
+ { orgId: alert.orgId, projectId: alert.projectId, resourceId: alert.resourceId, eventType: alert.eventType },
dto
);
let condition: unknown;
if (dto.condition !== undefined) {
- condition = $parseCondition($getEvent(provider, alert.eventType), dto.condition);
+ condition = $parseCondition(getAlertEvent(provider, alert.eventType), dto.condition);
await provider.assertConditionInScope?.({
projectId: alert.projectId,
resourceId: alert.resourceId,
diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.ts
index 4399b13169..46b747bba0 100644
--- a/backend/src/services/alert/alert-types.ts
+++ b/backend/src/services/alert/alert-types.ts
@@ -41,6 +41,7 @@ export type TAlertPermissionInput = {
orgId: string;
projectId?: string | null;
resourceId?: string | null;
+ eventType?: string;
actor: TGenericPermission;
};
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 60900b1546..90c1721026 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
@@ -7,7 +7,7 @@ import { certManagerApplicationAlertDALFactory } from "./cert-manager-applicatio
const PROJECT_ID = "3f2d7a4e-1b6c-4d8e-9a0f-5c7b2e1d4a6b";
const APPLICATION_ID = "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90";
-const buildDAL = () => {
+const buildDAL = (firstQueryRows: unknown[] = []) => {
const builder = knex({ client: "pg" });
const queries: { sql: string; bindings: readonly unknown[] }[] = [];
@@ -17,7 +17,7 @@ const buildDAL = () => {
then: (resolve: (rows: unknown[]) => void) => {
const { sql, bindings } = query.toSQL();
queries.push({ sql, bindings });
- resolve([]);
+ resolve(queries.length === 1 ? firstQueryRows : []);
}
});
}) as unknown as Knex;
@@ -65,13 +65,62 @@ describe("cert manager certificate alert DAL", () => {
alreadyAlerted: { alertId: "alert-1", channelIds: ["channel-1", "channel-2"], since }
});
+ expect(queries).toHaveLength(2);
+ const [neverNotified, leastRecentlyNotified] = queries;
+ expect(neverNotified.sql).toContain('count(distinct "tgt"."channelId")');
+ expect(neverNotified.sql).toContain('"tgt"."targetId" = "certificates".id::text');
+ expect(neverNotified.sql).toContain('not exists (select "notifiedTgt"."id"');
+ expect(neverNotified.sql).toMatch(/order by "certificates"\."notAfter" asc limit \?$/);
+ expect(neverNotified.bindings).toEqual(
+ expect.arrayContaining(["alert-1", since, "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(
+ 'order by "lastDelivered"."lastDeliveredAt" asc, "certificates"."notAfter" asc limit ?'
+ );
+ expect(leastRecentlyNotified.sql).not.toContain("not exists");
+ });
+
+ test("findExpiringCertificates stops after the never-notified query when it fills the cap", async () => {
+ const { dal, queries } = buildDAL(Array.from({ length: 1000 }, (_, index) => ({ id: `cert-${index}` })));
+
+ const certificates = await dal.findExpiringCertificates({
+ 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") }
+ });
+
+ expect(certificates).toHaveLength(1000);
+ 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('inner join "certificates" on "pki_signers"."certificateId" = "certificates"."id"');
+ expect(sql).toContain('"pki_signers"."projectId" = ?');
+ expect(sql).toContain('"pki_signers"."status" = ?');
+ expect(sql).toContain('"pki_signers"."name" as "signerName"');
+ expect(sql).toContain('not "certificates"."status" = ?');
expect(sql).toContain('count(distinct "tgt"."channelId")');
- expect(sql).toContain('"tgt"."targetId" = "certificates".id::text');
- expect(sql.indexOf("count(distinct")).toBeLessThan(sql.indexOf("limit"));
- expect(sql).toContain('max("lastHist"."triggeredAt")');
- expect(sql.indexOf("asc nulls first")).toBeLessThan(sql.indexOf('"certificates"."notAfter" asc'));
- expect(bindings).toEqual(expect.arrayContaining(["alert-1", since, "success", "channel-1", "channel-2", 2]));
+ expect(sql).toContain("not exists");
+ expect(bindings).toEqual(expect.arrayContaining([PROJECT_ID, "active", "alert-1"]));
+ expect(queries[1].sql).toContain(
+ 'inner join "certificates" on "pki_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 () => {
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 0a58d9546c..a567eac49f 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,6 +5,7 @@ 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>;
@@ -22,6 +23,15 @@ export type TApplicationAlertCertificate = {
revocationReason: number | null;
applicationId: string | null;
applicationName: string | null;
+ signerId?: string | null;
+ signerName?: string | null;
+};
+
+type TExpiryWindow = {
+ alertBeforeInterval: string;
+ leadInterval: string;
+ asOf: Date;
+ alreadyAlerted?: TAlreadyAlertedFilter;
};
type TCertificateScope = {
@@ -44,6 +54,95 @@ const applyCertificateScope = <TQuery extends Knex.QueryBuilder>(
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 neverNotified = (await dueQuery()
+ .whereNotExists(
+ reader(`${TableName.AlertHistory} as notifiedHist`)
+ .join(`${TableName.AlertHistoryTarget} as notifiedTgt`, "notifiedHist.id", "notifiedTgt.alertHistoryId")
+ .where("notifiedHist.alertId", alreadyAlerted.alertId)
+ .where("notifiedTgt.status", AlertRunStatus.SUCCESS)
+ .whereRaw(`"notifiedTgt"."targetId" = "${TableName.Certificate}".id::text`)
+ .select("notifiedTgt.id")
+ )
+ .orderBy(`${TableName.Certificate}.notAfter`, "asc")
+ .limit(MAX_EXPIRING_CERTIFICATES_PER_RUN)) as TApplicationAlertCertificate[];
+ if (neverNotified.length >= MAX_EXPIRING_CERTIFICATES_PER_RUN) return neverNotified;
+
+ 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)
+ .groupBy("lastTgt.targetId")
+ .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 - neverNotified.length)) as TApplicationAlertCertificate[];
+
+ return [...neverNotified, ...leastRecentlyNotified];
+};
+
export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {
const $selectCertificates = (reader: Knex, scope: TCertificateScope) => {
const query = applyCertificateScope(
@@ -53,74 +152,53 @@ export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {
scope
);
- return query.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`
- );
+ return query.select(CERTIFICATE_TARGET_COLUMNS);
};
const findExpiringCertificates = async (
- scope: TCertificateScope & {
- alertBeforeInterval: string;
- leadInterval: string;
- asOf: Date;
- alreadyAlerted?: TAlreadyAlertedFilter;
- },
+ scope: TCertificateScope & TExpiryWindow,
tx?: Knex
): Promise<TApplicationAlertCertificate[]> => {
try {
const reader = tx || db.replicaNode();
- const query = $selectCertificates(reader, scope);
- const { alreadyAlerted } = scope;
- 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]);
-
- const lastDeliveredAt = reader(`${TableName.AlertHistory} as lastHist`)
- .join(`${TableName.AlertHistoryTarget} as lastTgt`, "lastHist.id", "lastTgt.alertHistoryId")
- .where("lastHist.alertId", alreadyAlerted.alertId)
- .where("lastTgt.status", AlertRunStatus.SUCCESS)
- .whereRaw(`"lastTgt"."targetId" = "${TableName.Certificate}".id::text`)
- .max("lastHist.triggeredAt");
- void query.orderByRaw("(?) asc nulls first", [lastDeliveredAt]);
- }
-
- const certificates = (await query
- .whereNot(`${TableName.Certificate}.status`, CertStatus.REVOKED)
- .whereNull(`${TableName.Certificate}.renewedByCertificateId`)
- .whereRaw(`"${TableName.Certificate}"."notAfter" > ?::timestamptz`, [scope.asOf])
- .whereRaw(`"${TableName.Certificate}"."notAfter" <= ?::timestamptz + ?::interval + ?::interval`, [
- scope.asOf,
- scope.alertBeforeInterval,
- scope.leadInterval
- ])
- .orderBy(`${TableName.Certificate}.notAfter`, "asc")
- .limit(MAX_EXPIRING_CERTIFICATES_PER_RUN)) as TApplicationAlertCertificate[];
-
- return certificates;
+ return await selectExpiring(
+ reader,
+ () => $selectCertificates(reader, scope).whereNull(`${TableName.Certificate}.renewedByCertificateId`),
+ scope
+ );
} 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 buildQuery = () =>
+ reader(TableName.PkiSigners)
+ .join(TableName.Certificate, `${TableName.PkiSigners}.certificateId`, `${TableName.Certificate}.id`)
+ .leftJoin(`${TableName.PkiCertificateProfile} as profile`, `${TableName.Certificate}.profileId`, "profile.id")
+ .leftJoin(
+ TableName.PkiApplication,
+ `${TableName.Certificate}.applicationId`,
+ `${TableName.PkiApplication}.id`
+ )
+ .where(`${TableName.PkiSigners}.projectId`, scope.projectId)
+ .where(`${TableName.PkiSigners}.status`, SignerStatus.Active)
+ .select([
+ ...CERTIFICATE_TARGET_COLUMNS,
+ `${TableName.PkiSigners}.id as signerId`,
+ `${TableName.PkiSigners}.name as signerName`
+ ]);
+ return await selectExpiring(reader, buildQuery, scope);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindExpiringSignerCertificates" });
+ }
+ };
+
const findCertificatesByIds = async (
scope: TCertificateScope & { certificateIds: string[] },
tx?: Knex
@@ -219,6 +297,7 @@ 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 5ebbd9ac33..80ecf9a7cd 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,6 +19,7 @@ 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";
@@ -58,10 +59,12 @@ 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;
abilityRules?: { action: string; subject: string; inverted?: boolean; conditions?: unknown }[];
+ projectRoles?: string[];
pkiEnterpriseAlerting?: boolean;
}) => {
const application = opts?.application ?? {
@@ -82,6 +85,10 @@ 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 ?? [];
@@ -98,7 +105,10 @@ const buildProvider = (opts?: {
createMongoAbility((opts?.abilityRules ?? [{ action: "read", subject: "pki-alerts" }]) as never);
const permissionService = {
getResourcePermission: vi.fn(async () => ({ permission: ability() })),
- getProjectPermission: vi.fn(async () => ({ permission: ability() }))
+ getProjectPermission: vi.fn(async () => ({
+ permission: ability(),
+ hasRole: (role: string) => (opts?.projectRoles ?? []).includes(role)
+ }))
};
const licenseService = {
getPlan: async () => ({ pkiEnterpriseAlerting: opts?.pkiEnterpriseAlerting ?? false })
@@ -134,16 +144,18 @@ describe("cert manager application alert provider", () => {
test("issuance, renewal and revocation are event-triggered and take only optional filters", () => {
const { provider } = buildProvider();
expect(provider.supportsScopeWideAlerts).toBe(true);
- const eventKeys = provider.events.filter((event) => event.key !== EXPIRY_EVENT).map((event) => event.key);
- expect(eventKeys).toEqual([ISSUANCE_EVENT, "cert-manager.application.certificate.renewal", REVOCATION_EVENT]);
- provider.events
- .filter((event) => event.key !== EXPIRY_EVENT)
- .forEach((event) => {
- expect(event.conditionSchema.safeParse(null).success).toBe(true);
- expect(event.conditionSchema.safeParse({ profileIds: [PROFILE_ID] }).success).toBe(true);
- expect(event.conditionSchema.safeParse({ profileIds: [] }).success).toBe(false);
- expect(event.conditionSchema.safeParse({ alertBefore: "30d" }).success).toBe(false);
- });
+ const eventTriggered = provider.events.filter((event) => event.triggerType === "event");
+ expect(eventTriggered.map((event) => event.key)).toEqual([
+ ISSUANCE_EVENT,
+ "cert-manager.application.certificate.renewal",
+ REVOCATION_EVENT
+ ]);
+ eventTriggered.forEach((event) => {
+ expect(event.conditionSchema.safeParse(null).success).toBe(true);
+ expect(event.conditionSchema.safeParse({ profileIds: [PROFILE_ID] }).success).toBe(true);
+ expect(event.conditionSchema.safeParse({ profileIds: [] }).success).toBe(false);
+ expect(event.conditionSchema.safeParse({ alertBefore: "30d" }).success).toBe(false);
+ });
});
test("filters must be non-empty UUID lists and are stored as sent", () => {
@@ -273,6 +285,7 @@ describe("cert manager application alert provider", () => {
expect(payload.summary).toBe("1 certificate in application 'payments-api' expiring within 1 day");
expect(payload.alert.condition).toBe("1d");
expect(payload.webhookType).toBe(`com.infisical.${EXPIRY_EVENT}`);
+ expect(payload.eventKey).toBe(EXPIRY_EVENT);
expect(payload.webhookSource).toBe(`/applications/${alertContext().resourceId}/alerts/alert-1`);
expect(payload.alert.resourceId).toBe(alertContext().resourceId);
expect(payload.severity).toBe("critical");
@@ -417,6 +430,8 @@ describe("cert manager application alert provider", () => {
expect(payload.resourceOwnerKind).toBe("Certificate Manager");
expect(payload.webhookSource).toBe("/alerts/alert-1");
+ expect(payload.eventKey).toBe("cert-manager.certificate.expiry");
+ expect(payload.webhookType).toBe("com.infisical.cert-manager.certificate.expiry");
expect(payload.summary).toBe("1 certificate expiring within 30 days");
expect(payload.items[0].fields).toContainEqual({ label: "Application", value: "payments-api" });
});
@@ -438,7 +453,7 @@ describe("cert manager application alert provider", () => {
).rejects.toThrow("Application alerts already cover a single application");
await expect(
provider.assertConditionInScope?.({ projectId: "proj-1", condition: { applicationIds: [OTHER_APPLICATION_ID] } })
- ).rejects.toThrow(`Application(s) not found in Certificate Manager: '${OTHER_APPLICATION_ID}'`);
+ ).rejects.toThrow(`Application not found in Certificate Manager: '${OTHER_APPLICATION_ID}'`);
});
test("assertConditionInScope only checks IDs the update adds, so a deleted one can stay", async () => {
@@ -508,11 +523,11 @@ describe("cert manager application alert provider", () => {
};
expect(provider.getAuditEvent?.({ action: AlertAuditAction.Create, alert })).toEqual({
- type: "create-pki-certificate-alert",
+ type: "create-certificate-manager-alert",
metadata
});
expect(provider.getAuditEvent?.({ action: AlertAuditAction.Delete, alert })).toEqual({
- type: "delete-pki-certificate-alert",
+ type: "delete-certificate-manager-alert",
metadata
});
expect(
@@ -527,7 +542,7 @@ describe("cert manager application alert provider", () => {
}
})
).toMatchObject({
- type: "test-pki-certificate-alert-channel",
+ type: "test-certificate-manager-alert-channel",
metadata: { alertId: "alert-1", alertName: "prod-expiry", channelType: "email", success: true }
});
});
@@ -756,4 +771,129 @@ 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,
+ signerId: "signer-1",
+ signerName: "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({ signerId: "signer-1", signerName: "release-signer" });
+ expect(provider.dedupWindowHours?.({ alertBefore: "30d" })).toBe(44);
+ });
+ });
});
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 d446549239..862ee992c2 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,7 +1,7 @@
import { ForbiddenError, MongoAbility } from "@casl/ability";
import { z } from "zod";
-import { ActionProjectType, ResourceType } from "@app/db/schemas";
+import { ActionProjectType, ProjectMembershipRole, 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";
@@ -17,7 +17,8 @@ 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
+ CertificateAlertEvent,
+ CodeSigningAlertEvent
} 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";
@@ -49,11 +50,20 @@ import {
const MAX_CERTIFICATE_ALERT_FILTER_IDS = 100;
-const TELEMETRY_ALERT_TYPE_BY_EVENT: Record<CertificateAlertEvent, string> = {
+type TCertManagerAlertEvent = CertificateAlertEvent | CodeSigningAlertEvent;
+
+const toCertificateManagerEventKey = (eventType: TCertManagerAlertEvent) =>
+ eventType.replace(`${CERT_MANAGER_APPLICATION_RESOURCE_TYPE}.`, "cert-manager.");
+
+const isExpiryEvent = (eventType: TCertManagerAlertEvent) =>
+ eventType === CertificateAlertEvent.Expiry || eventType === CodeSigningAlertEvent.SignerCertificateExpiry;
+
+const TELEMETRY_ALERT_TYPE_BY_EVENT: Record<TCertManagerAlertEvent, string> = {
[CertificateAlertEvent.Expiry]: "expiration",
[CertificateAlertEvent.Issuance]: "issuance",
[CertificateAlertEvent.Renewal]: "renewal",
- [CertificateAlertEvent.Revocation]: "revocation"
+ [CertificateAlertEvent.Revocation]: "revocation",
+ [CodeSigningAlertEvent.SignerCertificateExpiry]: "signer-certificate-expiration"
};
const MIN_CERTIFICATE_ALERT_BEFORE_DAYS = 1;
@@ -91,18 +101,21 @@ const CertificateFilterSchema = z.object({
profileIds: filterIdsSchema("profileIds", "profile")
});
-const ExpirationConditionSchema = z
- .object({
- alertBefore: z
- .string()
- .refine(
- isValidAlertBefore,
- `Must be a number of days, weeks, months or years adding up to ${MIN_CERTIFICATE_ALERT_BEFORE_DAYS} to ${MAX_CERTIFICATE_ALERT_BEFORE_DAYS} days, e.g. '30d' or '2w'`
- ),
- dailyReminder: z.boolean().optional()
- })
- .merge(CertificateFilterSchema)
- .strict();
+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();
@@ -112,18 +125,20 @@ const assertValidApplicationId = (applicationId: string) => {
}
};
-const EVENT_LABELS: Record<CertificateAlertEvent, string> = {
+const EVENT_LABELS: Record<TCertManagerAlertEvent, string> = {
[CertificateAlertEvent.Expiry]: "Expiration",
[CertificateAlertEvent.Issuance]: "Issuance",
[CertificateAlertEvent.Renewal]: "Renewal",
- [CertificateAlertEvent.Revocation]: "Revocation"
+ [CertificateAlertEvent.Revocation]: "Revocation",
+ [CodeSigningAlertEvent.SignerCertificateExpiry]: "Expiration"
};
-const EVENT_VERBS: Record<CertificateAlertEvent, string> = {
+const EVENT_VERBS: Record<TCertManagerAlertEvent, string> = {
[CertificateAlertEvent.Expiry]: "is expiring",
[CertificateAlertEvent.Issuance]: "was issued",
[CertificateAlertEvent.Renewal]: "was renewed",
- [CertificateAlertEvent.Revocation]: "was revoked"
+ [CertificateAlertEvent.Revocation]: "was revoked",
+ [CodeSigningAlertEvent.SignerCertificateExpiry]: "is expiring"
};
const PERMISSION_ACTIONS: Record<AlertPermissionAction, ProjectPermissionActions> = {
@@ -133,8 +148,8 @@ const PERMISSION_ACTIONS: Record<AlertPermissionAction, ProjectPermissionActions
[AlertPermissionAction.Delete]: ProjectPermissionActions.Delete
};
-const eventSeverity = (eventType: CertificateAlertEvent, targets: TApplicationAlertCertificate[]): TAlertSeverity => {
- if (eventType === CertificateAlertEvent.Expiry) return expirySeverity(targets.map((target) => target.notAfter));
+const eventSeverity = (eventType: TCertManagerAlertEvent, targets: TApplicationAlertCertificate[]): TAlertSeverity => {
+ if (isExpiryEvent(eventType)) return expirySeverity(targets.map((target) => target.notAfter));
if (eventType === CertificateAlertEvent.Revocation) return "warning";
return "info";
};
@@ -152,13 +167,14 @@ const inApplication = (applicationName?: string | null) =>
applicationName ? ` in application '${applicationName}'` : "";
const buildSummary = (
- eventType: CertificateAlertEvent,
+ eventType: TCertManagerAlertEvent,
targets: TApplicationAlertCertificate[],
applicationName: string | null,
alertBefore?: string
): string => {
if (alertBefore) {
- const certificates = `${targets.length} certificate${targets.length === 1 ? "" : "s"}`;
+ const noun = eventType === CodeSigningAlertEvent.SignerCertificateExpiry ? "signer certificate" : "certificate";
+ const certificates = `${targets.length} ${noun}${targets.length === 1 ? "" : "s"}`;
return `${certificates}${inApplication(applicationName)} expiring within ${humanizeDays(durationToDays(alertBefore))}`;
}
if (targets.length === 1) {
@@ -167,7 +183,10 @@ const buildSummary = (
return `${targets.length} certificates ${EVENT_VERBS[eventType]}${inApplication(applicationName)}`;
};
-const buildItemSummary = (eventType: CertificateAlertEvent, certificate: TApplicationAlertCertificate): string => {
+const buildItemSummary = (eventType: TCertManagerAlertEvent, certificate: TApplicationAlertCertificate): string => {
+ if (eventType === CodeSigningAlertEvent.SignerCertificateExpiry) {
+ return `Certificate '${certificateDisplayName(certificate)}' of signer '${certificate.signerName}' expires on ${formatUtcDate(certificate.notAfter)}`;
+ }
if (eventType === CertificateAlertEvent.Expiry) {
return `Certificate '${certificateDisplayName(certificate)}'${inApplication(certificate.applicationName)} expires on ${formatUtcDate(certificate.notAfter)}`;
}
@@ -194,10 +213,8 @@ const parseFilters = (condition: unknown) => {
return filters.success ? filters.data : {};
};
-const canReadAllCertificates = (permission: MongoAbility<ProjectPermissionSet>) => {
- const rules = permission.rulesFor(ProjectPermissionCertificateActions.Read, ProjectPermissionSub.Certificates);
- return rules.some((rule) => !rule.inverted && !rule.conditions) && !rules.some((rule) => rule.inverted);
-};
+const isUnconditionalGrant = (rules: ReturnType<MongoAbility<ProjectPermissionSet>["rulesFor"]>) =>
+ rules.some((rule) => !rule.inverted && !rule.conditions) && !rules.some((rule) => rule.inverted);
export type TCertManagerApplicationAlertProviderDep = {
certManagerApplicationAlertDAL: TCertManagerApplicationAlertDALFactory;
@@ -215,6 +232,7 @@ 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`;
@@ -222,6 +240,17 @@ export const certManagerApplicationAlertProviderFactory = ({
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
+ });
+ }
const { alertBefore, applicationIds, profileIds } = ExpirationConditionSchema.parse(input.condition);
return certManagerApplicationAlertDAL.findExpiringCertificates({
@@ -257,10 +286,13 @@ export const certManagerApplicationAlertProviderFactory = ({
targets: TApplicationAlertCertificate[],
viewUrl: string
): TAlertPayload => {
- const eventType = alert.eventType as CertificateAlertEvent;
+ const eventType = alert.eventType as TCertManagerAlertEvent;
const isApplicationAlert = Boolean(alert.resourceId);
- const isExpiration = eventType === CertificateAlertEvent.Expiry;
- const alertBefore = isExpiration ? (alert.condition as { alertBefore?: string } | null)?.alertBefore : undefined;
+ const isSignerAlert = eventType === CodeSigningAlertEvent.SignerCertificateExpiry;
+ const deliveryEventKey = isApplicationAlert ? eventType : toCertificateManagerEventKey(eventType);
+ const alertBefore = isExpiryEvent(eventType)
+ ? (alert.condition as { alertBefore?: string } | null)?.alertBefore
+ : undefined;
return {
alert: {
@@ -273,11 +305,11 @@ export const certManagerApplicationAlertProviderFactory = ({
...(alertBefore ? { condition: alertBefore } : {}),
viewUrl
},
- eventKey: eventType,
+ eventKey: deliveryEventKey,
eventLabel: EVENT_LABELS[eventType],
- webhookType: `com.infisical.${eventType}`,
+ webhookType: `com.infisical.${deliveryEventKey}`,
webhookSource: getWebhookSource({ alertId: alert.id, resourceId: alert.resourceId }),
- resourceKind: "Certificate",
+ resourceKind: isSignerAlert ? "Signer Certificate" : "Certificate",
resourceOwnerKind: isApplicationAlert ? "Application" : "Certificate Manager",
severity: eventSeverity(eventType, targets),
summary: buildSummary(
@@ -298,6 +330,7 @@ export const certManagerApplicationAlertProviderFactory = ({
summary: buildItemSummary(eventType, certificate),
severity: eventSeverity(eventType, [certificate]),
fields: [
+ ...(isSignerAlert && certificate.signerName ? [{ label: "Signer", value: certificate.signerName }] : []),
{ label: "Serial Number", value: certificate.serialNumber },
...(altNames.length ? [{ label: "SANs", value: altNames.join(", ") }] : []),
...(certificate.profileName ? [{ label: "Profile", value: certificate.profileName }] : []),
@@ -320,7 +353,8 @@ export const certManagerApplicationAlertProviderFactory = ({
profileId: certificate.profileId,
profileName: certificate.profileName,
applicationId: certificate.applicationId,
- applicationName: certificate.applicationName
+ applicationName: certificate.applicationName,
+ ...(isSignerAlert ? { signerId: certificate.signerId, signerName: certificate.signerName } : {})
}
};
})
@@ -331,7 +365,7 @@ export const certManagerApplicationAlertProviderFactory = ({
if (input.action === AlertAuditAction.TestChannel) {
const { test } = input;
return {
- type: EventType.TEST_PKI_CERTIFICATE_ALERT_CHANNEL,
+ type: EventType.TEST_CERTIFICATE_MANAGER_ALERT_CHANNEL,
metadata: {
alertId: test.alertId,
alertName: test.alertName ?? null,
@@ -360,9 +394,9 @@ export const certManagerApplicationAlertProviderFactory = ({
applications: withNames(applicationIds),
profiles: withNames(profileIds)
};
- if (input.action === AlertAuditAction.Create) return { type: EventType.CREATE_PKI_CERTIFICATE_ALERT, metadata };
- if (input.action === AlertAuditAction.Update) return { type: EventType.UPDATE_PKI_CERTIFICATE_ALERT, metadata };
- return { type: EventType.DELETE_PKI_CERTIFICATE_ALERT, metadata };
+ 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 => {
@@ -421,7 +455,7 @@ export const certManagerApplicationAlertProviderFactory = ({
event: PostHogEventTypes.PkiAlertCreated,
properties: {
...properties,
- alertType: TELEMETRY_ALERT_TYPE_BY_EVENT[eventType as CertificateAlertEvent]
+ alertType: TELEMETRY_ALERT_TYPE_BY_EVENT[eventType as TCertManagerAlertEvent]
}
};
case AlertTelemetryAction.Update:
@@ -434,9 +468,10 @@ export const certManagerApplicationAlertProviderFactory = ({
const $assertCertificateManagerPermission = async ({
action,
projectId,
+ eventType,
actor
}: TAlertPermissionInput & { projectId: string }) => {
- const { permission } = await permissionService.getProjectPermission({
+ const { permission, hasRole } = await permissionService.getProjectPermission({
actor: actor.actor,
actorId: actor.actorId,
projectId,
@@ -447,7 +482,23 @@ export const certManagerApplicationAlertProviderFactory = ({
ForbiddenError.from(permission).throwUnlessCan(PERMISSION_ACTIONS[action], ProjectPermissionSub.PkiAlerts);
const definesDelivery = action === AlertPermissionAction.Create || action === AlertPermissionAction.Edit;
- if (definesDelivery && !canReadAllCertificates(permission)) {
+ 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)
+ )
+ ) {
throw new ForbiddenRequestError({
message:
"Certificate Manager alerts send certificate details from every application, so they require permission to read all certificates. Create the alert on an application instead."
@@ -456,11 +507,18 @@ export const certManagerApplicationAlertProviderFactory = ({
};
const assertPermission = async (input: TAlertPermissionInput): Promise<void> => {
- const { action, projectId, resourceId, actor } = input;
+ const { action, projectId, resourceId, eventType, 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;
@@ -529,14 +587,14 @@ export const certManagerApplicationAlertProviderFactory = ({
const missingApplicationIds = addedApplicationIds.filter((id) => !foundApplicationIdSet.has(id.toLowerCase()));
if (missingApplicationIds.length) {
throw new NotFoundError({
- message: `Application(s) not found in Certificate Manager: ${formatIds(missingApplicationIds)}`
+ message: `${missingApplicationIds.length === 1 ? "Application" : "Applications"} not found in Certificate Manager: ${formatIds(missingApplicationIds)}`
});
}
const foundProfileIdSet = toIdSet(foundProfileIds);
const missingProfileIds = addedProfileIds.filter((id) => !foundProfileIdSet.has(id.toLowerCase()));
if (missingProfileIds.length) {
throw new NotFoundError({
- message: `Certificate profile(s) not found in Certificate Manager: ${formatIds(missingProfileIds)}`
+ message: `${missingProfileIds.length === 1 ? "Certificate profile" : "Certificate profiles"} not found in Certificate Manager: ${formatIds(missingProfileIds)}`
});
}
};
@@ -607,6 +665,11 @@ 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,
diff --git a/backend/src/services/certificate/certificate-alert-events.ts b/backend/src/services/certificate/certificate-alert-events.ts
index 9f5feea73e..b4ff147b84 100644
--- a/backend/src/services/certificate/certificate-alert-events.ts
+++ b/backend/src/services/certificate/certificate-alert-events.ts
@@ -13,6 +13,10 @@ 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/docs/documentation/platform/pki/settings/alerts.mdx b/docs/documentation/platform/pki/settings/alerts.mdx
index 964c1a69ad..e6fa661e63 100644
--- a/docs/documentation/platform/pki/settings/alerts.mdx
+++ b/docs/documentation/platform/pki/settings/alerts.mdx
@@ -6,12 +6,13 @@ description: "Get notified about certificate events anywhere in Certificate Mana
An alert under **Settings** > **Alerts** covers certificates across Certificate Manager for one event, whether or not they belong to an [Application](/documentation/platform/pki/applications/overview). Without filters, it covers every certificate. Use a Certificate Manager alert when a team needs to hear about certificates across several applications. To alert on a single application, create an [application alert](/documentation/platform/pki/applications/alerting/overview) instead.
-Certificate Manager alerts use the same events and [notification channels](/documentation/platform/pki/applications/alerting/overview#notification-channels) as application alerts.
+Certificate Manager alerts use the same events and [notification channels](/documentation/platform/pki/applications/alerting/overview#notification-channels) as application alerts. They can also alert on [signer certificate expiration](#signer-certificate-expiration) for **Code Signing**.
## Prerequisites
- The **Create** action on **PKI Alerts**, which only the Certificate Manager **Admin** role has by default
- The **Read** action on **Certificates** with no conditions, because the alert sends details of certificates from every application. Editing an alert needs it too.
+- For a **Signer Certificate Expiration** alert, the **Admin** role instead, because the alert sends details of every signer's certificate, including signers you aren't a member of
- For Slack, PagerDuty, and webhook channels, the Enterprise plan. Email channels are available on every plan.
- For email alerts, recipients who are organization members, or addresses on one of your organization's [verified email domains](/documentation/platform/email-domain)
@@ -25,10 +26,10 @@ Certificate Manager alerts use the same events and [notification channels](/docu
Select **Create Alert**.
</Step>
<Step>
- Select the **Alert Type**, then enter an **Alert Name** and an optional **Description**. For an expiration alert, enter **Alert Before** as a number and a unit, for example `30d` or `2w`, up to 365 days. Turn on **Repeat daily until expiry** to get a reminder every day. See [how often expiration alerts repeat](/documentation/platform/pki/applications/alerting/overview#faq). Select **Continue**.
+ Select the **Alert Type** from the **Certificate Lifecycle** or **Code Signing** group, then enter an **Alert Name** and an optional **Description**. For an expiration alert, enter **Alert Before** as a number and a unit, for example `30d` or `2w`, up to 365 days. Turn on **Repeat daily until expiry** to get a reminder every day. See [how often expiration alerts repeat](/documentation/platform/pki/applications/alerting/overview#faq). Select **Continue**.
</Step>
<Step>
- On the **Filters** step, optionally select **Add Filter** to narrow the alert by **Applications** or **Certificate Profiles**. See [which certificates an alert covers](#which-certificates-an-alert-covers). **Matched Certificates** lists the active certificates the alert covers. After you change a filter, select **Reload Preview** to update the list. Select **Continue**.
+ On the **Filters** step, optionally select **Add Filter** to narrow the alert by **Applications** or **Certificate Profiles**. See [which certificates an alert covers](#which-certificates-an-alert-covers). **Matched Certificates** lists the active certificates the alert covers. The list updates as you change filters. Select **Continue**.
</Step>
<Step>
Select **Add Channel** and choose where to send notifications. You can add up to 10 channels. Select **Continue**.
@@ -51,6 +52,12 @@ If you don't add a filter, the alert covers every certificate in Certificate Man
You can select up to 100 applications and 100 profiles.
+## Signer certificate expiration
+
+A **Signer Certificate Expiration** alert, in the **Code Signing** group, warns you before the certificate a signer currently signs with expires. It covers every active signer under **Code Signing** > **Signers**, has no filters, and skips the **Filters** step. It works like a certificate expiration alert: set **Alert Before** and optionally **Repeat daily until expiry**.
+
+Only each signer's current certificate counts. When you reissue a signer's certificate, the alert follows the new one and stops alerting on the one it replaced. Signers that are disabled, failed, or still pending aren't covered.
+
## FAQ
<AccordionGroup>
@@ -65,11 +72,15 @@ You can select up to 100 applications and 100 profiles.
| Field | Certificate Manager alert |
|-------|---------------------------|
+ | `type` | `com.infisical.cert-manager.certificate.<event>`, for example `com.infisical.cert-manager.certificate.issuance` |
+ | `subject` | `cert-manager.certificate.<event>`, for example `cert-manager.certificate.issuance` |
| `source` | `/alerts/<alert-id>` |
| `data.alert.resourceType` | `cert-manager.application`, 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 plus `signerId` and `signerName` to each item.
</Accordion>
</AccordionGroup>
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable.tsx
index 1290bae5ce..1d6a7c738c 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable.tsx
@@ -63,13 +63,13 @@ export const PkiSyncMatchedCertificatesTable = ({
}
return (
- <Table>
+ <Table className="w-full">
<TableHeader>
<TableRow>
<TableHead className="w-full">SAN / CN</TableHead>
- <TableHead className="w-1/5">Serial Number</TableHead>
- <TableHead className="w-1/5">Profile</TableHead>
- <TableHead className="w-1/6">Expires At</TableHead>
+ <TableHead className="whitespace-nowrap">Serial Number</TableHead>
+ <TableHead className="whitespace-nowrap">Profile</TableHead>
+ <TableHead className="whitespace-nowrap">Expires At</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -89,17 +89,17 @@ export const PkiSyncMatchedCertificatesTable = ({
</TooltipContent>
</Tooltip>
</TableCell>
- <TableCell className="max-w-0">
+ <TableCell className="whitespace-nowrap">
<div className="font-mono text-xs" title={row.serialNumber ?? ""}>
{truncateCertificateSerialNumber(row.serialNumber ?? "")}
</div>
</TableCell>
- <TableCell className="max-w-0">
+ <TableCell className="max-w-40">
<div className="truncate text-sm" title={row.profileName ?? ""}>
{row.profileName ?? "-"}
</div>
</TableCell>
- <TableCell className="max-w-0">
+ <TableCell className="whitespace-nowrap">
<span className={isExpired ? "text-sm text-danger" : "text-sm"}>
{row.notAfter ? new Date(row.notAfter).toLocaleDateString() : "-"}
</span>
diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.ts
index 25e383c4ef..1c9a249811 100644
--- a/frontend/src/hooks/api/alerts/types.ts
+++ b/frontend/src/hooks/api/alerts/types.ts
@@ -36,7 +36,8 @@ export enum CertificateAlertEventType {
Expiry = "cert-manager.application.certificate.expiry",
Issuance = "cert-manager.application.certificate.issuance",
Renewal = "cert-manager.application.certificate.renewal",
- Revocation = "cert-manager.application.certificate.revocation"
+ Revocation = "cert-manager.application.certificate.revocation",
+ SignerCertificateExpiry = "cert-manager.signer-certificate.expiry"
}
export const MIN_ALERT_BEFORE_DAYS = 1;
@@ -139,6 +140,7 @@ 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/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index de1d5e6bbd..26b89f4db5 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -124,10 +124,10 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.UPDATE_PKI_APPLICATION_ALERT]: "Update application alert",
[EventType.DELETE_PKI_APPLICATION_ALERT]: "Delete application alert",
[EventType.TEST_PKI_APPLICATION_ALERT_CHANNEL]: "Test application alert channel",
- [EventType.CREATE_PKI_CERTIFICATE_ALERT]: "Create Certificate Manager alert",
- [EventType.UPDATE_PKI_CERTIFICATE_ALERT]: "Update Certificate Manager alert",
- [EventType.DELETE_PKI_CERTIFICATE_ALERT]: "Delete Certificate Manager alert",
- [EventType.TEST_PKI_CERTIFICATE_ALERT_CHANNEL]: "Test Certificate Manager alert channel",
+ [EventType.CREATE_CERTIFICATE_MANAGER_ALERT]: "Create Certificate Manager alert",
+ [EventType.UPDATE_CERTIFICATE_MANAGER_ALERT]: "Update Certificate Manager alert",
+ [EventType.DELETE_CERTIFICATE_MANAGER_ALERT]: "Delete Certificate Manager alert",
+ [EventType.TEST_CERTIFICATE_MANAGER_ALERT_CHANNEL]: "Test Certificate Manager alert channel",
[EventType.CREATE_PKI_COLLECTION]: "Create PKI collection",
[EventType.GET_PKI_COLLECTION]: "Get PKI collection",
[EventType.UPDATE_PKI_COLLECTION]: "Update PKI collection",
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index 84352694a4..f7a29a00bb 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -140,10 +140,10 @@ export enum EventType {
UPDATE_PKI_APPLICATION_ALERT = "update-pki-application-alert",
DELETE_PKI_APPLICATION_ALERT = "delete-pki-application-alert",
TEST_PKI_APPLICATION_ALERT_CHANNEL = "test-pki-application-alert-channel",
- CREATE_PKI_CERTIFICATE_ALERT = "create-pki-certificate-alert",
- UPDATE_PKI_CERTIFICATE_ALERT = "update-pki-certificate-alert",
- DELETE_PKI_CERTIFICATE_ALERT = "delete-pki-certificate-alert",
- TEST_PKI_CERTIFICATE_ALERT_CHANNEL = "test-pki-certificate-alert-channel",
+ CREATE_CERTIFICATE_MANAGER_ALERT = "create-certificate-manager-alert",
+ UPDATE_CERTIFICATE_MANAGER_ALERT = "update-certificate-manager-alert",
+ DELETE_CERTIFICATE_MANAGER_ALERT = "delete-certificate-manager-alert",
+ TEST_CERTIFICATE_MANAGER_ALERT_CHANNEL = "test-certificate-manager-alert-channel",
CREATE_PKI_COLLECTION = "create-pki-collection",
GET_PKI_COLLECTION = "get-pki-collection",
UPDATE_PKI_COLLECTION = "update-pki-collection",
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx
index 9d4604c1f0..f61ca310d6 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx
@@ -58,12 +58,14 @@ import {
CERTIFICATE_ALERT_EVENT_LABELS,
CERTIFICATE_FILTER_DEFINITIONS,
CertificateAlertScopeKind,
+ CertificateFilterKind,
formatAlertBefore,
getAlertResourceId,
getFilterName,
+ getScopeEventTypes,
+ isFilterableEventType,
pluralize,
TCertificateAlertScope,
- TCertificateFilterKind,
toConditionNames
} from "./types";
@@ -79,8 +81,7 @@ const SCOPE_CARD_CONFIG: Record<
hasFiltersColumn: false
},
[CertificateAlertScopeKind.CertificateManager]: {
- description:
- "Get notified about certificate events anywhere in Certificate Manager, inside or outside an application.",
+ description: "Get notified about certificate events.",
emptyDescription:
"No alerts configured. Create one to get notified about certificate events across Certificate Manager.",
docsUrl: PkiDocsUrls.settings.alerts,
@@ -92,9 +93,13 @@ const AlertFiltersSummary = ({ alert }: { alert: TAlert }) => {
const applicationIds = alert.condition?.applicationIds ?? [];
const profileIds = alert.condition?.profileIds ?? [];
const conditionNames = toConditionNames(alert);
- const namesOf = (kind: TCertificateFilterKind, ids: string[]) =>
+ const namesOf = (kind: CertificateFilterKind, ids: string[]) =>
ids.map((id) => getFilterName(kind, id, conditionNames)).join(", ");
+ if (!isFilterableEventType(alert.eventType as CertificateAlertEventType)) {
+ return <span className="text-muted">All signers</span>;
+ }
+
if (!applicationIds.length && !profileIds.length) {
return <span className="text-muted">All certificates</span>;
}
@@ -115,15 +120,17 @@ const AlertFiltersSummary = ({ alert }: { alert: TAlert }) => {
{applicationIds.length > 0 && (
<span>
<span className="text-muted">
- {CERTIFICATE_FILTER_DEFINITIONS.applicationIds.label}:{" "}
+ {CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Applications].label}:{" "}
</span>
- {namesOf("applicationIds", applicationIds)}
+ {namesOf(CertificateFilterKind.Applications, applicationIds)}
</span>
)}
{profileIds.length > 0 && (
<span>
- <span className="text-muted">{CERTIFICATE_FILTER_DEFINITIONS.profileIds.label}: </span>
- {namesOf("profileIds", profileIds)}
+ <span className="text-muted">
+ {CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Profiles].label}:{" "}
+ </span>
+ {namesOf(CertificateFilterKind.Profiles, profileIds)}
</span>
)}
</TooltipContent>
@@ -268,6 +275,7 @@ const AlertRow = ({
type Props = {
projectId: string;
scope: TCertificateAlertScope;
+ allowedEventTypes?: CertificateAlertEventType[];
canCreate: boolean;
canEdit: boolean;
canDelete: boolean;
@@ -276,6 +284,7 @@ type Props = {
export const ApplicationAlertsCard = ({
projectId,
scope,
+ allowedEventTypes,
canCreate,
canEdit,
canDelete
@@ -300,7 +309,11 @@ export const ApplicationAlertsCard = ({
scope.kind === CertificateAlertScopeKind.Application
? alerts.map((alert) => alert.eventType as CertificateAlertEventType)
: [];
- const hasAllEventTypes = Object.values(CertificateAlertEventType).every((eventType) =>
+ const isEventTypeAllowed = (eventType: string) =>
+ !allowedEventTypes || allowedEventTypes.includes(eventType as CertificateAlertEventType);
+ const creatableEventTypes = getScopeEventTypes(scope).filter(isEventTypeAllowed);
+ const canCreateAny = canCreate && creatableEventTypes.length > 0;
+ const hasAllEventTypes = creatableEventTypes.every((eventType) =>
usedEventTypes.includes(eventType)
);
const [alertModal, setAlertModal] = useState<{
@@ -341,7 +354,7 @@ export const ApplicationAlertsCard = ({
<Button
variant="outline"
onClick={() => setAlertModal({ isOpen: true })}
- isDisabled={!canCreate || hasAllEventTypes}
+ isDisabled={!canCreateAny || hasAllEventTypes}
>
<PlusIcon />
Create Alert
@@ -353,7 +366,13 @@ export const ApplicationAlertsCard = ({
You don&apos;t have permission to create alerts
</TooltipContent>
)}
- {canCreate && hasAllEventTypes && (
+ {canCreate && !canCreateAny && (
+ <TooltipContent side="left">
+ Creating an alert requires permission to read all certificates, or the Admin role
+ for signer alerts
+ </TooltipContent>
+ )}
+ {canCreateAny && hasAllEventTypes && (
<TooltipContent side="left">
This application already has an alert for every alert type
</TooltipContent>
@@ -403,7 +422,7 @@ export const ApplicationAlertsCard = ({
onDelete={() =>
setDeleteAlertModal({ isOpen: true, alertId: a.id, name: a.name })
}
- canEdit={canEdit}
+ canEdit={canEdit && isEventTypeAllowed(a.eventType)}
canDelete={canDelete}
scope={scope}
/>
@@ -421,6 +440,7 @@ export const ApplicationAlertsCard = ({
alert={alerts.find((a) => a.id === alertModal.alertId)}
isReadOnly={alertModal.isReadOnly}
usedEventTypes={usedEventTypes}
+ allowedEventTypes={creatableEventTypes}
/>
<DeleteConfirmDialog
isOpen={deleteAlertModal.isOpen}
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 f3d1e50e0d..121ec99d42 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useState } from "react";
-import { FormProvider, useFieldArray, useForm } from "react-hook-form";
+import { FormProvider, useFieldArray, useForm, useWatch } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { BellIcon } from "lucide-react";
@@ -63,6 +63,7 @@ type Props = {
alert?: TAlert;
isReadOnly?: boolean;
usedEventTypes: CertificateAlertEventType[];
+ allowedEventTypes: CertificateAlertEventType[];
};
type WizardProps = Omit<Props, "isOpen"> & {
@@ -77,12 +78,11 @@ const CertificateAlertWizard = ({
alert,
isReadOnly = false,
usedEventTypes,
+ allowedEventTypes,
members,
onDirtyChange
}: WizardProps) => {
const isEditing = Boolean(alert);
- const steps = getSteps(scope);
- const [step, setStep] = useState(isReadOnly ? steps.length - 1 : 0);
const createAlert = useCreateAlert();
const updateAlert = useUpdateAlert();
@@ -92,9 +92,12 @@ const CertificateAlertWizard = ({
defaultValues: alert
? toCertificateAlertForm(alert, members)
: emptyCertificateAlertForm(
- Object.values(CertificateAlertEventType).find((event) => !usedEventTypes.includes(event))
+ allowedEventTypes.find((event) => !usedEventTypes.includes(event))
)
});
+ const eventType = useWatch({ control: form.control, name: "eventType" });
+ const steps = getSteps(scope, eventType);
+ const [step, setStep] = useState(isReadOnly ? steps.length - 1 : 0);
const { fields, append, remove } = useFieldArray({ control: form.control, name: "channels" });
const { isDirty } = form.formState;
@@ -219,6 +222,7 @@ const CertificateAlertWizard = ({
scope={scope}
isEditing={isEditing}
usedEventTypes={usedEventTypes}
+ allowedEventTypes={allowedEventTypes}
/>
)}
{currentStep.key === CertificateAlertStep.Filters && (
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateFilterSelects.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateFilterSelects.tsx
index b2794551c8..7a6a72d5d9 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateFilterSelects.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateFilterSelects.tsx
@@ -6,7 +6,7 @@ import { MAX_CERTIFICATE_ALERT_FILTER_IDS } from "@app/hooks/api/alerts";
import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";
import { useListPkiApplications } from "@app/hooks/api/pkiApplications";
-import { getFilterName, TCertificateFilterKind } from "./types";
+import { CertificateFilterKind, getFilterName } from "./types";
type TFilterOption = { id: string; name: string };
@@ -26,7 +26,7 @@ const FilterCombobox = ({
onSearchChange,
placeholder
}: Props & {
- kind: TCertificateFilterKind;
+ kind: CertificateFilterKind;
options: TFilterOption[];
isLoading: boolean;
onSearchChange: (search: string) => void;
@@ -71,7 +71,7 @@ export const ApplicationFilterSelect = (props: Props) => {
return (
<FilterCombobox
{...props}
- kind="applicationIds"
+ kind={CertificateFilterKind.Applications}
options={options}
isLoading={isPending}
onSearchChange={setSearch}
@@ -95,7 +95,7 @@ export const ProfileFilterSelect = (props: Props) => {
return (
<FilterCombobox
{...props}
- kind="profileIds"
+ kind={CertificateFilterKind.Profiles}
options={options}
isLoading={isPending}
onSearchChange={setSearch}
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 d51b57be77..69763d7470 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx
@@ -1,5 +1,5 @@
import { useState } from "react";
-import { FieldArrayWithId, UseFormReturn } from "react-hook-form";
+import { FieldArrayWithId, UseFormReturn, useWatch } from "react-hook-form";
import { BellIcon } from "lucide-react";
import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
@@ -149,6 +149,7 @@ export const ChannelsStep = ({
members: TMemberEmails;
}) => {
const channelsError = form.formState.errors.channels?.root ?? form.formState.errors.channels;
+ const eventType = useWatch({ control: form.control, name: "eventType" });
if (!fields.length) {
return (
@@ -176,6 +177,7 @@ export const ChannelsStep = ({
resourceType={CertificateAlertResourceType.Application}
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/DetailsStep.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/DetailsStep.tsx
index 734e9e0332..0f81b988da 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/DetailsStep.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/DetailsStep.tsx
@@ -10,7 +10,10 @@ import {
Input,
Select,
SelectContent,
+ SelectGroup,
SelectItem,
+ SelectLabel,
+ SelectSeparator,
SelectTrigger,
SelectValue,
TextArea,
@@ -20,7 +23,11 @@ import { CertificateAlertEventType } from "@app/hooks/api/alerts";
import {
CERTIFICATE_ALERT_EVENT_LABELS,
+ CertificateFilterKind,
getAlertEventDescription,
+ getScopeEventGroups,
+ isExpiryEventType,
+ isFilterableEventType,
TCertificateAlertForm,
TCertificateAlertScope
} from "./types";
@@ -30,10 +37,29 @@ type Props = {
scope: TCertificateAlertScope;
isEditing: boolean;
usedEventTypes: CertificateAlertEventType[];
+ allowedEventTypes: CertificateAlertEventType[];
};
-export const DetailsStep = ({ form, scope, isEditing, usedEventTypes }: Props) => {
+export const DetailsStep = ({
+ form,
+ scope,
+ isEditing,
+ usedEventTypes,
+ allowedEventTypes
+}: Props) => {
const eventType = useWatch({ control: form.control, name: "eventType" });
+ const eventGroups = getScopeEventGroups(scope);
+
+ const onEventTypeChange = (
+ next: CertificateAlertEventType,
+ onChange: (value: string) => void
+ ) => {
+ onChange(next);
+ if (!isFilterableEventType(next)) {
+ form.setValue(CertificateFilterKind.Applications, undefined, { shouldDirty: true });
+ form.setValue(CertificateFilterKind.Profiles, undefined, { shouldDirty: true });
+ }
+ };
return (
<FieldGroup>
@@ -44,19 +70,34 @@ export const DetailsStep = ({ form, scope, isEditing, usedEventTypes }: Props) =
<Field>
<FieldLabel>Alert Type</FieldLabel>
<FieldContent>
- <Select value={field.value} onValueChange={field.onChange} disabled={isEditing}>
+ <Select
+ value={field.value}
+ onValueChange={(next) =>
+ onEventTypeChange(next as CertificateAlertEventType, field.onChange)
+ }
+ disabled={isEditing}
+ >
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent position="popper">
- {Object.values(CertificateAlertEventType).map((event) => (
- <SelectItem
- key={event}
- value={event}
- disabled={!isEditing && usedEventTypes.includes(event)}
- >
- {CERTIFICATE_ALERT_EVENT_LABELS[event]}
- </SelectItem>
+ {eventGroups.map((group, index) => (
+ <SelectGroup key={group.label}>
+ {index > 0 && <SelectSeparator />}
+ <SelectLabel>{group.label}</SelectLabel>
+ {group.events.map((event) => (
+ <SelectItem
+ key={event}
+ value={event}
+ disabled={
+ !isEditing &&
+ (usedEventTypes.includes(event) || !allowedEventTypes.includes(event))
+ }
+ >
+ {CERTIFICATE_ALERT_EVENT_LABELS[event]}
+ </SelectItem>
+ ))}
+ </SelectGroup>
))}
</SelectContent>
</Select>
@@ -101,7 +142,7 @@ export const DetailsStep = ({ form, scope, isEditing, usedEventTypes }: Props) =
</Field>
)}
/>
- {eventType === CertificateAlertEventType.Expiry && (
+ {isExpiryEventType(eventType) && (
<>
<Controller
name="alertBefore"
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/FiltersStep.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/FiltersStep.tsx
index 80183e51dd..856dbb8eb9 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/FiltersStep.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/FiltersStep.tsx
@@ -1,6 +1,6 @@
-import { Fragment, useState } from "react";
+import { Fragment, useEffect, useState } from "react";
import { UseFormReturn, useWatch } from "react-hook-form";
-import { FilterIcon, PlusIcon, RefreshCwIcon, TrashIcon, TriangleAlertIcon } from "lucide-react";
+import { FilterIcon, PlusIcon, TrashIcon } from "lucide-react";
import { PkiSyncMatchedCertificatesTable } from "@app/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable";
import {
@@ -17,10 +17,7 @@ import {
FieldError,
FieldLabel,
IconButton,
- Pagination,
- Tooltip,
- TooltipContent,
- TooltipTrigger
+ Pagination
} from "@app/components/v3";
import { useListWorkspaceCertificates } from "@app/hooks/api";
import { CertStatus } from "@app/hooks/api/certificates/enums";
@@ -28,33 +25,42 @@ import { CertStatus } from "@app/hooks/api/certificates/enums";
import { ApplicationFilterSelect, ProfileFilterSelect } from "./CertificateFilterSelects";
import {
CERTIFICATE_FILTER_DEFINITIONS,
- hasUnfinishedFilter,
+ CertificateFilterKind,
NO_FILTERS_DESCRIPTION,
- TCertificateAlertForm,
- TCertificateFilterKind
+ TCertificateAlertForm
} from "./types";
const MATCHED_PAGE_SIZE = 20;
-const FILTER_KINDS = Object.keys(CERTIFICATE_FILTER_DEFINITIONS) as TCertificateFilterKind[];
+const FILTER_KINDS = Object.values(CertificateFilterKind);
type Props = { form: UseFormReturn<TCertificateAlertForm>; projectId: string };
export const FiltersStep = ({ form, projectId }: Props) => {
- const applicationIds = useWatch({ control: form.control, name: "applicationIds" });
- const profileIds = useWatch({ control: form.control, name: "profileIds" });
+ const applicationIds = useWatch({
+ control: form.control,
+ name: CertificateFilterKind.Applications
+ });
+ const profileIds = useWatch({ control: form.control, name: CertificateFilterKind.Profiles });
const conditionNames = useWatch({ control: form.control, name: "conditionNames" });
const filters = { applicationIds, profileIds };
- const [previewFilters, setPreviewFilters] = useState(filters);
+ const previewFilters = {
+ applicationIds: applicationIds?.length ? applicationIds : undefined,
+ profileIds: profileIds?.length ? profileIds : undefined
+ };
+ const previewKey = JSON.stringify(previewFilters);
const [page, setPage] = useState(1);
- const isStale = JSON.stringify(filters) !== JSON.stringify(previewFilters);
- const isUnfinished = hasUnfinishedFilter(filters);
+
+ useEffect(() => {
+ setPage(1);
+ }, [previewKey]);
const {
data: preview,
isFetching: isPreviewing,
- refetch: refetchPreview
+ isError: isPreviewError,
+ refetch: retryPreview
} = useListWorkspaceCertificates({
projectId,
offset: (page - 1) * MATCHED_PAGE_SIZE,
@@ -64,43 +70,41 @@ export const FiltersStep = ({ form, projectId }: Props) => {
profileIds: previewFilters.profileIds
});
- const reloadPreview = () => {
- setPage(1);
- if (isStale) setPreviewFilters(filters);
- else refetchPreview().catch(() => {});
- };
-
- const setFilter = (kind: TCertificateFilterKind, ids: string[] | undefined) =>
+ const setFilter = (kind: CertificateFilterKind, ids: string[] | undefined) =>
form.setValue(kind, ids, { shouldDirty: true, shouldValidate: true });
- const addFilter = (kind: TCertificateFilterKind) =>
- form.setValue(kind, [], { shouldDirty: true });
+ const addFilter = (kind: CertificateFilterKind) => form.setValue(kind, [], { shouldDirty: true });
const presentKinds = FILTER_KINDS.filter((kind) => filters[kind] !== undefined);
const addableKinds = FILTER_KINDS.filter((kind) => filters[kind] === undefined);
const matchedCount = preview?.totalCount ?? 0;
const isPreviewFiltered = FILTER_KINDS.some((kind) => previewFilters[kind] !== undefined);
+ const hasUnfinishedFilter = FILTER_KINDS.some((kind) => filters[kind]?.length === 0);
const certificatesLabel = `${matchedCount} active certificate${matchedCount === 1 ? "" : "s"}`;
let previewSummary = "Loading the certificates this alert covers.";
- if (preview && !isPreviewing) {
+ if (isPreviewError && !isPreviewing) {
+ previewSummary = "The matched certificates couldn't be loaded.";
+ } else if (hasUnfinishedFilter) {
+ previewSummary =
+ "Select at least one value in each filter, or remove it, to update the preview.";
+ } else if (preview && !isPreviewing) {
previewSummary = isPreviewFiltered
? `${certificatesLabel} ${matchedCount === 1 ? "matches" : "match"} these filters.`
- : `${certificatesLabel} in Certificate Manager.`;
+ : `This alert covers ${matchedCount > 1 ? "all " : ""}${certificatesLabel}.`;
}
- const reloadButton = (
- <Button
- type="button"
- size="xs"
- variant={isStale ? "warning" : "outline"}
- isDisabled={isPreviewing || isUnfinished}
- onClick={reloadPreview}
- >
- <RefreshCwIcon className="size-3" />
- Reload Preview
- {isStale && <TriangleAlertIcon className="size-3" />}
- </Button>
- );
+ let previewEmptyState = isPreviewFiltered
+ ? {
+ title: "No certificates match",
+ description: "No active certificate matches these filters yet."
+ }
+ : { title: "No active certificates", description: "There are no active certificates yet." };
+ if (isPreviewError) {
+ previewEmptyState = {
+ title: "Certificates couldn't be loaded",
+ description: "Select Retry to try again."
+ };
+ }
return (
<div className="flex flex-col">
@@ -115,7 +119,9 @@ export const FiltersStep = ({ form, projectId }: Props) => {
<div className="mt-3 flex flex-col gap-3">
{presentKinds.map((kind, index) => {
const Select =
- kind === "applicationIds" ? ApplicationFilterSelect : ProfileFilterSelect;
+ kind === CertificateFilterKind.Applications
+ ? ApplicationFilterSelect
+ : ProfileFilterSelect;
const { label } = CERTIFICATE_FILTER_DEFINITIONS[kind];
return (
<Fragment key={kind}>
@@ -196,37 +202,31 @@ export const FiltersStep = ({ form, projectId }: Props) => {
</div>
)}
- <div className="mt-8 flex items-start justify-between gap-4">
+ <div className="mt-8 flex items-end justify-between gap-3">
<div>
<p className="text-sm font-medium text-foreground">Matched Certificates</p>
<p className="mt-0.5 text-xs text-muted">{previewSummary}</p>
</div>
- {isStale ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <span>{reloadButton}</span>
- </TooltipTrigger>
- <TooltipContent>
- {isUnfinished
- ? "A filter is unfinished. Complete it, then reload the preview."
- : "Filters changed. Reload the preview to see what they match now."}
- </TooltipContent>
- </Tooltip>
- ) : (
- reloadButton
+ {isPreviewError && (
+ <Button
+ type="button"
+ variant="outline"
+ size="xs"
+ isPending={isPreviewing}
+ isDisabled={isPreviewing}
+ onClick={() => retryPreview()}
+ >
+ Retry
+ </Button>
)}
</div>
<div className="mt-3">
<PkiSyncMatchedCertificatesTable
rows={preview?.certificates ?? []}
- isLoading={isPreviewing}
- emptyTitle={isPreviewFiltered ? "No certificates match" : "No active certificates"}
- emptyDescription={
- isPreviewFiltered
- ? "No active certificate matches these filters yet."
- : "There are no active certificates yet."
- }
+ isLoading={!preview && !isPreviewError}
+ emptyTitle={previewEmptyState.title}
+ emptyDescription={previewEmptyState.description}
/>
{matchedCount > MATCHED_PAGE_SIZE && (
<Pagination
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsx
index d9a1c5346c..42b7eea1c2 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsx
@@ -7,7 +7,6 @@ import {
ALERT_CHANNEL_TYPE_LABELS,
AlertChannelType,
AlertPrincipalType,
- CertificateAlertEventType,
TChannelForm
} from "@app/hooks/api/alerts";
@@ -15,8 +14,11 @@ import {
CERTIFICATE_ALERT_EVENT_LABELS,
CERTIFICATE_FILTER_DEFINITIONS,
CertificateAlertScopeKind,
+ CertificateFilterKind,
formatAlertBefore,
getFilterName,
+ isExpiryEventType,
+ isFilterableEventType,
NO_FILTERS_DESCRIPTION,
TCertificateAlertForm,
TCertificateAlertScope,
@@ -79,23 +81,25 @@ const FilterDetails = ({
profileIds: string[];
conditionNames: Record<string, string>;
}) => {
- const getApplicationName = (id: string) => getFilterName("applicationIds", id, conditionNames);
- const getProfileName = (id: string) => getFilterName("profileIds", id, conditionNames);
+ const getApplicationName = (id: string) =>
+ getFilterName(CertificateFilterKind.Applications, id, conditionNames);
+ const getProfileName = (id: string) =>
+ getFilterName(CertificateFilterKind.Profiles, id, conditionNames);
return (
<>
- <Detail label={CERTIFICATE_FILTER_DEFINITIONS.applicationIds.label}>
+ <Detail label={CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Applications].label}>
{applicationIds.length ? (
<PkiSyncFilterValueBadges values={applicationIds.map(getApplicationName)} />
) : (
- CERTIFICATE_FILTER_DEFINITIONS.applicationIds.allLabel
+ CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Applications].allLabel
)}
</Detail>
- <Detail label={CERTIFICATE_FILTER_DEFINITIONS.profileIds.label}>
+ <Detail label={CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Profiles].label}>
{profileIds.length ? (
<PkiSyncFilterValueBadges values={profileIds.map(getProfileName)} />
) : (
- CERTIFICATE_FILTER_DEFINITIONS.profileIds.allLabel
+ CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Profiles].allLabel
)}
</Detail>
</>
@@ -104,7 +108,7 @@ const FilterDetails = ({
export const ReviewStep = ({ form, scope, members }: Props) => {
const values = useWatch({ control: form.control }) as TCertificateAlertForm;
- const isExpiry = values.eventType === CertificateAlertEventType.Expiry;
+ const isExpiry = isExpiryEventType(values.eventType);
return (
<div className="flex flex-col gap-8">
@@ -127,21 +131,22 @@ export const ReviewStep = ({ form, scope, members }: Props) => {
</div>
</Section>
- {scope.kind === CertificateAlertScopeKind.CertificateManager && (
- <Section title="Certificate Filters">
- {values.applicationIds?.length || values.profileIds?.length ? (
- <div className="grid grid-cols-2 gap-x-6 gap-y-4">
- <FilterDetails
- applicationIds={values.applicationIds ?? []}
- profileIds={values.profileIds ?? []}
- conditionNames={values.conditionNames}
- />
- </div>
- ) : (
- <span className="text-sm text-muted">{NO_FILTERS_DESCRIPTION}</span>
- )}
- </Section>
- )}
+ {scope.kind === CertificateAlertScopeKind.CertificateManager &&
+ isFilterableEventType(values.eventType) && (
+ <Section title="Certificate Filters">
+ {values.applicationIds?.length || values.profileIds?.length ? (
+ <div className="grid grid-cols-2 gap-x-6 gap-y-4">
+ <FilterDetails
+ applicationIds={values.applicationIds ?? []}
+ profileIds={values.profileIds ?? []}
+ conditionNames={values.conditionNames}
+ />
+ </div>
+ ) : (
+ <span className="text-sm text-muted">{NO_FILTERS_DESCRIPTION}</span>
+ )}
+ </Section>
+ )}
<Section title="Notification Channels">
<div className="flex flex-col gap-3">
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 d0de0861f2..886ce0eff6 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts
@@ -27,15 +27,67 @@ export const CERTIFICATE_ALERT_EVENT_LABELS: Record<CertificateAlertEventType, s
[CertificateAlertEventType.Expiry]: "Certificate Expiration",
[CertificateAlertEventType.Issuance]: "Certificate Issuance",
[CertificateAlertEventType.Renewal]: "Certificate Renewal",
- [CertificateAlertEventType.Revocation]: "Certificate Revocation"
+ [CertificateAlertEventType.Revocation]: "Certificate Revocation",
+ [CertificateAlertEventType.SignerCertificateExpiry]: "Signer Certificate Expiration"
};
+export enum CertificateAlertAccess {
+ ReadAllCertificates = "read-all-certificates",
+ Admin = "admin"
+}
+
+export const CERTIFICATE_ALERT_EVENT_GROUPS: {
+ label: string;
+ events: CertificateAlertEventType[];
+ scopes: CertificateAlertScopeKind[];
+ requiredAccess: CertificateAlertAccess;
+}[] = [
+ {
+ label: "Certificate Lifecycle",
+ events: [
+ CertificateAlertEventType.Expiry,
+ CertificateAlertEventType.Issuance,
+ CertificateAlertEventType.Renewal,
+ CertificateAlertEventType.Revocation
+ ],
+ scopes: [CertificateAlertScopeKind.Application, CertificateAlertScopeKind.CertificateManager],
+ requiredAccess: CertificateAlertAccess.ReadAllCertificates
+ },
+ {
+ label: "Code Signing",
+ events: [CertificateAlertEventType.SignerCertificateExpiry],
+ scopes: [CertificateAlertScopeKind.CertificateManager],
+ requiredAccess: CertificateAlertAccess.Admin
+ }
+];
+
+export const getEventTypesForAccess = (access: CertificateAlertAccess[]) =>
+ CERTIFICATE_ALERT_EVENT_GROUPS.filter((group) => access.includes(group.requiredAccess)).flatMap(
+ (group) => group.events
+ );
+
+export const getScopeEventGroups = (scope: TCertificateAlertScope) =>
+ CERTIFICATE_ALERT_EVENT_GROUPS.filter((group) => group.scopes.includes(scope.kind));
+
+export const getScopeEventTypes = (scope: TCertificateAlertScope) =>
+ getScopeEventGroups(scope).flatMap((group) => group.events);
+
+export const isExpiryEventType = (eventType: CertificateAlertEventType) =>
+ eventType === CertificateAlertEventType.Expiry ||
+ eventType === CertificateAlertEventType.SignerCertificateExpiry;
+
+export const isFilterableEventType = (eventType: CertificateAlertEventType) =>
+ eventType !== CertificateAlertEventType.SignerCertificateExpiry;
+
const ALERT_EVENT_DESCRIPTIONS: Record<CertificateAlertEventType, (where: string) => string> = {
[CertificateAlertEventType.Expiry]: () => "Fires ahead of a certificate's expiry date.",
[CertificateAlertEventType.Issuance]: (where) =>
`Fires when Infisical issues a certificate ${where}.`,
[CertificateAlertEventType.Renewal]: (where) => `Fires when a certificate ${where} is renewed.`,
- [CertificateAlertEventType.Revocation]: (where) => `Fires when a certificate ${where} is revoked.`
+ [CertificateAlertEventType.Revocation]: (where) =>
+ `Fires when a certificate ${where} is revoked.`,
+ [CertificateAlertEventType.SignerCertificateExpiry]: () =>
+ "Fires ahead of the expiry date of the certificate each signer currently signs with."
};
export const getAlertEventDescription = (
@@ -96,19 +148,22 @@ export const toRecipientEmails = (
return recipient.principalType === AlertPrincipalType.Email ? [recipient.principalId] : [];
});
-export type TCertificateFilterKind = "applicationIds" | "profileIds";
+export enum CertificateFilterKind {
+ Applications = "applicationIds",
+ Profiles = "profileIds"
+}
export const CERTIFICATE_FILTER_DEFINITIONS: Record<
- TCertificateFilterKind,
+ CertificateFilterKind,
{ label: string; hint: string; allLabel: string; unknownLabel: string }
> = {
- applicationIds: {
+ [CertificateFilterKind.Applications]: {
label: "Applications",
hint: "Certificates in one of these applications",
allLabel: "All applications",
unknownLabel: "Unknown application"
},
- profileIds: {
+ [CertificateFilterKind.Profiles]: {
label: "Certificate Profiles",
hint: "Issued from one of these profiles",
allLabel: "All certificate profiles",
@@ -116,11 +171,10 @@ export const CERTIFICATE_FILTER_DEFINITIONS: Record<
}
};
-export const NO_FILTERS_DESCRIPTION =
- "No filters. This alert covers every certificate in Certificate Manager.";
+export const NO_FILTERS_DESCRIPTION = "No filters. This alert covers every certificate.";
export const getFilterName = (
- kind: TCertificateFilterKind,
+ kind: CertificateFilterKind,
id: string,
conditionNames: Record<string, string>
) => conditionNames[id] ?? CERTIFICATE_FILTER_DEFINITIONS[kind].unknownLabel;
@@ -132,14 +186,11 @@ export const toConditionNames = (alert: TAlert): Record<string, string> =>
.flatMap(({ id, name }) => (name ? [[id, name]] : []))
);
-export const isUnfinishedFilter = (ids?: string[]) => ids?.length === 0;
-
-export const hasUnfinishedFilter = (filters: Partial<Record<TCertificateFilterKind, string[]>>) =>
- isUnfinishedFilter(filters.applicationIds) || isUnfinishedFilter(filters.profileIds);
+const isUnfinishedFilter = (ids?: string[]) => ids?.length === 0;
-const UNFINISHED_FILTER_MESSAGES: Record<TCertificateFilterKind, string> = {
- applicationIds: "Select at least one application, or remove this filter",
- profileIds: "Select at least one profile, or remove this filter"
+const UNFINISHED_FILTER_MESSAGES: Record<CertificateFilterKind, string> = {
+ [CertificateFilterKind.Applications]: "Select at least one application, or remove this filter",
+ [CertificateFilterKind.Profiles]: "Select at least one profile, or remove this filter"
};
export enum CertificateAlertStep {
@@ -176,8 +227,8 @@ const STEP_DEFINITIONS = {
}
};
-export const getSteps = (scope: TCertificateAlertScope) =>
- (scope.kind === CertificateAlertScopeKind.CertificateManager
+export const getSteps = (scope: TCertificateAlertScope, eventType: CertificateAlertEventType) =>
+ (scope.kind === CertificateAlertScopeKind.CertificateManager && isFilterableEventType(eventType)
? [
CertificateAlertStep.Details,
CertificateAlertStep.Filters,
@@ -213,12 +264,12 @@ export const certificateAlertFormSchema = z
channels: z.array(channelFormSchema).min(1, "Add at least one channel").max(MAX_CHANNELS)
})
.superRefine((form, ctx) => {
- (Object.keys(UNFINISHED_FILTER_MESSAGES) as TCertificateFilterKind[]).forEach((kind) => {
+ Object.values(CertificateFilterKind).forEach((kind) => {
if (isUnfinishedFilter(form[kind])) {
ctx.addIssue({ code: "custom", path: [kind], message: UNFINISHED_FILTER_MESSAGES[kind] });
}
});
- if (form.eventType !== CertificateAlertEventType.Expiry) return;
+ if (!isExpiryEventType(form.eventType)) return;
const days = alertBeforeToDays(form.alertBefore);
if (days === null) {
ctx.addIssue({
@@ -245,7 +296,7 @@ export const STEP_FIELDS: Partial<Record<CertificateAlertStep, (keyof TCertifica
"alertBefore",
"dailyReminder"
],
- [CertificateAlertStep.Filters]: ["applicationIds", "profileIds"],
+ [CertificateAlertStep.Filters]: Object.values(CertificateFilterKind),
[CertificateAlertStep.Channels]: ["channels"]
};
@@ -300,14 +351,15 @@ export const toCertificateAlertForm = (
export const toCondition = (scope: TCertificateAlertScope, form: TCertificateAlertForm) => {
const filters =
- scope.kind === CertificateAlertScopeKind.CertificateManager
+ scope.kind === CertificateAlertScopeKind.CertificateManager &&
+ isFilterableEventType(form.eventType)
? {
...(form.applicationIds?.length ? { applicationIds: form.applicationIds } : {}),
...(form.profileIds?.length ? { profileIds: form.profileIds } : {})
}
: {};
- if (form.eventType === CertificateAlertEventType.Expiry) {
+ if (isExpiryEventType(form.eventType)) {
return {
alertBefore: form.alertBefore.trim(),
dailyReminder: form.dailyReminder,
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/AlertsTab.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/AlertsTab.tsx
index 3c92a9efaf..577f97118a 100644
--- a/frontend/src/pages/cert-manager/SettingsPage/components/AlertsTab.tsx
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/AlertsTab.tsx
@@ -5,34 +5,42 @@ import {
useProjectPermission
} from "@app/context";
import { ProjectPermissionCertificateActions } from "@app/context/ProjectPermissionContext/types";
+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
import { ApplicationAlertsCard } from "../../ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard";
-import { CertificateAlertScopeKind } from "../../ApplicationDetailsByIDPage/components/ApplicationAlerts/types";
+import {
+ CertificateAlertAccess,
+ CertificateAlertScopeKind,
+ getEventTypesForAccess
+} from "../../ApplicationDetailsByIDPage/components/ApplicationAlerts/types";
export const AlertsTab = () => {
const { currentProject } = useProject();
- const { permission } = useProjectPermission();
+ const { permission, hasProjectRole } = useProjectPermission();
- const certificateReadRules = permission.rulesFor(
- ProjectPermissionCertificateActions.Read,
- ProjectPermissionSub.Certificates
- );
- const canReadAllCertificates =
- certificateReadRules.some((rule) => !rule.inverted && !rule.conditions) &&
- !certificateReadRules.some((rule) => rule.inverted);
+ const isUnconditionalGrant = (rules: ReturnType<typeof permission.rulesFor>) =>
+ rules.some((rule) => !rule.inverted && !rule.conditions) &&
+ !rules.some((rule) => rule.inverted);
+
+ const allowedEventTypes = getEventTypesForAccess([
+ ...(isUnconditionalGrant(
+ permission.rulesFor(
+ ProjectPermissionCertificateActions.Read,
+ ProjectPermissionSub.Certificates
+ )
+ )
+ ? [CertificateAlertAccess.ReadAllCertificates]
+ : []),
+ ...(hasProjectRole(ProjectMembershipRole.Admin) ? [CertificateAlertAccess.Admin] : [])
+ ]);
return (
<ApplicationAlertsCard
projectId={currentProject.id}
scope={{ kind: CertificateAlertScopeKind.CertificateManager }}
- canCreate={
- canReadAllCertificates &&
- permission.can(ProjectPermissionActions.Create, ProjectPermissionSub.PkiAlerts)
- }
- canEdit={
- canReadAllCertificates &&
- permission.can(ProjectPermissionActions.Edit, ProjectPermissionSub.PkiAlerts)
- }
+ allowedEventTypes={allowedEventTypes}
+ canCreate={permission.can(ProjectPermissionActions.Create, ProjectPermissionSub.PkiAlerts)}
+ canEdit={permission.can(ProjectPermissionActions.Edit, ProjectPermissionSub.PkiAlerts)}
canDelete={permission.can(ProjectPermissionActions.Delete, ProjectPermissionSub.PkiAlerts)}
/>
);
diff --git a/frontend/src/views/Alerts/ChannelCard.tsx b/frontend/src/views/Alerts/ChannelCard.tsx
index 7ef4deb6a8..29a5ab7d49 100644
--- a/frontend/src/views/Alerts/ChannelCard.tsx
+++ b/frontend/src/views/Alerts/ChannelCard.tsx
@@ -43,6 +43,7 @@ type Props = {
resourceType: string;
resourceId?: string | null;
alertId?: string;
+ eventType?: string;
onRemove: () => void;
canRemove: boolean;
renderRecipients?: (props: TChannelRecipientsRenderProps) => ReactElement;
@@ -91,6 +92,7 @@ export const ChannelCard = ({
resourceType,
resourceId,
alertId,
+ eventType,
onRemove,
canRemove,
renderRecipients
@@ -123,6 +125,7 @@ export const ChannelCard = ({
resourceId,
projectId: projectId ?? null,
alertId,
+ eventType,
channelId: channel?.id,
channelType,
config,