Skip to content

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

feat: add Certificate Manager-wide certificate alerts

Carlos Monastyrski9579baba5445
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 558029097a..30f1a4603e 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -698,6 +698,8 @@ That's it — CRUD routes, channel creation/rotation, recipient resolution, KMS
**Event-path reads go to the primary, `findEventTargets` included.** An empty read there is terminal (the event is marked delivered and never asked about again), so a replica that hasn't seen the commit loses the notification. `findEnabledForEvent` and the engine's channel lookup already do this; a provider's `findEventTargets` must too, since the target usually commits in the same transaction as the event. The scheduled path keeps the replica because tomorrow's scan asks again.
+**An event only reaches channels that existed when it occurred.** `runAlertForEvent` drops channels created after `occurredAt`, because the outbox retries an event for up to an hour while any channel on any matching alert keeps failing, and each retry looks the alerts up again. Without it, an alert created (or a channel added) during that window is notified about something that happened before it existed.
+
**The history write is retried, then logged, never thrown.** The channels have already sent by then, so a throw can't undo anything and would re-notify on the event path.
Invariants worth knowing before extending it:
@@ -705,9 +707,10 @@ Invariants worth knowing before extending it:
- **The alert module owns no CASL subject.** Each provider reuses its own resource's existing permissions inside `assertPermission`, so authorization stays with the domain that owns the resource.
- **New delivery mediums are channel definitions**, not providers: add one under `src/services/alert/channels/` and register it in `ALERT_CHANNEL_REGISTRY`. `directed: true` means the channel addresses principals and needs recipients (email); undirected channels carry their destination in config. `secretFields` drives masking on read and merge-from-stored on update.
- **Channel configs are encrypted** with the org/project KMS cipher (`alert-channel-crypto-fns.ts`) — never store or return them in plaintext.
-- **One alert per `(scope, resource, event)`**, enforced by `alert_unique_scope_resource_event`. **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`. `assertChannelTypesAllowed` is where a provider gates paid channel types on create and on update (new types only). `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-types.ts`). `getTelemetryEvent` lets a provider map alert create, update and delete to its own PostHog event, so the shared router never branches on a resource type. `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`). The resolver sends to them directly and skips an address that a user recipient on the same channel already covers.
+- **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.
+- **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. The certificate alert DAL does this in `findExpiringCertificates`.
- **Deleting an alertable resource does NOT delete its alerts. You have to reap them yourself.** `alerts.resourceId` is a plain string column with **no foreign key** to the resource's table (a provider's `resourceType` can point at anything), so nothing cascades. Skip the reap and the row survives as a dangling alert whose `findScheduledTargets` matches nothing and whose "view" link 404s. Two helpers on `alertService`, and picking the wrong one is the bug:
- **`deleteAlertsForDeletedResource({ resourceType, resourceId })`** when the resource **row is gone**. It has **no scope filter** and reaps across every org and project. This is required, not just tidier: the same resource can be watched from another org (a root-org identity invited into a child org), so an `orgId`-filtered reap leaves those rows orphaned.
- **`deleteAlertsForResource({ orgId, projectId?, resourceType, resourceId })`** when the resource merely **left a scope** (removed from a project, removed from an org) but still exists. Narrow on purpose: leaving one project must not drop the org-level alert, and leaving one org must not touch another org's alerts. Omitting `projectId` reaps the whole org, which is what org-membership removal wants since it cascades the project memberships.
diff --git a/backend/e2e-test/cert-manager-application-alert-dal.spec.ts b/backend/e2e-test/cert-manager-application-alert-dal.spec.ts
new file mode 100644
index 0000000000..e042d9361d
--- /dev/null
+++ b/backend/e2e-test/cert-manager-application-alert-dal.spec.ts
@@ -0,0 +1,175 @@
+import { randomUUID } from "node:crypto";
+
+import { Knex } from "knex";
+import { afterAll, beforeAll, describe, expect, test } from "vitest";
+
+import { TableName } from "@app/db/schemas";
+import { seedData1 } from "@app/db/seed-data";
+import { AlertRunStatus } from "@app/services/alert/alert-types";
+import { certManagerApplicationAlertDALFactory } from "@app/services/alert/providers/cert-manager-application-alert-dal";
+
+declare const testDb: Knex;
+
+const dal = certManagerApplicationAlertDALFactory(testDb as never);
+
+const PROJECT_ID = seedData1.project.id;
+const ORG_ID = seedData1.organization.id;
+const DAY_MS = 24 * 60 * 60 * 1000;
+const now = new Date();
+const since = new Date(now.getTime() - DAY_MS);
+const tag = randomUUID().slice(0, 8);
+
+const CERTIFICATE_KEYS = ["bothChannels", "oneChannel", "beforeWindow", "oneFailed", "neverAlerted"] as const;
+const certificateIds = {} as Record<(typeof CERTIFICATE_KEYS)[number], string>;
+const allCertificateIds = () => Object.values(certificateIds);
+
+let alertId: string;
+let channelIds: string[];
+
+const insertCertificate = async (key: string, expiresInDays: number) => {
+ const [certificate] = await testDb(TableName.Certificate)
+ .insert({
+ projectId: PROJECT_ID,
+ status: "active",
+ serialNumber: `${tag}-${key}`,
+ friendlyName: `e2e-${tag}`,
+ commonName: `e2e-${tag}-${key}.example.com`,
+ notBefore: now,
+ notAfter: new Date(now.getTime() + expiresInDays * DAY_MS)
+ })
+ .returning("id");
+ return certificate.id;
+};
+
+const insertDelivery = async (
+ certificateId: string,
+ deliveries: { channelId: string; status: AlertRunStatus }[],
+ triggeredAt: Date
+) => {
+ const [history] = await testDb(TableName.AlertHistory)
+ .insert({ alertId, status: AlertRunStatus.SUCCESS, triggeredAt })
+ .returning("id");
+ await testDb(TableName.AlertHistoryTarget).insert(
+ deliveries.map(({ channelId, status }) => ({
+ alertHistoryId: history.id,
+ targetId: certificateId,
+ channelId,
+ channelType: "email",
+ status
+ }))
+ );
+};
+
+const scan = (alreadyAlerted?: { alertId: string; channelIds: string[]; since: Date }) =>
+ dal.findExpiringCertificates({
+ projectId: PROJECT_ID,
+ alertBeforeInterval: "30 days",
+ leadInterval: "1 day",
+ asOf: now,
+ alreadyAlerted
+ });
+
+const ownIds = (rows: { id: string }[]) => rows.map((row) => row.id).filter((id) => allCertificateIds().includes(id));
+
+describe("cert manager certificate alert DAL (postgres)", () => {
+ beforeAll(async () => {
+ const [alert] = await testDb(TableName.Alert)
+ .insert({
+ name: `e2e-${tag}`,
+ resourceType: "cert-manager.application",
+ eventType: "cert-manager.application.certificate.expiry",
+ triggerType: "scheduled",
+ orgId: ORG_ID,
+ projectId: PROJECT_ID,
+ createdByActorId: seedData1.id,
+ createdByActorType: "user"
+ })
+ .returning("id");
+ alertId = alert.id;
+
+ const channels = await testDb(TableName.AlertChannel)
+ .insert(
+ [1, 2].map((index) => ({
+ name: `e2e-${tag}-${index}`,
+ channelType: "email",
+ encryptedConfig: Buffer.from("e2e"),
+ orgId: ORG_ID,
+ createdByActorId: seedData1.id,
+ createdByActorType: "user"
+ }))
+ )
+ .returning("id");
+ channelIds = channels.map((channel) => channel.id);
+
+ await Promise.all(
+ CERTIFICATE_KEYS.map(async (key, index) => {
+ certificateIds[key] = await insertCertificate(key, index + 1);
+ })
+ );
+
+ const recent = new Date(now.getTime() - 60 * 60 * 1000);
+ const old = new Date(now.getTime() - 2 * DAY_MS);
+ const [first, second] = channelIds;
+
+ await insertDelivery(
+ certificateIds.bothChannels,
+ [
+ { channelId: first, status: AlertRunStatus.SUCCESS },
+ { channelId: second, status: AlertRunStatus.SUCCESS }
+ ],
+ recent
+ );
+ await insertDelivery(certificateIds.oneChannel, [{ channelId: first, status: AlertRunStatus.SUCCESS }], recent);
+ await insertDelivery(
+ certificateIds.beforeWindow,
+ [
+ { channelId: first, status: AlertRunStatus.SUCCESS },
+ { channelId: second, status: AlertRunStatus.SUCCESS }
+ ],
+ old
+ );
+ await insertDelivery(
+ certificateIds.oneFailed,
+ [
+ { channelId: first, status: AlertRunStatus.SUCCESS },
+ { channelId: second, status: AlertRunStatus.FAILED }
+ ],
+ recent
+ );
+ });
+
+ afterAll(async () => {
+ await testDb(TableName.Alert).where({ id: alertId }).del();
+ await testDb(TableName.AlertChannel).whereIn("id", channelIds).del();
+ await testDb(TableName.Certificate).whereIn("id", allCertificateIds()).del();
+ });
+
+ test("without an already-alerted filter every due certificate comes back", async () => {
+ expect(ownIds(await scan()).sort()).toEqual(allCertificateIds().sort());
+ });
+
+ test("a certificate is dropped only when every enabled channel delivered it inside the window", async () => {
+ const found = ownIds(await scan({ alertId, channelIds, since }));
+
+ expect(found).not.toContain(certificateIds.bothChannels);
+ expect(found.sort()).toEqual(
+ [
+ certificateIds.oneChannel,
+ certificateIds.beforeWindow,
+ certificateIds.oneFailed,
+ certificateIds.neverAlerted
+ ].sort()
+ );
+ });
+
+ test("a channel outside the enabled set does not count towards the exclusion", async () => {
+ const [first] = channelIds;
+ const found = ownIds(await scan({ alertId, channelIds: [first], since }));
+
+ expect(found).not.toContain(certificateIds.bothChannels);
+ expect(found).not.toContain(certificateIds.oneChannel);
+ expect(found).not.toContain(certificateIds.oneFailed);
+ expect(found).toContain(certificateIds.beforeWindow);
+ expect(found).toContain(certificateIds.neverAlerted);
+ });
+});
diff --git a/backend/src/db/migrations/20260928193642_allow-multiple-scope-wide-alerts.ts b/backend/src/db/migrations/20260928193642_allow-multiple-scope-wide-alerts.ts
new file mode 100644
index 0000000000..80ad5bf9d6
--- /dev/null
+++ b/backend/src/db/migrations/20260928193642_allow-multiple-scope-wide-alerts.ts
@@ -0,0 +1,73 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+const UNIQUE_INDEX = "alert_unique_scope_resource_event";
+const RESOURCE_BOUND_UNIQUE_INDEX = "alert_unique_scope_resource_event_bound";
+const ORG_ID_INDEX = "alerts_orgid_index";
+const MIGRATION_TIMEOUT = 60 * 60 * 1000;
+const MIGRATION_LOCK_TIMEOUT = 30 * 1000;
+
+const UNIQUE_COLUMNS = `("orgId", (COALESCE("projectId", '')), "resourceType", (COALESCE("resourceId", '')), "eventType")`;
+
+const withMigrationConnection = async (knex: Knex, run: (raw: (sql: string) => Knex.Raw) => Promise<void>) => {
+ const connection = await knex.client.acquireConnection();
+ const raw = (sql: string) => knex.raw(sql).connection(connection);
+
+ try {
+ const stmtResult = await raw("SHOW statement_timeout");
+ const originalStatementTimeout = stmtResult.rows[0].statement_timeout as string;
+ const lockResult = await raw("SHOW lock_timeout");
+ const originalLockTimeout = lockResult.rows[0].lock_timeout as string;
+
+ try {
+ await raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);
+ await raw(`SET lock_timeout = ${MIGRATION_LOCK_TIMEOUT}`);
+ await run(raw);
+ } finally {
+ await raw(`SET statement_timeout = '${originalStatementTimeout}'`);
+ await raw(`SET lock_timeout = '${originalLockTimeout}'`);
+ }
+ } finally {
+ await knex.client.releaseConnection(connection);
+ }
+};
+
+const createIndexConcurrently = async (raw: (sql: string) => Knex.Raw, name: string, definition: string) => {
+ const invalid = await raw(
+ `SELECT 1 FROM pg_class c JOIN pg_index i ON i.indexrelid = c.oid WHERE c.relname = '${name}' AND NOT i.indisvalid`
+ );
+ if (invalid.rows.length > 0) await raw(`DROP INDEX CONCURRENTLY IF EXISTS "${name}"`);
+ await raw(`CREATE ${definition}`);
+};
+
+export async function up(knex: Knex): Promise<void> {
+ await withMigrationConnection(knex, async (raw) => {
+ await createIndexConcurrently(
+ raw,
+ ORG_ID_INDEX,
+ `INDEX CONCURRENTLY IF NOT EXISTS "${ORG_ID_INDEX}" ON "${TableName.Alert}" ("orgId")`
+ );
+ await createIndexConcurrently(
+ raw,
+ RESOURCE_BOUND_UNIQUE_INDEX,
+ `UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "${RESOURCE_BOUND_UNIQUE_INDEX}" ON "${TableName.Alert}" ${UNIQUE_COLUMNS} WHERE "resourceId" IS NOT NULL`
+ );
+ await raw(`DROP INDEX CONCURRENTLY IF EXISTS "${UNIQUE_INDEX}"`);
+ });
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await withMigrationConnection(knex, async (raw) => {
+ await createIndexConcurrently(
+ raw,
+ UNIQUE_INDEX,
+ `UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "${UNIQUE_INDEX}" ON "${TableName.Alert}" ${UNIQUE_COLUMNS}`
+ );
+ await raw(`DROP INDEX CONCURRENTLY IF EXISTS "${RESOURCE_BOUND_UNIQUE_INDEX}"`);
+ await raw(`DROP INDEX CONCURRENTLY IF EXISTS "${ORG_ID_INDEX}"`);
+ });
+}
+
+const config = { transaction: false };
+export { config };
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 2ac81921ff..5c5ed98e85 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -962,7 +962,11 @@ export enum EventType {
CREATE_PKI_APPLICATION_ALERT = "create-pki-application-alert",
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"
+ 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"
}
// Maps each actor type to the JSONB key that holds the actor's primary ID in actorMetadata.
@@ -7931,6 +7935,43 @@ interface TestPkiApplicationAlertEvent {
};
}
+type TPkiCertificateAlertEventMetadata = {
+ alertId: string;
+ name: string;
+ eventType: string;
+ applications: { id: string; name: string | null }[];
+ profiles: { id: string; name: string | null }[];
+};
+
+interface CreatePkiCertificateAlertEvent {
+ type: EventType.CREATE_PKI_CERTIFICATE_ALERT;
+ metadata: TPkiCertificateAlertEventMetadata;
+}
+
+interface UpdatePkiCertificateAlertEvent {
+ type: EventType.UPDATE_PKI_CERTIFICATE_ALERT;
+ metadata: TPkiCertificateAlertEventMetadata;
+}
+
+interface DeletePkiCertificateAlertEvent {
+ type: EventType.DELETE_PKI_CERTIFICATE_ALERT;
+ metadata: TPkiCertificateAlertEventMetadata;
+}
+
+interface TestPkiCertificateAlertEvent {
+ type: EventType.TEST_PKI_CERTIFICATE_ALERT_CHANNEL;
+ metadata: {
+ alertId?: string;
+ alertName?: string | null;
+ channelId?: string;
+ channelName?: string | null;
+ channelType: string;
+ success: boolean;
+ deliveredTo?: number;
+ error?: string;
+ };
+}
+
export type Event =
| CreateAlertEvent
| UpdateAlertEvent
@@ -7940,6 +7981,10 @@ export type Event =
| UpdatePkiApplicationAlertEvent
| DeletePkiApplicationAlertEvent
| TestPkiApplicationAlertEvent
+ | CreatePkiCertificateAlertEvent
+ | UpdatePkiCertificateAlertEvent
+ | DeletePkiCertificateAlertEvent
+ | TestPkiCertificateAlertEvent
| CreateSubOrganizationEvent
| UpdateSubOrganizationEvent
| DeleteSubOrganizationEvent
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 0ae24e588d..3c849310c1 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2397,6 +2397,35 @@ 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."
+};
+
export const ALERTS = {
CREATE: {
projectId: "The ID of the project to create the alert in.",
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 919a560901..01edfaa49f 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1084,6 +1084,10 @@ export const registerRoutes = async (
const alertChannelMembershipDAL = alertChannelMembershipDALFactory(db);
const alertHistoryDAL = alertHistoryDALFactory(db);
const certManagerApplicationAlertDAL = certManagerApplicationAlertDALFactory(db);
+ const certManagerProjectResolver = certManagerProjectResolverFactory({
+ orgDAL,
+ projectDAL
+ });
const alertProviderRegistry = alertProviderRegistryFactory();
alertProviderRegistry.register(
identityCredentialAlertProviderFactory({
@@ -1095,7 +1099,8 @@ export const registerRoutes = async (
certManagerApplicationAlertProviderFactory({
certManagerApplicationAlertDAL,
permissionService,
- licenseService
+ licenseService,
+ certManagerProjectResolver
})
);
const alertRecipientResolver = alertRecipientResolverFactory({
@@ -1885,11 +1890,6 @@ export const registerRoutes = async (
approvalPolicyDAL
});
- const certManagerProjectResolver = certManagerProjectResolverFactory({
- orgDAL,
- projectDAL
- });
-
const agentVaultMemberDAL = agentVaultMemberDALFactory(db);
const agentVaultAccessBundleDAL = agentVaultAccessBundleDALFactory(db);
const agentVaultServiceDAL = agentVaultServiceDALFactory(db);
diff --git a/backend/src/server/routes/v1/alert-router.ts b/backend/src/server/routes/v1/alert-router.ts
index b71e006191..b20b9c4aa3 100644
--- a/backend/src/server/routes/v1/alert-router.ts
+++ b/backend/src/server/routes/v1/alert-router.ts
@@ -1,6 +1,7 @@
import { FastifyRequest } from "fastify";
import { z } from "zod";
+import { ALERTING } from "@app/lib/api-docs";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
@@ -50,6 +51,10 @@ const AlertResponseSchema = z.object({
orgId: z.string(),
projectId: z.string().nullable(),
resourceName: z.string().nullable().optional(),
+ filters: z
+ .record(z.array(z.object({ id: z.string(), name: z.string().nullable() })))
+ .optional()
+ .describe(ALERTING.filters),
channels: z.array(
z.object({
id: z.string().uuid(),
@@ -89,16 +94,17 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
config: { rateLimit: writeLimit },
schema: {
operationId: "createAlert",
+ description: ALERTING.ROUTES.create,
body: z.object({
- name: z.string().min(1).max(255),
- description: z.string().max(1000).optional(),
- resourceType: z.string().min(1),
- resourceId: z.string().nullable().optional(),
- eventType: z.string().min(1),
- condition: z.unknown().optional(),
- enabled: z.boolean().optional(),
- projectId: z.string().nullable().optional(),
- channels: z.array(CreateChannelInputSchema).min(1).max(MAX_CHANNELS_PER_ALERT)
+ 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().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)
}),
response: { 200: z.object({ alert: AlertResponseSchema }) }
},
@@ -130,12 +136,13 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
config: { rateLimit: writeLimit },
schema: {
operationId: "testAlertChannel",
+ description: ALERTING.ROUTES.testChannel,
body: z.object({
- resourceType: z.string().min(1),
- resourceId: z.string().nullable().optional(),
- projectId: z.string().nullable().optional(),
- alertId: z.string().uuid().optional(),
- channelId: z.string().uuid().optional(),
+ resourceType: z.string().min(1).describe(ALERTING.resourceType),
+ resourceId: z.string().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),
channelType: z.nativeEnum(AlertChannelType),
config: z.record(z.unknown()).default({}),
recipients: z.array(ChannelRecipientSchema).max(MAX_RECIPIENTS_PER_CHANNEL).optional()
@@ -190,14 +197,16 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
config: { rateLimit: readLimit },
schema: {
operationId: "listAlerts",
+ description: ALERTING.ROUTES.list,
querystring: z.object({
- resourceType: z.string().min(1),
- resourceId: z.string().optional(),
- projectId: z.string().optional(),
+ resourceType: z.string().min(1).describe(ALERTING.resourceType),
+ resourceId: z.string().optional().describe(ALERTING.listResourceId),
+ projectId: z.string().optional().describe(ALERTING.projectId),
enabled: z
.enum(["true", "false"])
.transform((value) => value === "true")
.optional()
+ .describe(ALERTING.enabled)
}),
response: { 200: z.object({ alerts: AlertResponseSchema.array() }) }
},
@@ -220,7 +229,8 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
config: { rateLimit: readLimit },
schema: {
operationId: "getAlertById",
- params: z.object({ alertId: z.string().uuid() }),
+ description: ALERTING.ROUTES.get,
+ params: z.object({ alertId: z.string().uuid().describe(ALERTING.alertId) }),
response: { 200: z.object({ alert: AlertResponseSchema }) }
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
@@ -242,13 +252,19 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
config: { rateLimit: writeLimit },
schema: {
operationId: "updateAlert",
- params: z.object({ alertId: z.string().uuid() }),
+ description: ALERTING.ROUTES.update,
+ params: z.object({ alertId: z.string().uuid().describe(ALERTING.alertId) }),
body: z.object({
- name: z.string().min(1).max(255).optional(),
- description: z.string().max(1000).nullable().optional(),
- condition: z.unknown().optional(),
- enabled: z.boolean().optional(),
- channels: z.array(UpdateChannelInputSchema).min(1).max(MAX_CHANNELS_PER_ALERT).optional()
+ 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),
+ channels: z
+ .array(UpdateChannelInputSchema)
+ .min(1)
+ .max(MAX_CHANNELS_PER_ALERT)
+ .optional()
+ .describe(ALERTING.channels)
}),
response: { 200: z.object({ alert: AlertResponseSchema }) }
},
@@ -281,7 +297,8 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
config: { rateLimit: writeLimit },
schema: {
operationId: "deleteAlert",
- params: z.object({ alertId: z.string().uuid() }),
+ description: ALERTING.ROUTES.delete,
+ params: z.object({ alertId: z.string().uuid().describe(ALERTING.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/server/routes/v1/pki-application-alert-router.ts b/backend/src/server/routes/v1/pki-application-alert-router.ts
index c7da6a5bc6..5fdbf7afca 100644
--- a/backend/src/server/routes/v1/pki-application-alert-router.ts
+++ b/backend/src/server/routes/v1/pki-application-alert-router.ts
@@ -12,7 +12,7 @@ import {
PkiAlertV2ResponseSchema,
UpdatePkiAlertV2Schema
} from "@app/services/pki-alert-v2/pki-alert-v2-types";
-import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+import { PkiAlertScope, PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { ApplicationIdParamsSchema } from "./pki-application-schemas";
@@ -114,6 +114,7 @@ export const registerPkiApplicationAlertRoutes = async (server: FastifyZodProvid
orgId: req.permission.orgId,
projectId: req.internalCertManagerProjectId,
applicationId: req.params.applicationId,
+ alertScope: PkiAlertScope.Application,
alertType: alert.eventType
}
});
@@ -175,7 +176,8 @@ export const registerPkiApplicationAlertRoutes = async (server: FastifyZodProvid
properties: {
orgId: req.permission.orgId,
projectId: req.internalCertManagerProjectId,
- applicationId: req.params.applicationId
+ applicationId: req.params.applicationId,
+ alertScope: PkiAlertScope.Application
}
});
@@ -231,7 +233,8 @@ export const registerPkiApplicationAlertRoutes = async (server: FastifyZodProvid
properties: {
orgId: req.permission.orgId,
projectId: req.internalCertManagerProjectId,
- applicationId: req.params.applicationId
+ applicationId: req.params.applicationId,
+ alertScope: PkiAlertScope.Application
}
});
diff --git a/backend/src/services/alert/alert-dal.test.ts b/backend/src/services/alert/alert-dal.test.ts
index 67f069bae7..39a72c878c 100644
--- a/backend/src/services/alert/alert-dal.test.ts
+++ b/backend/src/services/alert/alert-dal.test.ts
@@ -119,12 +119,28 @@ describe("alert dal", () => {
expect(calls.where).toContainEqual([`${TableName.Alert}.orgId`, "org-1"]);
expect(calls.where).toContainEqual([`${TableName.Alert}.resourceType`, "approval.workflow"]);
expect(calls.where).toContainEqual([`${TableName.Alert}.resourceId`, "policy-1"]);
+ expect(calls.orWhereNull).toContainEqual(`${TableName.Alert}.resourceId`);
expect(calls.where).toContainEqual([`${TableName.Alert}.eventType`, "approval.workflow.request_opened"]);
// Mirrors the cron's filter: an event must never trigger a scheduled alert.
expect(calls.where).toContainEqual([`${TableName.Alert}.triggerType`, "event"]);
expect(calls.where).toContainEqual([`${TableName.Alert}.enabled`, true]);
});
+ test("findEnabledForEvent matches only resource-less alerts for an event without a resource", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.findEnabledForEvent({
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceType: "cert-manager.application",
+ resourceId: null,
+ eventType: "cert-manager.application.certificate.issuance"
+ });
+
+ expect(calls.whereNull).toContainEqual(`${TableName.Alert}.resourceId`);
+ expect(calls.where).not.toContainEqual([`${TableName.Alert}.resourceId`, null]);
+ });
+
// An empty result is terminal for the event, so it can't come from a replica that hasn't seen the
// alert commit yet.
test("findEnabledForEvent reads the primary while the scheduled and list lookups keep the replica", async () => {
@@ -189,6 +205,6 @@ describe("alert dal", () => {
expect(calls.whereNull).not.toContainEqual(`${TableName.Alert}.projectId`);
expect(calls.where).not.toContainEqual(expect.arrayContaining([`${TableName.Alert}.projectId`]));
- expect(calls.orWhereNull).toHaveLength(0);
+ expect(calls.orWhereNull).not.toContainEqual(`${TableName.Alert}.projectId`);
});
});
diff --git a/backend/src/services/alert/alert-dal.ts b/backend/src/services/alert/alert-dal.ts
index a1fd27ffd9..8d0c8e06ca 100644
--- a/backend/src/services/alert/alert-dal.ts
+++ b/backend/src/services/alert/alert-dal.ts
@@ -49,7 +49,7 @@ export const alertDALFactory = (db: TDbClient) => {
orgId: string;
projectId?: string | null;
resourceType: string;
- resourceId: string;
+ resourceId?: string | null;
eventType: string;
},
tx?: Knex
@@ -59,7 +59,6 @@ export const alertDALFactory = (db: TDbClient) => {
.leftJoin(TableName.Project, `${TableName.Alert}.projectId`, `${TableName.Project}.id`)
.where(`${TableName.Alert}.orgId`, filter.orgId)
.where(`${TableName.Alert}.resourceType`, filter.resourceType)
- .where(`${TableName.Alert}.resourceId`, filter.resourceId)
.where(`${TableName.Alert}.eventType`, filter.eventType)
.where(`${TableName.Alert}.triggerType`, AlertTriggerType.Event)
.where(`${TableName.Alert}.enabled`, true)
@@ -78,6 +77,15 @@ export const alertDALFactory = (db: TDbClient) => {
.where(`${TableName.AlertChannel}.enabled`, true)
);
+ void query.where(
+ (builder) =>
+ void (filter.resourceId
+ ? builder
+ .where(`${TableName.Alert}.resourceId`, filter.resourceId)
+ .orWhereNull(`${TableName.Alert}.resourceId`)
+ : builder.whereNull(`${TableName.Alert}.resourceId`))
+ );
+
if (filter.projectId) {
void query.where(
(builder) =>
diff --git a/backend/src/services/alert/alert-engine.test.ts b/backend/src/services/alert/alert-engine.test.ts
index b3b51aeac1..3ee4b9d5fc 100644
--- a/backend/src/services/alert/alert-engine.test.ts
+++ b/backend/src/services/alert/alert-engine.test.ts
@@ -115,7 +115,7 @@ type TDelivery = { targetId: string; channelId: string; channelType: string; sta
const buildEngine = (opts: {
targets: TTarget[];
- channels: Array<{ id: string; channelType: string; encryptedConfig: Buffer; enabled: boolean }>;
+ channels: Array<{ id: string; channelType: string; encryptedConfig: Buffer; enabled: boolean; createdAt?: Date }>;
recentlyAlerted?: Array<{ channelId: string; targetId: string }>;
deliveredForEvent?: string[];
recipients?: Array<{ userId: string; email: string; firstName?: string | null }>;
@@ -152,9 +152,8 @@ const buildEngine = (opts: {
alertChannelDAL: {
findByAlertId: async (_alertId: string, filter?: { enabled?: boolean; readFromPrimary?: boolean }) => {
channelLookups.push(filter);
- return filter?.enabled === undefined
- ? opts.channels
- : opts.channels.filter((c) => c.enabled === filter.enabled);
+ const channels = opts.channels.map((c) => ({ createdAt: new Date(0), ...c }));
+ return filter?.enabled === undefined ? channels : channels.filter((c) => c.enabled === filter.enabled);
}
},
alertChannelRecipientDAL: {
@@ -532,10 +531,45 @@ describe("alert engine, event path", () => {
const EVENT = {
eventId: "7",
eventType: "test.resource.opened",
+ occurredAt: new Date(),
targetIds: ["t1"],
payload: { targetIds: ["t1"], note: "x" }
};
+ test("a retried event skips channels created after the event happened", async () => {
+ const { engine, sentMail } = buildEngine({
+ targets: [{ id: "t1" }],
+ channels: [
+ { id: "c-old", channelType: "email", encryptedConfig: encConfig({}), enabled: true },
+ {
+ id: "c-new",
+ channelType: "email",
+ encryptedConfig: encConfig({}),
+ enabled: true,
+ createdAt: new Date(Date.now() + 60_000)
+ }
+ ]
+ });
+
+ await engine.runAlertForEvent(eventAlert(), EVENT);
+ expect(sentMail).toHaveLength(1);
+
+ const late = buildEngine({
+ targets: [{ id: "t1" }],
+ channels: [
+ {
+ id: "c-new",
+ channelType: "email",
+ encryptedConfig: encConfig({}),
+ enabled: true,
+ createdAt: new Date(Date.now() + 60_000)
+ }
+ ]
+ });
+ expect(await late.engine.runAlertForEvent(eventAlert(), EVENT)).toBe(AlertDispatchOutcome.NoChannels);
+ expect(late.sentMail).toHaveLength(0);
+ });
+
test("delivers the targets the event named and files the run under the event id", async () => {
const { engine, sentMail, historyWrites, eventPayloads } = buildEngine({
targets: [{ id: "t1" }, { id: "t2" }],
diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.ts
index 4bbd418179..ecfd2312d8 100644
--- a/backend/src/services/alert/alert-engine.ts
+++ b/backend/src/services/alert/alert-engine.ts
@@ -301,7 +301,13 @@ export const alertEngineFactory = ({
const runAlertForEvent = async (
alert: TAlerts,
- input: { eventId: string; eventType: string; targetIds: string[]; payload: Record<string, unknown> }
+ input: {
+ eventId: string;
+ eventType: string;
+ occurredAt: Date;
+ targetIds: string[];
+ payload: Record<string, unknown>;
+ }
): Promise<AlertDispatchOutcome> => {
const provider = $getProvider(alert, "findEventTargets");
if (!provider?.findEventTargets) return AlertDispatchOutcome.NoProvider;
@@ -311,7 +317,9 @@ export const alertEngineFactory = ({
alertHistoryDAL.findDeliveredChannelIdsForEvent(alert.id, input.eventId)
]);
const skip = new Set(alreadyDelivered);
- const channels = enabledChannels.filter((channel) => !skip.has(channel.id));
+ const channels = enabledChannels.filter(
+ (channel) => !skip.has(channel.id) && new Date(channel.createdAt) <= new Date(input.occurredAt)
+ );
if (channels.length === 0) return AlertDispatchOutcome.NoChannels;
const resolved = await provider.findEventTargets({
diff --git a/backend/src/services/alert/alert-event-consumer.test.ts b/backend/src/services/alert/alert-event-consumer.test.ts
index 4f692dd012..9322a80b1f 100644
--- a/backend/src/services/alert/alert-event-consumer.test.ts
+++ b/backend/src/services/alert/alert-event-consumer.test.ts
@@ -98,6 +98,15 @@ describe("alert event consumer", () => {
expect(runs[0].payload).toEqual(makePayload());
});
+ test("accepts a scope-wide event that carries no resource", async () => {
+ const { consumer, runs } = buildConsumer();
+
+ const [result] = await consumer.handle([makeEvent({ payload: makePayload({ resourceId: null }) })]);
+
+ expect(result.status).toBe(EventResultStatus.Delivered);
+ expect(runs[0].targetIds).toEqual(["req-1"]);
+ });
+
// The outbox row id is stable across attempts, so it's the only key a retry can use to find what
// already went out.
test("hands the engine the event id so a retry can skip channels that already delivered", async () => {
diff --git a/backend/src/services/alert/alert-event-consumer.ts b/backend/src/services/alert/alert-event-consumer.ts
index e6f8564d54..0180f2f389 100644
--- a/backend/src/services/alert/alert-event-consumer.ts
+++ b/backend/src/services/alert/alert-event-consumer.ts
@@ -19,7 +19,7 @@ export const AlertEventPayloadSchema = z.object({
orgId: z.string().uuid(),
projectId: z.string().trim().min(1).max(255).nullish(),
resourceType: z.string().trim().min(1).max(255),
- resourceId: z.string().trim().min(1).max(255),
+ resourceId: z.string().trim().min(1).max(255).nullish(),
targetIds: z.array(z.string().trim().min(1).max(255)).min(1).max(MAX_TARGET_IDS_PER_EVENT)
});
@@ -86,10 +86,11 @@ export const alertEventConsumerFactory = ({
const errors: string[] = [];
for (const alert of alerts) {
- // eslint-disable-next-line no-await-in-loop -- at most a project- and an org-scoped alert
+ // eslint-disable-next-line no-await-in-loop -- bounds DB connection use; a retry skips channels already delivered for this event
const outcome = await alertEngine.runAlertForEvent(alert, {
eventId: id,
eventType: event.eventType,
+ occurredAt: event.occurredAt,
targetIds,
payload: (event.payload ?? {}) as Record<string, unknown>
});
@@ -113,7 +114,7 @@ export const alertEventConsumerFactory = ({
filter.orgId,
filter.projectId ?? null,
filter.resourceType,
- filter.resourceId,
+ filter.resourceId ?? null,
filter.eventType
]);
let lookup = alertsByFilter.get(key);
diff --git a/backend/src/services/alert/alert-provider-registry.ts b/backend/src/services/alert/alert-provider-registry.ts
index 69247c7359..68287e92d1 100644
--- a/backend/src/services/alert/alert-provider-registry.ts
+++ b/backend/src/services/alert/alert-provider-registry.ts
@@ -4,7 +4,7 @@ export const resolveAlertProjectId = async (
provider: IResourceAlertProvider,
{ orgId, projectId, resourceId }: { orgId: string; projectId?: string | null; resourceId?: string | null }
): Promise<string | null> => {
- if (projectId || !resourceId || !provider.resolveProjectId) return projectId ?? null;
+ if (projectId || !provider.resolveProjectId) return projectId ?? null;
return provider.resolveProjectId({ orgId, resourceId });
};
diff --git a/backend/src/services/alert/alert-service-types.ts b/backend/src/services/alert/alert-service-types.ts
index ece666da33..d768945ef2 100644
--- a/backend/src/services/alert/alert-service-types.ts
+++ b/backend/src/services/alert/alert-service-types.ts
@@ -2,7 +2,7 @@ import { TGenericPermission } from "@app/lib/types";
import { TAlertChannelEmbedded, TAlertChannelInput, TChannelRecipientInput } from "./alert-channel-service-types";
import { AlertChannelType } from "./alert-channel-types";
-import { AlertRunStatus } from "./alert-types";
+import { AlertRunStatus, TAlertFilters } from "./alert-types";
export type TCreateAlertDTO = TGenericPermission & {
name: string;
@@ -75,6 +75,7 @@ export type TAlertResponse = {
orgId: string;
projectId: string | null;
resourceName?: string | null;
+ filters?: TAlertFilters;
channels: TAlertChannelEmbedded[];
lastRun?: TAlertLastRun | null;
createdAt: Date;
diff --git a/backend/src/services/alert/alert-service.test.ts b/backend/src/services/alert/alert-service.test.ts
index 6d923e4c2c..034911fdf8 100644
--- a/backend/src/services/alert/alert-service.test.ts
+++ b/backend/src/services/alert/alert-service.test.ts
@@ -31,6 +31,7 @@ const buildService = (opts?: {
resourceScopeThrows?: boolean;
duplicateExists?: boolean;
resolvedProjectId?: string;
+ supportsScopeWideAlerts?: boolean;
atOrgScope?: boolean;
// Runs right after a find() has taken its snapshot, to stand in for a concurrent transaction
// committing between two statements of ours.
@@ -38,6 +39,12 @@ const buildService = (opts?: {
}) => {
const permissionCalls: TAlertPermissionInput[] = [];
const gatedChannelTypeCalls: string[][] = [];
+ const conditionScopeCalls: {
+ projectId?: string | null;
+ resourceId?: string | null;
+ condition: unknown;
+ previousCondition?: unknown;
+ }[] = [];
const recipientProjectIds: (string | null)[] = [];
const provider: IResourceAlertProvider = {
resourceType: RESOURCE_TYPE,
@@ -69,7 +76,11 @@ const buildService = (opts?: {
assertChannelTypesAllowed: async ({ channelTypes }) => {
gatedChannelTypeCalls.push(channelTypes);
},
- ...(opts?.resolvedProjectId ? { resolveProjectId: async () => opts.resolvedProjectId as string } : {})
+ ...(opts?.resolvedProjectId ? { resolveProjectId: async () => opts.resolvedProjectId as string } : {}),
+ supportsScopeWideAlerts: opts?.supportsScopeWideAlerts,
+ assertConditionInScope: async ({ projectId, resourceId, condition, previousCondition }) => {
+ conditionScopeCalls.push({ projectId, resourceId, condition, previousCondition });
+ }
};
const registry = alertProviderRegistryFactory();
registry.register(provider);
@@ -232,6 +243,7 @@ const buildService = (opts?: {
service,
permissionCalls,
gatedChannelTypeCalls,
+ conditionScopeCalls,
recipientProjectIds,
alerts,
memberships,
@@ -383,7 +395,28 @@ describe("alert service", () => {
test("rejects a resource-less (scope-wide) alert as unsupported", async () => {
const { service } = buildService();
- await expect(service.createAlert({ ...validCreate, resourceId: undefined })).rejects.toThrow(/not supported yet/);
+ await expect(service.createAlert({ ...validCreate, resourceId: undefined })).rejects.toThrow(
+ "must be bound to a specific resource"
+ );
+ });
+
+ test("creates a resource-less alert when the provider supports scope-wide alerts", async () => {
+ const { service } = buildService({ supportsScopeWideAlerts: true });
+ const alert = await service.createAlert({ ...validCreate, resourceId: undefined, projectId: "proj-x" });
+ expect(alert.resourceId).toBeNull();
+ expect(alert.projectId).toBe("proj-x");
+ });
+
+ test("checks the condition's scope on create, and on update with the stored condition", async () => {
+ const { service, conditionScopeCalls } = buildService();
+ await service.createAlert(validCreate);
+ await service.updateAlert({ alertId: "alert-1", condition: { alertBefore: "5d" }, ...actor });
+ await service.updateAlert({ alertId: "alert-1", name: "renamed", ...actor });
+
+ expect(conditionScopeCalls).toHaveLength(2);
+ expect(conditionScopeCalls[0]).toMatchObject({ condition: { alertBefore: "30d" } });
+ expect(conditionScopeCalls[1]).toMatchObject({ condition: { alertBefore: "5d" } });
+ expect(conditionScopeCalls[1].previousCondition).toBeDefined();
});
test("rejects a condition that fails the provider schema", async () => {
@@ -466,6 +499,15 @@ describe("alert service", () => {
expect(findFilters[0]).toMatchObject({ projectId: null });
});
+ test("listing without a resource returns only resource-less alerts when the provider supports them", async () => {
+ const { service, alerts } = buildService({ supportsScopeWideAlerts: true });
+ alerts.set("bound", { id: "bound", name: "bound", projectId: "proj-x", ...listBase, resourceId: "resource-1" });
+ alerts.set("scope-wide", { id: "scope-wide", name: "scope-wide", projectId: "proj-x", ...listBase });
+
+ const listed = await service.listAlerts({ resourceType: RESOURCE_TYPE, projectId: "proj-x", ...actor });
+ expect(listed.map((alert) => alert.id)).toEqual(["scope-wide"]);
+ });
+
test("create and list resolve the project from the resource when projectId is omitted", async () => {
const { service, permissionCalls, findFilters } = buildService({ resolvedProjectId: "proj-resolved" });
@@ -528,7 +570,7 @@ describe("alert service", () => {
expect(gatedChannelTypeCalls.at(-1)).toEqual([AlertChannelType.WEBHOOK]);
});
- test("update does not gate channels the alert already has", async () => {
+ test("update does not gate channels the alert already has, so a downgraded plan can still edit the alert", async () => {
const { service, gatedChannelTypeCalls } = buildService();
const created = await service.createAlert(validCreate);
@@ -545,6 +587,33 @@ describe("alert service", () => {
expect(gatedChannelTypeCalls.at(-1)).toEqual([]);
});
+ test("update gates a disabled channel being enabled again", async () => {
+ const { service, gatedChannelTypeCalls } = buildService();
+ const created = await service.createAlert(validCreate);
+ const email = created.channels.find((c) => c.channelType === AlertChannelType.EMAIL)!;
+ const webhook = created.channels.find((c) => c.channelType === AlertChannelType.WEBHOOK)!;
+
+ await service.updateAlert({
+ alertId: "alert-1",
+ channels: [
+ { id: email.id, name: email.name, channelType: AlertChannelType.EMAIL, enabled: false },
+ { id: webhook.id, name: webhook.name, channelType: AlertChannelType.WEBHOOK, enabled: false }
+ ],
+ ...actor
+ });
+ expect(gatedChannelTypeCalls.at(-1)).toEqual([]);
+
+ await service.updateAlert({
+ alertId: "alert-1",
+ channels: [
+ { id: email.id, name: email.name, channelType: AlertChannelType.EMAIL },
+ { id: webhook.id, name: webhook.name, channelType: AlertChannelType.WEBHOOK, enabled: true }
+ ],
+ ...actor
+ });
+ expect(gatedChannelTypeCalls.at(-1)).toEqual([AlertChannelType.WEBHOOK]);
+ });
+
test("update rejects a channel id that does not belong to the alert", async () => {
const { service } = buildService();
await service.createAlert(validCreate);
diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.ts
index 6de353ba23..4499912774 100644
--- a/backend/src/services/alert/alert-service.ts
+++ b/backend/src/services/alert/alert-service.ts
@@ -33,6 +33,7 @@ import {
IResourceAlertProvider,
TAlertAuditInput,
TAlertEventDefinition,
+ TAlertFilters,
TAlertRecipientScope,
toAlertActor
} from "./alert-types";
@@ -123,9 +124,9 @@ export const alertServiceFactory = ({
return event;
};
- const $validateCondition = (event: TAlertEventDefinition, condition: unknown) => {
+ const $parseCondition = (event: TAlertEventDefinition, condition: unknown): unknown => {
try {
- event.conditionSchema.parse(condition);
+ return event.conditionSchema.parse(condition);
} catch (err) {
const message = err instanceof z.ZodError ? err.issues.map((i) => i.message).join(", ") : "Invalid condition";
throw new BadRequestError({ message: `Invalid alert condition: ${message}` });
@@ -158,11 +159,23 @@ export const alertServiceFactory = ({
);
};
+ const $getFilters = async (
+ provider: IResourceAlertProvider,
+ scope: { orgId: string; projectId: string | null },
+ alerts: Pick<TAlerts, "id" | "condition">[]
+ ): Promise<Map<string, TAlertFilters>> => {
+ if (!provider.getFilters || alerts.length === 0) return new Map();
+ return provider.getFilters({
+ ...scope,
+ alerts: alerts.map((alert) => ({ id: alert.id, condition: alert.condition }))
+ });
+ };
+
const $assembleResponse = (
provider: IResourceAlertProvider,
alert: TAlerts,
channels: TAlertChannelEmbedded[],
- extras: { resourceName: string | null; lastRun?: TAlertLastRun }
+ extras: { resourceName: string | null; lastRun?: TAlertLastRun; filters?: TAlertFilters }
): TAlertResponse => ({
id: alert.id,
name: alert.name,
@@ -176,6 +189,7 @@ export const alertServiceFactory = ({
orgId: alert.orgId,
projectId: alert.projectId ?? null,
...(provider.getResourceNames ? { resourceName: extras.resourceName } : {}),
+ ...(provider.getFilters ? { filters: extras.filters ?? {} } : {}),
channels,
...(provider.includeLastRun ? { lastRun: extras.lastRun ?? null } : {}),
createdAt: alert.createdAt,
@@ -183,14 +197,13 @@ export const alertServiceFactory = ({
});
const createAlert = async (dto: TCreateAlertDTO): Promise<TAlertResponse> => {
- if (!dto.resourceId) {
+ const provider = $getProvider(dto.resourceType);
+ if (!dto.resourceId && !provider.supportsScopeWideAlerts) {
throw new BadRequestError({
- message:
- "Alerts must be bound to a specific resource. Organization wide and project wide alerts are not supported yet."
+ message: `Alerts for resource type '${dto.resourceType}' must be bound to a specific resource. Pass resourceId.`
});
}
- const provider = $getProvider(dto.resourceType);
const projectId = await resolveAlertProjectId(provider, {
orgId: dto.actorOrgId,
projectId: dto.projectId,
@@ -198,7 +211,7 @@ export const alertServiceFactory = ({
});
const event = $getEvent(provider, dto.eventType);
- $validateCondition(event, dto.condition);
+ const condition = $parseCondition(event, dto.condition);
await $assertAlertPermission(
provider,
@@ -213,19 +226,19 @@ export const alertServiceFactory = ({
resourceId: dto.resourceId
});
- const duplicate = await alertDAL.findScopedDuplicate({
- orgId: dto.actorOrgId,
- projectId,
- resourceType: dto.resourceType,
- resourceId: dto.resourceId,
- eventType: dto.eventType
- });
- if (duplicate) {
- throw new BadRequestError({
- message: dto.resourceId
- ? "An alert for this resource and event already exists"
- : "An alert for this event already exists in this scope"
+ await provider.assertConditionInScope?.({ projectId, resourceId: dto.resourceId, condition });
+
+ if (dto.resourceId) {
+ const duplicate = await alertDAL.findScopedDuplicate({
+ orgId: dto.actorOrgId,
+ projectId,
+ resourceType: dto.resourceType,
+ resourceId: dto.resourceId,
+ eventType: dto.eventType
});
+ if (duplicate) {
+ throw new BadRequestError({ message: "An alert for this resource and event already exists" });
+ }
}
if (!dto.channels || dto.channels.length === 0) {
@@ -249,7 +262,7 @@ export const alertServiceFactory = ({
resourceId: dto.resourceId,
eventType: dto.eventType,
triggerType: event.triggerType,
- condition: dto.condition != null ? JSON.stringify(dto.condition) : null,
+ condition: condition != null ? JSON.stringify(condition) : null,
enabled: dto.enabled ?? true,
orgId: dto.actorOrgId,
projectId,
@@ -286,8 +299,10 @@ export const alertServiceFactory = ({
return { created: createdAlert, channels: details };
});
+ const filters = await $getFilters(provider, scope, [created]);
return $assembleResponse(provider, created, channels, {
- resourceName: await $getResourceName(provider, created)
+ resourceName: await $getResourceName(provider, created),
+ filters: filters.get(created.id)
});
};
@@ -307,9 +322,11 @@ export const alertServiceFactory = ({
const cipher = await getAlertChannelCipher(kmsService, { orgId: alert.orgId, projectId: alert.projectId });
const details = await alertChannelService.getDetailsForChannels(channels, cipher);
const lastRuns = await $getLastRuns(provider, [alert.id]);
+ const filters = await $getFilters(provider, { orgId: alert.orgId, projectId: alert.projectId ?? null }, [alert]);
return $assembleResponse(provider, alert, details, {
resourceName: await $getResourceName(provider, alert),
- lastRun: lastRuns.get(alert.id)
+ lastRun: lastRuns.get(alert.id),
+ filters: filters.get(alert.id)
});
};
@@ -330,7 +347,7 @@ export const alertServiceFactory = ({
const alerts = await alertDAL.findActiveByScope({
orgId: dto.actorOrgId,
resourceType: dto.resourceType,
- ...(dto.resourceId !== undefined ? { resourceId: dto.resourceId } : {}),
+ resourceId: dto.resourceId ?? (provider.supportsScopeWideAlerts ? null : undefined),
projectId,
...(dto.enabled !== undefined ? { enabled: dto.enabled } : {})
});
@@ -344,6 +361,7 @@ export const alertServiceFactory = ({
provider,
alerts.map((alert) => alert.id)
);
+ const filters = await $getFilters(provider, { orgId: dto.actorOrgId, projectId }, alerts);
const resourceNames = await $getResourceNames(
provider,
dto.actorOrgId,
@@ -367,7 +385,8 @@ export const alertServiceFactory = ({
.filter((detail): detail is TAlertChannelEmbedded => Boolean(detail)),
{
resourceName: (alert.resourceId && resourceNames.get(alert.resourceId)) || null,
- lastRun: lastRuns.get(alert.id)
+ lastRun: lastRuns.get(alert.id),
+ filters: filters.get(alert.id)
}
)
);
@@ -450,19 +469,35 @@ export const alertServiceFactory = ({
dto
);
- if (dto.condition !== undefined) $validateCondition($getEvent(provider, alert.eventType), dto.condition);
+ let condition: unknown;
+ if (dto.condition !== undefined) {
+ condition = $parseCondition($getEvent(provider, alert.eventType), dto.condition);
+ await provider.assertConditionInScope?.({
+ projectId: alert.projectId,
+ resourceId: alert.resourceId,
+ condition,
+ previousCondition: alert.condition
+ });
+ }
if (dto.channels !== undefined && dto.channels.length === 0) {
throw new BadRequestError({ message: "At least one channel is required" });
}
if (dto.channels && provider.assertChannelTypesAllowed) {
- const existingTypeById = new Map(
- (await alertChannelDAL.findByAlertId(alert.id)).map((channel) => [channel.id, channel.channelType])
+ const existingById = new Map(
+ (await alertChannelDAL.findByAlertId(alert.id)).map((channel) => [channel.id, channel])
);
await provider.assertChannelTypesAllowed({
orgId: alert.orgId,
channelTypes: dto.channels
- .filter((channel) => !channel.id || existingTypeById.get(channel.id) !== channel.channelType)
+ .filter((channel) => {
+ const existing = channel.id ? existingById.get(channel.id) : undefined;
+ return (
+ !existing ||
+ existing.channelType !== channel.channelType ||
+ (!existing.enabled && channel.enabled === true)
+ );
+ })
.map((channel) => channel.channelType)
});
}
@@ -474,9 +509,7 @@ export const alertServiceFactory = ({
const patch = {
...(dto.name !== undefined ? { name: dto.name } : {}),
...(dto.description !== undefined ? { description: dto.description } : {}),
- ...(dto.condition !== undefined
- ? { condition: dto.condition != null ? JSON.stringify(dto.condition) : null }
- : {}),
+ ...(dto.condition !== undefined ? { condition: condition != null ? JSON.stringify(condition) : null } : {}),
...(dto.enabled !== undefined ? { enabled: dto.enabled } : {})
};
@@ -492,9 +525,11 @@ export const alertServiceFactory = ({
});
const lastRuns = await $getLastRuns(provider, [alert.id]);
+ const filters = await $getFilters(provider, { orgId: alert.orgId, projectId: alert.projectId ?? null }, [updated]);
return $assembleResponse(provider, updated, channels, {
resourceName: await $getResourceName(provider, alert),
- lastRun: lastRuns.get(alert.id)
+ lastRun: lastRuns.get(alert.id),
+ filters: filters.get(updated.id)
});
};
@@ -521,6 +556,8 @@ export const alertServiceFactory = ({
resourceId: string | null;
resourceName: string | null;
eventType: string;
+ condition: unknown;
+ filters?: TAlertFilters;
orgId: string;
projectId: string | null;
}> => {
@@ -536,6 +573,7 @@ export const alertServiceFactory = ({
);
const resourceName = await $getResourceName(provider, alert);
+ const filters = await $getFilters(provider, { orgId: alert.orgId, projectId: alert.projectId ?? null }, [alert]);
await alertDAL.transaction((tx) => $deleteAlertsByFilter({ id: alert.id }, tx));
return {
@@ -545,6 +583,8 @@ export const alertServiceFactory = ({
resourceId: alert.resourceId ?? null,
resourceName,
eventType: alert.eventType,
+ condition: alert.condition ?? null,
+ ...(provider.getFilters ? { filters: filters.get(alert.id) ?? {} } : {}),
orgId: alert.orgId,
projectId: alert.projectId ?? null
};
diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.ts
index 7702a81ff3..13f659f804 100644
--- a/backend/src/services/alert/alert-types.ts
+++ b/backend/src/services/alert/alert-types.ts
@@ -97,6 +97,12 @@ export type TFindEventTargetsInput = {
payload: Record<string, unknown>;
};
+export type TAlreadyAlertedFilter = {
+ alertId: string;
+ channelIds: string[];
+ since: Date;
+};
+
export type TFindScheduledTargetsInput = {
orgId: string;
projectId?: string | null;
@@ -104,7 +110,7 @@ export type TFindScheduledTargetsInput = {
eventType: string;
condition: unknown;
asOf: Date;
- alreadyAlerted?: { alertId: string; channelIds: string[]; since: Date };
+ alreadyAlerted?: TAlreadyAlertedFilter;
};
// Lets a provider factory declare which discovery method it guarantees.
@@ -114,6 +120,10 @@ export type IScheduledAlertProvider<TTarget = unknown> = IResourceAlertProvider<
export type IEventAlertProvider<TTarget = unknown> = IResourceAlertProvider<TTarget> &
Required<Pick<IResourceAlertProvider<TTarget>, "findEventTargets">>;
+export type TAlertFilterValue = { id: string; name: string | null };
+
+export type TAlertFilters = Record<string, TAlertFilterValue[]>;
+
export enum AlertAuditAction {
Create = "create",
Update = "update",
@@ -124,6 +134,8 @@ export enum AlertAuditAction {
type TAlertAuditAlert = {
id: string;
name: string;
+ condition?: unknown;
+ filters?: TAlertFilters;
resourceType: string;
resourceId: string | null;
resourceName?: string | null;
@@ -207,6 +219,15 @@ export interface IResourceAlertProvider<TTarget = unknown> {
// existing permissions (e.g. PKI reuses the `pki-alerts` subject, project- or application-scoped).
assertPermission(input: TAlertPermissionInput): Promise<void>;
+ supportsScopeWideAlerts?: boolean;
+
+ assertConditionInScope?(input: {
+ projectId?: string | null;
+ resourceId?: string | null;
+ condition: unknown;
+ previousCondition?: unknown;
+ }): Promise<void>;
+
assertChannelTypesAllowed?(input: { orgId: string; channelTypes: string[] }): Promise<void>;
recipientPolicy?: TAlertRecipientPolicy;
@@ -219,7 +240,13 @@ export interface IResourceAlertProvider<TTarget = unknown> {
getResourceNames?(input: { orgId: string; resourceIds: string[] }): Promise<Map<string, string>>;
- resolveProjectId?(input: { orgId: string; resourceId: string }): Promise<string>;
+ getFilters?(input: {
+ orgId: string;
+ projectId: string | null;
+ alerts: { id: string; condition: unknown }[];
+ }): Promise<Map<string, TAlertFilters>>;
+
+ resolveProjectId?(input: { orgId: string; resourceId?: string | null }): Promise<string>;
getTelemetryEvent?(input: TAlertTelemetryInput): TAlertTelemetryEvent | undefined;
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 39dabd184b..9b47491ec4 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
@@ -26,7 +26,7 @@ const buildDAL = () => {
return { dal: certManagerApplicationAlertDALFactory(db), queries };
};
-describe("cert manager application alert DAL", () => {
+describe("cert manager certificate alert DAL", () => {
test("findExpiringCertificates only scans live certificates of the alert's application inside the window", async () => {
const { dal, queries } = buildDAL();
const asOf = new Date("2026-01-01T00:00:00Z");
@@ -104,4 +104,62 @@ describe("cert manager application alert DAL", () => {
expect(queries[0].sql).toContain('"projects"."orgId" = ?');
expect(queries[0].bindings).toEqual(expect.arrayContaining([APPLICATION_ID, "org-1"]));
});
+
+ test("a project-wide scan filters by the application and profile lists instead of pinning one application", async () => {
+ const { dal, queries } = buildDAL();
+
+ await dal.findExpiringCertificates({
+ projectId: PROJECT_ID,
+ applicationIds: ["app-1", "app-2"],
+ profileIds: ["prof-1"],
+ alertBeforeInterval: "30 days",
+ leadInterval: "1 day",
+ asOf: new Date("2026-01-01T00:00:00Z")
+ });
+
+ const [{ sql, bindings }] = queries;
+ expect(sql).toContain('"certificates"."projectId" = ?');
+ expect(sql).not.toContain('"certificates"."applicationId" = ?');
+ expect(sql).toContain('"certificates"."applicationId" in (?, ?)');
+ expect(sql).toContain('"certificates"."profileId" in (?)');
+ expect(bindings).toEqual(expect.arrayContaining(["app-1", "app-2", "prof-1"]));
+ });
+
+ test("findExpiringCertificates adds no exclusion when the alert has no enabled channels", async () => {
+ const { dal, queries } = buildDAL();
+
+ await dal.findExpiringCertificates({
+ projectId: PROJECT_ID,
+ applicationId: APPLICATION_ID,
+ alertBeforeInterval: "30 days",
+ leadInterval: "1 day",
+ asOf: new Date("2026-01-02T00:00:00Z"),
+ alreadyAlerted: { alertId: "alert-1", channelIds: [], since: new Date() }
+ });
+
+ expect(queries[0].sql).not.toContain("count(distinct");
+ });
+
+ test("findCertificatesByIds narrows a project-wide lookup by the profile list", async () => {
+ const { dal, queries } = buildDAL();
+
+ await dal.findCertificatesByIds({ projectId: PROJECT_ID, profileIds: ["prof-1"], certificateIds: ["cert-1"] });
+
+ expect(queries[0].sql).toContain('"certificates"."profileId" in (?)');
+ expect(queries[0].sql).toContain('"certificates"."id" in (?)');
+ });
+
+ test("application and profile id checks are scoped to the project", async () => {
+ const { dal, queries } = buildDAL();
+
+ await dal.findProjectApplicationIds(PROJECT_ID, ["app-1"]);
+ await dal.findProjectProfileIds(PROJECT_ID, ["prof-1"]);
+
+ expect(queries[0].sql).toContain('from "pki_applications" where "projectId" = ?');
+ expect(queries[1].sql).toContain('from "pki_certificate_profiles" where "projectId" = ?');
+ expect(queries.map((query) => query.bindings)).toEqual([
+ expect.arrayContaining([PROJECT_ID, "app-1"]),
+ expect.arrayContaining([PROJECT_ID, "prof-1"])
+ ]);
+ });
});
diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts b/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts
index 77610c66ef..79788b6d78 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
@@ -3,7 +3,7 @@ import { Knex } from "knex";
import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
-import { AlertRunStatus } from "@app/services/alert/alert-types";
+import { AlertRunStatus, TAlreadyAlertedFilter } from "@app/services/alert/alert-types";
import { CertStatus } from "@app/services/certificate/certificate-types";
export type TCertManagerApplicationAlertDALFactory = ReturnType<typeof certManagerApplicationAlertDALFactory>;
@@ -13,6 +13,7 @@ export type TApplicationAlertCertificate = {
serialNumber: string;
commonName: string;
altNames: string | null;
+ profileId: string | null;
profileName: string | null;
status: string;
notBefore: Date;
@@ -25,39 +26,56 @@ export type TApplicationAlertCertificate = {
type TCertificateScope = {
projectId: string;
- applicationId: string;
+ applicationId?: string | null;
+ applicationIds?: string[];
+ profileIds?: string[];
};
const MAX_EXPIRING_CERTIFICATES_PER_RUN = 1000;
+const applyCertificateScope = <TQuery extends Knex.QueryBuilder>(
+ query: TQuery,
+ { projectId, applicationId, applicationIds, profileIds }: TCertificateScope
+): TQuery => {
+ void query.where(`${TableName.Certificate}.projectId`, projectId);
+ if (applicationId) void query.where(`${TableName.Certificate}.applicationId`, applicationId);
+ if (applicationIds?.length) void query.whereIn(`${TableName.Certificate}.applicationId`, applicationIds);
+ if (profileIds?.length) void query.whereIn(`${TableName.Certificate}.profileId`, profileIds);
+ return query;
+};
+
export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {
- const $selectCertificates = (reader: Knex, { projectId, applicationId }: TCertificateScope) =>
- reader(TableName.Certificate)
- .leftJoin(`${TableName.PkiCertificateProfile} as profile`, `${TableName.Certificate}.profileId`, "profile.id")
- .leftJoin(TableName.PkiApplication, `${TableName.Certificate}.applicationId`, `${TableName.PkiApplication}.id`)
- .where(`${TableName.Certificate}.projectId`, projectId)
- .where(`${TableName.Certificate}.applicationId`, applicationId)
- .select(
- `${TableName.Certificate}.id`,
- `${TableName.Certificate}.serialNumber`,
- `${TableName.Certificate}.commonName`,
- `${TableName.Certificate}.altNames`,
- `${TableName.Certificate}.status`,
- `${TableName.Certificate}.notBefore`,
- `${TableName.Certificate}.notAfter`,
- `${TableName.Certificate}.revokedAt`,
- `${TableName.Certificate}.revocationReason`,
- `${TableName.Certificate}.applicationId`,
- "profile.slug as profileName",
- `${TableName.PkiApplication}.name as applicationName`
- );
+ const $selectCertificates = (reader: Knex, scope: TCertificateScope) => {
+ const query = applyCertificateScope(
+ reader(TableName.Certificate)
+ .leftJoin(`${TableName.PkiCertificateProfile} as profile`, `${TableName.Certificate}.profileId`, "profile.id")
+ .leftJoin(TableName.PkiApplication, `${TableName.Certificate}.applicationId`, `${TableName.PkiApplication}.id`),
+ scope
+ );
+
+ return query.select(
+ `${TableName.Certificate}.id`,
+ `${TableName.Certificate}.serialNumber`,
+ `${TableName.Certificate}.commonName`,
+ `${TableName.Certificate}.altNames`,
+ `${TableName.Certificate}.status`,
+ `${TableName.Certificate}.notBefore`,
+ `${TableName.Certificate}.notAfter`,
+ `${TableName.Certificate}.revokedAt`,
+ `${TableName.Certificate}.revocationReason`,
+ `${TableName.Certificate}.applicationId`,
+ `${TableName.Certificate}.profileId`,
+ "profile.slug as profileName",
+ `${TableName.PkiApplication}.name as applicationName`
+ );
+ };
const findExpiringCertificates = async (
scope: TCertificateScope & {
alertBeforeInterval: string;
leadInterval: string;
asOf: Date;
- alreadyAlerted?: { alertId: string; channelIds: string[]; since: Date };
+ alreadyAlerted?: TAlreadyAlertedFilter;
},
tx?: Knex
): Promise<TApplicationAlertCertificate[]> => {
@@ -156,10 +174,48 @@ export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {
}
};
+ const findProfileNamesByIds = async (projectId: string, profileIds: string[]) => {
+ if (profileIds.length === 0) return [];
+ try {
+ return (await db
+ .replicaNode()(TableName.PkiCertificateProfile)
+ .where({ projectId })
+ .whereIn("id", profileIds)
+ .select("id", "slug as name")) as { id: string; name: string }[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindProfileNamesByIds" });
+ }
+ };
+
+ const findProjectApplicationIds = async (projectId: string, applicationIds: string[], tx?: Knex) => {
+ try {
+ return (await (tx || db)(TableName.PkiApplication)
+ .where({ projectId })
+ .whereIn("id", applicationIds)
+ .pluck("id")) as string[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindProjectApplicationIds" });
+ }
+ };
+
+ const findProjectProfileIds = async (projectId: string, profileIds: string[], tx?: Knex) => {
+ try {
+ return (await (tx || db)(TableName.PkiCertificateProfile)
+ .where({ projectId })
+ .whereIn("id", profileIds)
+ .pluck("id")) as string[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindProjectProfileIds" });
+ }
+ };
+
return {
findExpiringCertificates,
findCertificatesByIds,
findApplicationById,
- findApplicationNamesByIds
+ findApplicationNamesByIds,
+ findProfileNamesByIds,
+ findProjectApplicationIds,
+ findProjectProfileIds
};
};
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 c0ace4082e..5ebbd9ac33 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
@@ -1,7 +1,7 @@
import { createMongoAbility } from "@casl/ability";
import { vi } from "vitest";
-import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+import { PkiAlertScope, PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { AlertChannelType } from "../alert-channel-types";
import { AlertAuditAction, AlertPermissionAction, AlertTelemetryAction, TAlertContext } from "../alert-types";
@@ -19,6 +19,9 @@ 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 APPLICATION_ID = "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90";
+const OTHER_APPLICATION_ID = "6c8e4a1f-9b2d-4f3c-8e7a-2b3c4d5e6f70";
+const PROFILE_ID = "7d9f5b2a-0c3e-4a4d-9f8b-3c4d5e6f7081";
const futureDate = (days: number) => new Date(Date.now() + days * 24 * 60 * 60 * 1000);
@@ -27,6 +30,7 @@ const sampleCertificate = (overrides: Partial<TApplicationAlertCertificate> = {}
serialNumber: "105d3b4c",
commonName: "api.example.com",
altNames: "api.example.com, www.api.example.com",
+ profileId: "profile-1",
profileName: "tls-server",
status: "active",
notBefore: new Date("2026-09-01T00:00:00.000Z"),
@@ -56,7 +60,8 @@ const buildProvider = (opts?: {
onFindExpiring?: (args: Record<string, unknown>) => void;
onFindByIds?: (args: Record<string, unknown>) => void;
onFindNames?: (ids: string[], orgId: string) => void;
- abilityRules?: { action: string; subject: string }[];
+ onFindApplicationIds?: (ids: string[]) => void;
+ abilityRules?: { action: string; subject: string; inverted?: boolean; conditions?: unknown }[];
pkiEnterpriseAlerting?: boolean;
}) => {
const application = opts?.application ?? {
@@ -69,7 +74,7 @@ const buildProvider = (opts?: {
findApplicationById: async (id: string) => (id === application.id ? application : undefined),
findApplicationNamesByIds: async (ids: string[], orgId: string) => {
opts?.onFindNames?.(ids, orgId);
- return ids.includes(application.id) && orgId === application.orgId
+ return ids.some((id) => id.toLowerCase() === application.id) && orgId === application.orgId
? [{ id: application.id, name: application.name }]
: [];
},
@@ -80,11 +85,20 @@ const buildProvider = (opts?: {
findCertificatesByIds: async (args: Record<string, unknown>) => {
opts?.onFindByIds?.(args);
return opts?.certificates ?? [];
- }
+ },
+ findProjectApplicationIds: async (_projectId: string, ids: string[]) => {
+ opts?.onFindApplicationIds?.(ids);
+ return ids.some((id) => id.toLowerCase() === application.id) ? [application.id] : [];
+ },
+ findProjectProfileIds: async (_projectId: string, ids: string[]) => ids.filter((id) => id === PROFILE_ID),
+ findProfileNamesByIds: async (_projectId: string, ids: string[]) =>
+ ids.filter((id) => id === PROFILE_ID).map((id) => ({ id, name: "tls-server" }))
};
- const ability = () => createMongoAbility(opts?.abilityRules ?? [{ action: "read", subject: "pki-alerts" }]);
+ const ability = () =>
+ createMongoAbility((opts?.abilityRules ?? [{ action: "read", subject: "pki-alerts" }]) as never);
const permissionService = {
- getResourcePermission: vi.fn(async () => ({ permission: ability() }))
+ getResourcePermission: vi.fn(async () => ({ permission: ability() })),
+ getProjectPermission: vi.fn(async () => ({ permission: ability() }))
};
const licenseService = {
getPlan: async () => ({ pkiEnterpriseAlerting: opts?.pkiEnterpriseAlerting ?? false })
@@ -92,7 +106,10 @@ const buildProvider = (opts?: {
const provider = certManagerApplicationAlertProviderFactory({
certManagerApplicationAlertDAL: dal,
permissionService,
- licenseService
+ licenseService,
+ certManagerProjectResolver: {
+ getActiveProjectId: async (orgId: string) => (orgId === "org-1" ? "proj-1" : null)
+ }
} as unknown as TCertManagerApplicationAlertProviderDep);
return { provider, permissionService };
};
@@ -114,18 +131,66 @@ describe("cert manager application alert provider", () => {
expect(schema.safeParse({ alertBefore: "30d", filters: [] }).success).toBe(false);
});
- test("issuance, renewal and revocation are event-triggered and take no condition", () => {
+ 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);
});
});
+ test("filters must be non-empty UUID lists and are stored as sent", () => {
+ const schema = expiryConditionSchema(buildProvider().provider);
+ expect(
+ schema.safeParse({ alertBefore: "30d", applicationIds: [APPLICATION_ID], profileIds: [PROFILE_ID] }).success
+ ).toBe(true);
+ expect(schema.safeParse({ alertBefore: "30d", applicationIds: ["not-a-uuid"] }).success).toBe(false);
+ expect(schema.safeParse({ alertBefore: "30d", applicationIds: [] }).success).toBe(false);
+ const upper = schema.safeParse({ alertBefore: "30d", applicationIds: [APPLICATION_ID.toUpperCase()] });
+ expect(upper.success && (upper.data as { applicationIds: string[] }).applicationIds).toEqual([
+ APPLICATION_ID.toUpperCase()
+ ]);
+ });
+
+ test("filters reject an ID listed twice, in any case, instead of storing the duplicate", () => {
+ const schema = expiryConditionSchema(buildProvider().provider);
+ const duplicated = schema.safeParse({
+ alertBefore: "30d",
+ applicationIds: [APPLICATION_ID, APPLICATION_ID.toUpperCase()]
+ });
+ expect(duplicated.success).toBe(false);
+ expect(duplicated.error?.issues[0].message).toBe(
+ `applicationIds lists the same ID more than once: '${APPLICATION_ID.toUpperCase()}'`
+ );
+ expect(schema.safeParse({ alertBefore: "30d", profileIds: [PROFILE_ID, PROFILE_ID] }).success).toBe(false);
+ });
+
+ test("filter IDs match case-insensitively when checked and named", async () => {
+ const { provider } = buildProvider();
+ await expect(
+ provider.assertConditionInScope?.({
+ projectId: "proj-1",
+ condition: { applicationIds: [APPLICATION_ID.toUpperCase()] }
+ })
+ ).resolves.toBeUndefined();
+ const names = await provider.getFilters?.({
+ orgId: "org-1",
+ projectId: "proj-1",
+ alerts: [{ id: "alert-1", condition: { applicationIds: [APPLICATION_ID.toUpperCase()] } }]
+ });
+ expect(names?.get("alert-1")).toEqual({
+ applications: [{ id: APPLICATION_ID.toUpperCase(), name: "payments-api" }],
+ profiles: []
+ });
+ });
+
test("findScheduledTargets converts alertBefore to days and scopes the scan to the alert's application", async () => {
let args: Record<string, unknown> | undefined;
const { provider } = buildProvider({
@@ -148,26 +213,45 @@ describe("cert manager application alert provider", () => {
});
});
- test("findScheduledTargets and findEventTargets return nothing for an alert with no application", async () => {
- const { provider } = buildProvider({ certificates: [sampleCertificate()] });
- await expect(
- provider.findScheduledTargets({
- orgId: "org-1",
- projectId: "proj-1",
- eventType: EXPIRY_EVENT,
- condition: { alertBefore: "30d" },
- asOf: new Date()
- })
- ).resolves.toEqual([]);
- await expect(
- provider.findEventTargets({
- orgId: "org-1",
- projectId: "proj-1",
- eventType: ISSUANCE_EVENT,
- condition: null,
- targetIds: ["cert-1"]
- } as never)
- ).resolves.toEqual([]);
+ test("findScheduledTargets and findEventTargets scan the whole project for an alert with no application", async () => {
+ let scheduledArgs: Record<string, unknown> | undefined;
+ let eventArgs: Record<string, unknown> | undefined;
+ const { provider } = buildProvider({
+ onFindExpiring: (value) => {
+ scheduledArgs = value;
+ },
+ onFindByIds: (value) => {
+ eventArgs = value;
+ }
+ });
+ await provider.findScheduledTargets({
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: null,
+ eventType: EXPIRY_EVENT,
+ condition: { alertBefore: "2w", profileIds: [PROFILE_ID] },
+ asOf: new Date()
+ });
+ await provider.findEventTargets({
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: null,
+ eventType: ISSUANCE_EVENT,
+ condition: { applicationIds: [APPLICATION_ID] },
+ targetIds: ["cert-1"]
+ } as never);
+
+ expect(scheduledArgs).toMatchObject({
+ projectId: "proj-1",
+ profileIds: [PROFILE_ID],
+ alertBeforeInterval: "14 days"
+ });
+ expect(scheduledArgs?.applicationId).toBeNull();
+ expect(eventArgs).toMatchObject({
+ projectId: "proj-1",
+ applicationIds: [APPLICATION_ID],
+ certificateIds: ["cert-1"]
+ });
});
test("dedup window tightens as the lead time shrinks and a daily reminder forces 24h", () => {
@@ -209,6 +293,7 @@ describe("cert manager application alert provider", () => {
notAfter: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/) as string,
revokedAt: null,
revocationReason: null,
+ profileId: "profile-1",
profileName: "tls-server",
applicationId: "app-1",
applicationName: "payments-api"
@@ -317,6 +402,134 @@ describe("cert manager application alert provider", () => {
await expect(provider.buildViewUrl(alertContext({ resourceId: "missing" }))).resolves.toBe(
"https://app.infisical.com/organizations/org-1/projects/cert-manager/proj-1/applications"
);
+ await expect(provider.buildViewUrl(alertContext({ resourceId: null }))).resolves.toBe(
+ "https://app.infisical.com/organizations/org-1/projects/cert-manager/proj-1/inventory"
+ );
+ });
+
+ test("buildPayload for an alert with no application names Certificate Manager and lists each application", () => {
+ const { provider } = buildProvider();
+ const payload = provider.buildPayload(
+ alertContext({ resourceId: null }),
+ [sampleCertificate({ notAfter: futureDate(20) })],
+ "https://app.infisical.com/view"
+ );
+
+ expect(payload.resourceOwnerKind).toBe("Certificate Manager");
+ expect(payload.webhookSource).toBe("/alerts/alert-1");
+ expect(payload.summary).toBe("1 certificate expiring within 30 days");
+ expect(payload.items[0].fields).toContainEqual({ label: "Application", value: "payments-api" });
+ });
+
+ test("assertConditionInScope rejects filters on an application alert and unknown IDs", async () => {
+ const { provider } = buildProvider();
+ await expect(
+ provider.assertConditionInScope?.({
+ projectId: "proj-1",
+ condition: { applicationIds: [APPLICATION_ID], profileIds: [PROFILE_ID] }
+ })
+ ).resolves.toBeUndefined();
+ await expect(
+ provider.assertConditionInScope?.({
+ projectId: "proj-1",
+ resourceId: APPLICATION_ID,
+ condition: { alertBefore: "30d", profileIds: [PROFILE_ID] }
+ })
+ ).rejects.toThrow("Application alerts already cover a single application");
+ await expect(
+ provider.assertConditionInScope?.({ projectId: "proj-1", condition: { applicationIds: [OTHER_APPLICATION_ID] } })
+ ).rejects.toThrow(`Application(s) not found in Certificate Manager: '${OTHER_APPLICATION_ID}'`);
+ });
+
+ test("assertConditionInScope only checks IDs the update adds, so a deleted one can stay", async () => {
+ const lookups: string[][] = [];
+ const { provider } = buildProvider({ onFindApplicationIds: (ids) => lookups.push(ids) });
+ await expect(
+ provider.assertConditionInScope?.({
+ projectId: "proj-1",
+ condition: { applicationIds: [OTHER_APPLICATION_ID, APPLICATION_ID] },
+ previousCondition: { applicationIds: [OTHER_APPLICATION_ID] }
+ })
+ ).resolves.toBeUndefined();
+ expect(lookups).toEqual([[APPLICATION_ID]]);
+ });
+
+ test("lists each alert's filter IDs with their names, with a null name for IDs that no longer exist", async () => {
+ const { provider } = buildProvider();
+ const names = await provider.getFilters?.({
+ orgId: "org-1",
+ projectId: "proj-1",
+ alerts: [
+ {
+ id: "alert-1",
+ condition: { applicationIds: [APPLICATION_ID, OTHER_APPLICATION_ID], profileIds: [PROFILE_ID] }
+ },
+ { id: "alert-2", condition: null }
+ ]
+ });
+
+ expect(names?.get("alert-1")).toEqual({
+ applications: [
+ { id: APPLICATION_ID, name: "payments-api" },
+ { id: OTHER_APPLICATION_ID, name: null }
+ ],
+ profiles: [{ id: PROFILE_ID, name: "tls-server" }]
+ });
+ expect(names?.get("alert-2")).toEqual({ applications: [], profiles: [] });
+ });
+
+ test("an alert with no application logs Certificate Manager audit events naming its filters", () => {
+ const { provider } = buildProvider();
+ const alert = {
+ id: "alert-1",
+ name: "prod-expiry",
+ resourceType: RESOURCE_TYPE,
+ resourceId: null,
+ eventType: EXPIRY_EVENT,
+ condition: {
+ alertBefore: "30d",
+ applicationIds: [APPLICATION_ID, OTHER_APPLICATION_ID],
+ profileIds: [PROFILE_ID]
+ },
+ filters: {
+ applications: [{ id: APPLICATION_ID, name: "payments-api" }],
+ profiles: [{ id: PROFILE_ID, name: "tls-server" }]
+ }
+ };
+ const metadata = {
+ alertId: "alert-1",
+ name: "prod-expiry",
+ eventType: EXPIRY_EVENT,
+ applications: [
+ { id: APPLICATION_ID, name: "payments-api" },
+ { id: OTHER_APPLICATION_ID, name: null }
+ ],
+ profiles: [{ id: PROFILE_ID, name: "tls-server" }]
+ };
+
+ expect(provider.getAuditEvent?.({ action: AlertAuditAction.Create, alert })).toEqual({
+ type: "create-pki-certificate-alert",
+ metadata
+ });
+ expect(provider.getAuditEvent?.({ action: AlertAuditAction.Delete, alert })).toEqual({
+ type: "delete-pki-certificate-alert",
+ metadata
+ });
+ expect(
+ provider.getAuditEvent?.({
+ action: AlertAuditAction.TestChannel,
+ test: {
+ resourceType: RESOURCE_TYPE,
+ alertId: "alert-1",
+ alertName: "prod-expiry",
+ channelType: "email",
+ success: true
+ }
+ })
+ ).toMatchObject({
+ type: "test-pki-certificate-alert-channel",
+ metadata: { alertId: "alert-1", alertName: "prod-expiry", channelType: "email", success: true }
+ });
});
test("assertPermission checks the application's resource permission when the alert is bound to one", async () => {
@@ -342,15 +555,57 @@ describe("cert manager application alert provider", () => {
expect(permissionService.getResourcePermission).toHaveBeenCalled();
});
- test("assertPermission requires a project and an application", async () => {
+ test("assertPermission requires a project", async () => {
+ const { provider } = buildProvider();
+ await expect(
+ provider.assertPermission({ action: AlertPermissionAction.Read, orgId: "org-1", actor })
+ ).rejects.toThrow("Certificate alerts must be created in Certificate Manager");
+ });
+
+ test("an alert with no application uses the project-level alerts permission", async () => {
const { provider, permissionService } = buildProvider();
await expect(
provider.assertPermission({ action: AlertPermissionAction.Read, orgId: "org-1", projectId: "proj-1", actor })
- ).rejects.toThrow("Application alerts require an application ID");
+ ).resolves.toBeUndefined();
+ await expect(
+ provider.assertPermission({ action: AlertPermissionAction.Create, orgId: "org-1", projectId: "proj-1", actor })
+ ).rejects.toThrow();
+ expect(permissionService.getProjectPermission).toHaveBeenCalled();
expect(permissionService.getResourcePermission).not.toHaveBeenCalled();
+ });
+
+ test("creating or editing an alert with no application requires reading every certificate", async () => {
+ const create = { action: AlertPermissionAction.Create, orgId: "org-1", projectId: "proj-1", actor };
+ const alertRules = [
+ { action: "create", subject: "pki-alerts" },
+ { action: "edit", subject: "pki-alerts" }
+ ];
+
await expect(
- provider.assertPermission({ action: AlertPermissionAction.Read, orgId: "org-1", actor })
- ).rejects.toThrow("Certificate alerts must be created in Certificate Manager");
+ buildProvider({
+ abilityRules: [...alertRules, { action: "read", subject: "certificates" }]
+ }).provider.assertPermission(create)
+ ).resolves.toBeUndefined();
+ await expect(buildProvider({ abilityRules: alertRules }).provider.assertPermission(create)).rejects.toThrow(
+ "require permission to read all certificates"
+ );
+ await expect(
+ buildProvider({
+ abilityRules: [
+ ...alertRules,
+ { action: "read", subject: "certificates", conditions: { commonName: { $glob: "*.internal" } } }
+ ]
+ }).provider.assertPermission({ ...create, action: AlertPermissionAction.Edit })
+ ).rejects.toThrow("require permission to read all certificates");
+ await expect(
+ buildProvider({
+ abilityRules: [
+ ...alertRules,
+ { action: "read", subject: "certificates" },
+ { action: "read", subject: "certificates", inverted: true, conditions: { commonName: { $glob: "*.prod" } } }
+ ]
+ }).provider.assertPermission(create)
+ ).rejects.toThrow("require permission to read all certificates");
});
test("assertResourceInScope rejects an application from another project or org", async () => {
@@ -389,6 +644,14 @@ describe("cert manager application alert provider", () => {
).rejects.toThrow("Application with ID '7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90' not found");
});
+ test("resolveProjectId falls back to the org's Certificate Manager project without an application", async () => {
+ const { provider } = buildProvider();
+ await expect(provider.resolveProjectId?.({ orgId: "org-1" })).resolves.toBe("proj-1");
+ await expect(provider.resolveProjectId?.({ orgId: "org-2" })).rejects.toThrow(
+ "Certificate Manager isn't set up for this organization"
+ );
+ });
+
test("rejects a malformed application ID with a bad request before any lookup", async () => {
const { provider, permissionService } = buildProvider();
const expected = "Invalid application ID 'not-a-uuid': must be a UUID";
@@ -462,6 +725,7 @@ describe("cert manager application alert provider", () => {
orgId: "org-1",
projectId: "proj-1",
applicationId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",
+ alertScope: PkiAlertScope.Application,
alertType: "expiration"
}
});
@@ -474,5 +738,22 @@ describe("cert manager application alert provider", () => {
eventType: ISSUANCE_EVENT
})?.event
).toBe(PostHogEventTypes.PkiAlertDeleted);
+ expect(
+ provider.getTelemetryEvent?.({
+ action: AlertTelemetryAction.Create,
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: null,
+ eventType: ISSUANCE_EVENT
+ })
+ ).toEqual({
+ event: PostHogEventTypes.PkiAlertCreated,
+ properties: {
+ orgId: "org-1",
+ projectId: "proj-1",
+ alertScope: PkiAlertScope.CertificateManager,
+ alertType: "issuance"
+ }
+ });
});
});
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 bf5241425d..d446549239 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,20 +1,26 @@
-import { ForbiddenError } from "@casl/ability";
+import { ForbiddenError, MongoAbility } from "@casl/ability";
import { z } from "zod";
-import { ResourceType } from "@app/db/schemas";
+import { ActionProjectType, ResourceType } from "@app/db/schemas";
import { Event as TAuditEvent, EventType } from "@app/ee/services/audit-log/audit-log-types";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { ProjectPermissionActions } from "@app/ee/services/permission/project-permission";
+import {
+ ProjectPermissionActions,
+ ProjectPermissionCertificateActions,
+ ProjectPermissionSet,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
import { ResourcePermissionSub } from "@app/ee/services/permission/resource-permission";
import { getConfig } from "@app/lib/config/env";
-import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { TCertManagerProjectResolverFactory } from "@app/services/cert-manager-instance/cert-manager-project-resolver";
import {
CERT_MANAGER_APPLICATION_RESOURCE_TYPE,
CertificateAlertEvent
} from "@app/services/certificate/certificate-alert-events";
import { getRevocationReasonLabel } from "@app/services/pki-alert-v2/pki-alert-v2-types";
-import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+import { PkiAlertScope, PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { AlertChannelType, TAlertPayload, TAlertSeverity } from "../alert-channel-types";
import { durationToDays, expirySeverity, formatUtcDate, humanizeDays } from "../alert-format-fns";
@@ -29,6 +35,7 @@ import {
IScheduledAlertProvider,
TAlertAuditInput,
TAlertContext,
+ TAlertFilters,
TAlertPermissionInput,
TAlertTelemetryEvent,
TAlertTelemetryInput,
@@ -40,6 +47,8 @@ import {
TCertManagerApplicationAlertDALFactory
} from "./cert-manager-application-alert-dal";
+const MAX_CERTIFICATE_ALERT_FILTER_IDS = 100;
+
const TELEMETRY_ALERT_TYPE_BY_EVENT: Record<CertificateAlertEvent, string> = {
[CertificateAlertEvent.Expiry]: "expiration",
[CertificateAlertEvent.Issuance]: "issuance",
@@ -55,6 +64,33 @@ const isValidAlertBefore = (alertBefore: string): boolean => {
return days >= MIN_CERTIFICATE_ALERT_BEFORE_DAYS && days <= MAX_CERTIFICATE_ALERT_BEFORE_DAYS;
};
+const filterIdsSchema = (field: string, noun: string) =>
+ z
+ .array(z.string().uuid())
+ .min(1, `${field} must list at least one ${noun}. Omit it to cover every ${noun}.`)
+ .max(MAX_CERTIFICATE_ALERT_FILTER_IDS)
+ .superRefine((ids, ctx) => {
+ const seen = new Set<string>();
+ const duplicates = new Set<string>();
+ ids.forEach((id) => {
+ const key = id.toLowerCase();
+ if (seen.has(key)) duplicates.add(id);
+ seen.add(key);
+ });
+ if (duplicates.size) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `${field} lists the same ID more than once: ${[...duplicates].map((id) => `'${id}'`).join(", ")}`
+ });
+ }
+ })
+ .optional();
+
+const CertificateFilterSchema = z.object({
+ applicationIds: filterIdsSchema("applicationIds", "application"),
+ profileIds: filterIdsSchema("profileIds", "profile")
+});
+
const ExpirationConditionSchema = z
.object({
alertBefore: z
@@ -65,9 +101,10 @@ const ExpirationConditionSchema = z
),
dailyReminder: z.boolean().optional()
})
+ .merge(CertificateFilterSchema)
.strict();
-const EventConditionSchema = z.object({}).strict().nullish();
+const EventConditionSchema = CertificateFilterSchema.strict().nullish();
const assertValidApplicationId = (applicationId: string) => {
if (!z.string().uuid().safeParse(applicationId).success) {
@@ -111,29 +148,30 @@ const splitAltNames = (altNames: string | null): string[] =>
const certificateDisplayName = (certificate: TApplicationAlertCertificate): string =>
certificate.commonName || splitAltNames(certificate.altNames)[0] || certificate.serialNumber;
+const inApplication = (applicationName?: string | null) =>
+ applicationName ? ` in application '${applicationName}'` : "";
+
const buildSummary = (
eventType: CertificateAlertEvent,
targets: TApplicationAlertCertificate[],
+ applicationName: string | null,
alertBefore?: string
): string => {
- const applicationName = targets[0]?.applicationName;
- const inApplication = applicationName ? ` in application '${applicationName}'` : "";
if (alertBefore) {
const certificates = `${targets.length} certificate${targets.length === 1 ? "" : "s"}`;
- return `${certificates}${inApplication} expiring within ${humanizeDays(durationToDays(alertBefore))}`;
+ return `${certificates}${inApplication(applicationName)} expiring within ${humanizeDays(durationToDays(alertBefore))}`;
}
if (targets.length === 1) {
- return `Certificate '${certificateDisplayName(targets[0])}' ${EVENT_VERBS[eventType]}${inApplication}`;
+ return `Certificate '${certificateDisplayName(targets[0])}' ${EVENT_VERBS[eventType]}${inApplication(targets[0].applicationName)}`;
}
- return `${targets.length} certificates ${EVENT_VERBS[eventType]}${inApplication}`;
+ return `${targets.length} certificates ${EVENT_VERBS[eventType]}${inApplication(applicationName)}`;
};
const buildItemSummary = (eventType: CertificateAlertEvent, certificate: TApplicationAlertCertificate): string => {
- const inApplication = certificate.applicationName ? ` in application '${certificate.applicationName}'` : "";
if (eventType === CertificateAlertEvent.Expiry) {
- return `Certificate '${certificateDisplayName(certificate)}'${inApplication} expires on ${formatUtcDate(certificate.notAfter)}`;
+ return `Certificate '${certificateDisplayName(certificate)}'${inApplication(certificate.applicationName)} expires on ${formatUtcDate(certificate.notAfter)}`;
}
- return `Certificate '${certificateDisplayName(certificate)}' ${EVENT_VERBS[eventType]}${inApplication}`;
+ return `Certificate '${certificateDisplayName(certificate)}' ${EVENT_VERBS[eventType]}${inApplication(certificate.applicationName)}`;
};
const DAILY_SCAN_DEDUP_MARGIN_HOURS = 4;
@@ -147,33 +185,50 @@ const expirationDedupWindowHours = (days: number, dailyReminder?: boolean): numb
return dayMultipleDedupWindowHours(30);
};
+const formatIds = (ids: string[]) => ids.map((id) => `'${id}'`).join(", ");
+
+const toIdSet = (ids: string[] = []) => new Set(ids.map((id) => id.toLowerCase()));
+
+const parseFilters = (condition: unknown) => {
+ const filters = CertificateFilterSchema.safeParse(condition ?? {});
+ return filters.success ? filters.data : {};
+};
+
+const 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);
+};
+
export type TCertManagerApplicationAlertProviderDep = {
certManagerApplicationAlertDAL: TCertManagerApplicationAlertDALFactory;
- permissionService: Pick<TPermissionServiceFactory, "getResourcePermission">;
+ permissionService: Pick<TPermissionServiceFactory, "getResourcePermission" | "getProjectPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+ certManagerProjectResolver: Pick<TCertManagerProjectResolverFactory, "getActiveProjectId">;
};
export const certManagerApplicationAlertProviderFactory = ({
certManagerApplicationAlertDAL,
permissionService,
- licenseService
+ licenseService,
+ certManagerProjectResolver
}: TCertManagerApplicationAlertProviderDep): IScheduledAlertProvider<TApplicationAlertCertificate> &
IEventAlertProvider<TApplicationAlertCertificate> => {
const buildViewUrl = async (alert: TAlertContext): Promise<string> => {
const base = `${getConfig().SITE_URL}/organizations/${alert.orgId}/projects/cert-manager/${alert.projectId}`;
- const application = alert.resourceId
- ? await certManagerApplicationAlertDAL.findApplicationById(alert.resourceId)
- : undefined;
+ if (!alert.resourceId) return `${base}/inventory`;
+ const application = await certManagerApplicationAlertDAL.findApplicationById(alert.resourceId);
return application ? `${base}/applications/${encodeURIComponent(application.name)}` : `${base}/applications`;
};
const findScheduledTargets = async (input: TFindScheduledTargetsInput): Promise<TApplicationAlertCertificate[]> => {
- if (!input.projectId || !input.resourceId) return [];
- const { alertBefore } = ExpirationConditionSchema.parse(input.condition);
+ if (!input.projectId) return [];
+ const { alertBefore, applicationIds, profileIds } = ExpirationConditionSchema.parse(input.condition);
return certManagerApplicationAlertDAL.findExpiringCertificates({
projectId: input.projectId,
applicationId: input.resourceId,
+ applicationIds,
+ profileIds,
alertBeforeInterval: `${durationToDays(alertBefore)} days`,
leadInterval: ALERT_SCAN_LEAD_INTERVAL,
asOf: input.asOf,
@@ -182,75 +237,20 @@ export const certManagerApplicationAlertProviderFactory = ({
};
const findEventTargets = async (input: TFindEventTargetsInput): Promise<TApplicationAlertCertificate[]> => {
- if (!input.projectId || !input.resourceId) return [];
- EventConditionSchema.parse(input.condition);
+ if (!input.projectId) return [];
+ const condition = EventConditionSchema.parse(input.condition);
return certManagerApplicationAlertDAL.findCertificatesByIds({
projectId: input.projectId,
applicationId: input.resourceId,
+ applicationIds: condition?.applicationIds,
+ profileIds: condition?.profileIds,
certificateIds: input.targetIds
});
};
const getWebhookSource = ({ alertId, resourceId }: { alertId: string; resourceId?: string | null }) =>
- resourceId ? `/applications/${resourceId}/alerts/${alertId}` : undefined;
-
- const getAuditEvent = (input: TAlertAuditInput): TAuditEvent => {
- if (input.action === AlertAuditAction.TestChannel) {
- const { test } = input;
- return {
- type: EventType.TEST_PKI_APPLICATION_ALERT_CHANNEL,
- metadata: {
- applicationId: test.resourceId ?? null,
- applicationName: test.resourceName ?? null,
- alertId: test.alertId,
- alertName: test.alertName ?? null,
- channelId: test.channelId,
- channelName: test.channelName ?? null,
- channelType: test.channelType,
- success: test.success,
- deliveredTo: test.deliveredTo,
- error: test.error
- }
- };
- }
-
- const metadata = {
- applicationId: input.alert.resourceId,
- applicationName: input.alert.resourceName ?? null,
- alertId: input.alert.id,
- name: input.alert.name,
- eventType: input.alert.eventType
- };
- if (input.action === AlertAuditAction.Create) return { type: EventType.CREATE_PKI_APPLICATION_ALERT, metadata };
- if (input.action === AlertAuditAction.Update) return { type: EventType.UPDATE_PKI_APPLICATION_ALERT, metadata };
- return { type: EventType.DELETE_PKI_APPLICATION_ALERT, metadata };
- };
-
- const getTelemetryEvent = ({
- action,
- orgId,
- projectId,
- resourceId,
- eventType
- }: TAlertTelemetryInput): TAlertTelemetryEvent | undefined => {
- if (!projectId || !resourceId) return undefined;
- const properties = { orgId, projectId, applicationId: resourceId };
- switch (action) {
- case AlertTelemetryAction.Create:
- return {
- event: PostHogEventTypes.PkiAlertCreated,
- properties: {
- ...properties,
- alertType: TELEMETRY_ALERT_TYPE_BY_EVENT[eventType as CertificateAlertEvent]
- }
- };
- case AlertTelemetryAction.Update:
- return { event: PostHogEventTypes.PkiAlertUpdated, properties };
- default:
- return { event: PostHogEventTypes.PkiAlertDeleted, properties };
- }
- };
+ resourceId ? `/applications/${resourceId}/alerts/${alertId}` : `/alerts/${alertId}`;
const buildPayload = (
alert: TAlertContext,
@@ -258,6 +258,7 @@ export const certManagerApplicationAlertProviderFactory = ({
viewUrl: string
): TAlertPayload => {
const eventType = alert.eventType as CertificateAlertEvent;
+ const isApplicationAlert = Boolean(alert.resourceId);
const isExpiration = eventType === CertificateAlertEvent.Expiry;
const alertBefore = isExpiration ? (alert.condition as { alertBefore?: string } | null)?.alertBefore : undefined;
@@ -277,9 +278,14 @@ export const certManagerApplicationAlertProviderFactory = ({
webhookType: `com.infisical.${eventType}`,
webhookSource: getWebhookSource({ alertId: alert.id, resourceId: alert.resourceId }),
resourceKind: "Certificate",
- resourceOwnerKind: "Application",
+ resourceOwnerKind: isApplicationAlert ? "Application" : "Certificate Manager",
severity: eventSeverity(eventType, targets),
- summary: buildSummary(eventType, targets, alertBefore),
+ summary: buildSummary(
+ eventType,
+ targets,
+ isApplicationAlert ? (targets[0]?.applicationName ?? null) : null,
+ alertBefore
+ ),
items: targets.map((certificate) => {
const revocationReason =
eventType === CertificateAlertEvent.Revocation
@@ -295,6 +301,9 @@ export const certManagerApplicationAlertProviderFactory = ({
{ label: "Serial Number", value: certificate.serialNumber },
...(altNames.length ? [{ label: "SANs", value: altNames.join(", ") }] : []),
...(certificate.profileName ? [{ label: "Profile", value: certificate.profileName }] : []),
+ ...(!isApplicationAlert && certificate.applicationName
+ ? [{ label: "Application", value: certificate.applicationName }]
+ : []),
{ label: "Expires", value: formatUtcDate(certificate.notAfter) },
...(revocationReason ? [{ label: "Revocation Reason", value: revocationReason }] : [])
],
@@ -308,6 +317,7 @@ export const certManagerApplicationAlertProviderFactory = ({
notAfter: certificate.notAfter.toISOString(),
revokedAt: certificate.revokedAt?.toISOString() ?? null,
revocationReason: certificate.revocationReason,
+ profileId: certificate.profileId,
profileName: certificate.profileName,
applicationId: certificate.applicationId,
applicationName: certificate.applicationName
@@ -317,13 +327,143 @@ export const certManagerApplicationAlertProviderFactory = ({
};
};
- const assertPermission = async ({ action, projectId, resourceId, actor }: TAlertPermissionInput): Promise<void> => {
+ const getCertificateManagerAuditEvent = (input: TAlertAuditInput): TAuditEvent => {
+ if (input.action === AlertAuditAction.TestChannel) {
+ const { test } = input;
+ return {
+ type: EventType.TEST_PKI_CERTIFICATE_ALERT_CHANNEL,
+ metadata: {
+ alertId: test.alertId,
+ alertName: test.alertName ?? null,
+ channelId: test.channelId,
+ channelName: test.channelName ?? null,
+ channelType: test.channelType,
+ success: test.success,
+ deliveredTo: test.deliveredTo,
+ error: test.error
+ }
+ };
+ }
+
+ const { alert } = input;
+ const { applicationIds = [], profileIds = [] } = parseFilters(alert.condition);
+ const nameById = new Map(
+ Object.values(alert.filters ?? {})
+ .flat()
+ .map((resource) => [resource.id, resource.name])
+ );
+ const withNames = (ids: string[]) => ids.map((id) => ({ id, name: nameById.get(id) ?? null }));
+ const metadata = {
+ alertId: alert.id,
+ name: alert.name,
+ eventType: alert.eventType,
+ 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 };
+ };
+
+ const getAuditEvent = (input: TAlertAuditInput): TAuditEvent => {
+ const resourceId = input.action === AlertAuditAction.TestChannel ? input.test.resourceId : input.alert.resourceId;
+ if (!resourceId) return getCertificateManagerAuditEvent(input);
+
+ if (input.action === AlertAuditAction.TestChannel) {
+ const { test } = input;
+ return {
+ type: EventType.TEST_PKI_APPLICATION_ALERT_CHANNEL,
+ metadata: {
+ applicationId: resourceId,
+ applicationName: test.resourceName ?? null,
+ alertId: test.alertId,
+ alertName: test.alertName ?? null,
+ channelId: test.channelId,
+ channelName: test.channelName ?? null,
+ channelType: test.channelType,
+ success: test.success,
+ deliveredTo: test.deliveredTo,
+ error: test.error
+ }
+ };
+ }
+
+ const metadata = {
+ applicationId: resourceId,
+ applicationName: input.alert.resourceName ?? null,
+ alertId: input.alert.id,
+ name: input.alert.name,
+ eventType: input.alert.eventType
+ };
+ if (input.action === AlertAuditAction.Create) return { type: EventType.CREATE_PKI_APPLICATION_ALERT, metadata };
+ if (input.action === AlertAuditAction.Update) return { type: EventType.UPDATE_PKI_APPLICATION_ALERT, metadata };
+ return { type: EventType.DELETE_PKI_APPLICATION_ALERT, metadata };
+ };
+
+ const getTelemetryEvent = ({
+ action,
+ orgId,
+ projectId,
+ resourceId,
+ eventType
+ }: TAlertTelemetryInput): TAlertTelemetryEvent | undefined => {
+ if (!projectId) return undefined;
+ const properties = {
+ orgId,
+ projectId,
+ ...(resourceId
+ ? { applicationId: resourceId, alertScope: PkiAlertScope.Application }
+ : { alertScope: PkiAlertScope.CertificateManager })
+ };
+ switch (action) {
+ case AlertTelemetryAction.Create:
+ return {
+ event: PostHogEventTypes.PkiAlertCreated,
+ properties: {
+ ...properties,
+ alertType: TELEMETRY_ALERT_TYPE_BY_EVENT[eventType as CertificateAlertEvent]
+ }
+ };
+ case AlertTelemetryAction.Update:
+ return { event: PostHogEventTypes.PkiAlertUpdated, properties };
+ default:
+ return { event: PostHogEventTypes.PkiAlertDeleted, properties };
+ }
+ };
+
+ const $assertCertificateManagerPermission = async ({
+ action,
+ projectId,
+ actor
+ }: TAlertPermissionInput & { projectId: string }) => {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.actor,
+ actorId: actor.actorId,
+ projectId,
+ actorAuthMethod: actor.actorAuthMethod,
+ actorOrgId: actor.actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+ ForbiddenError.from(permission).throwUnlessCan(PERMISSION_ACTIONS[action], ProjectPermissionSub.PkiAlerts);
+
+ const definesDelivery = action === AlertPermissionAction.Create || action === AlertPermissionAction.Edit;
+ if (definesDelivery && !canReadAllCertificates(permission)) {
+ throw new ForbiddenRequestError({
+ message:
+ "Certificate Manager alerts send certificate details from every application, so they require permission to read all certificates. Create the alert on an application instead."
+ });
+ }
+ };
+
+ const assertPermission = async (input: TAlertPermissionInput): Promise<void> => {
+ const { action, projectId, resourceId, actor } = input;
if (!projectId) {
throw new BadRequestError({ message: "Certificate alerts must be created in Certificate Manager" });
}
if (!resourceId) {
- throw new BadRequestError({ message: "Application alerts require an application ID" });
+ await $assertCertificateManagerPermission({ ...input, projectId });
+ return;
}
assertValidApplicationId(resourceId);
@@ -355,7 +495,89 @@ export const certManagerApplicationAlertProviderFactory = ({
}
};
- const resolveProjectId = async ({ orgId, resourceId }: { orgId: string; resourceId: string }) => {
+ const assertConditionInScope = async (input: {
+ projectId?: string | null;
+ resourceId?: string | null;
+ condition: unknown;
+ previousCondition?: unknown;
+ }): Promise<void> => {
+ if (!input.projectId) return;
+ const { applicationIds = [], profileIds = [] } = CertificateFilterSchema.parse(input.condition ?? {});
+ if (input.resourceId && (applicationIds.length || profileIds.length)) {
+ throw new BadRequestError({
+ message:
+ "Application alerts already cover a single application. Remove applicationIds and profileIds, or create a Certificate Manager alert instead."
+ });
+ }
+
+ const previous = parseFilters(input.previousCondition);
+ const savedApplicationIds = toIdSet(previous.applicationIds);
+ const savedProfileIds = toIdSet(previous.profileIds);
+ const addedApplicationIds = applicationIds.filter((id) => !savedApplicationIds.has(id.toLowerCase()));
+ const addedProfileIds = profileIds.filter((id) => !savedProfileIds.has(id.toLowerCase()));
+
+ const [foundApplicationIds, foundProfileIds]: string[][] = await Promise.all([
+ addedApplicationIds.length
+ ? certManagerApplicationAlertDAL.findProjectApplicationIds(input.projectId, addedApplicationIds)
+ : [],
+ addedProfileIds.length
+ ? certManagerApplicationAlertDAL.findProjectProfileIds(input.projectId, addedProfileIds)
+ : []
+ ]);
+
+ const foundApplicationIdSet = toIdSet(foundApplicationIds);
+ const missingApplicationIds = addedApplicationIds.filter((id) => !foundApplicationIdSet.has(id.toLowerCase()));
+ if (missingApplicationIds.length) {
+ throw new NotFoundError({
+ message: `Application(s) 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)}`
+ });
+ }
+ };
+
+ const getFilters = async ({
+ orgId,
+ projectId,
+ alerts
+ }: {
+ orgId: string;
+ projectId: string | null;
+ alerts: { id: string; condition: unknown }[];
+ }): Promise<Map<string, TAlertFilters>> => {
+ const filtersByAlert = alerts.map((alert) => ({ id: alert.id, ...parseFilters(alert.condition) }));
+ const applicationIds = [...new Set(filtersByAlert.flatMap((filters) => filters.applicationIds ?? []))];
+ const profileIds = [...new Set(filtersByAlert.flatMap((filters) => filters.profileIds ?? []))];
+
+ const [applications, profiles] = await Promise.all([
+ certManagerApplicationAlertDAL.findApplicationNamesByIds(applicationIds, orgId),
+ projectId ? certManagerApplicationAlertDAL.findProfileNamesByIds(projectId, profileIds) : []
+ ]);
+ const nameById = new Map([...applications, ...profiles].map((entry) => [entry.id.toLowerCase(), entry.name]));
+
+ const withNames = (ids: string[] = []) => ids.map((id) => ({ id, name: nameById.get(id.toLowerCase()) ?? null }));
+
+ return new Map(
+ filtersByAlert.map((filters) => [
+ filters.id,
+ { applications: withNames(filters.applicationIds), profiles: withNames(filters.profileIds) }
+ ])
+ );
+ };
+
+ const resolveProjectId = async ({ orgId, resourceId }: { orgId: string; resourceId?: string | null }) => {
+ if (!resourceId) {
+ const projectId = await certManagerProjectResolver.getActiveProjectId(orgId);
+ if (!projectId) {
+ throw new NotFoundError({ message: "Certificate Manager isn't set up for this organization" });
+ }
+ return projectId;
+ }
assertValidApplicationId(resourceId);
const application = await certManagerApplicationAlertDAL.findApplicationById(resourceId);
if (!application || application.orgId !== orgId) {
@@ -371,13 +593,14 @@ export const certManagerApplicationAlertProviderFactory = ({
const plan = await licenseService.getPlan(orgId);
if (!plan.pkiEnterpriseAlerting) {
throw new BadRequestError({
- message: `Failed to add a ${gatedType} channel due to plan restriction. Upgrade plan to alert on channels other than email.`
+ message: `Failed to save a ${gatedType} channel due to plan restriction. Upgrade plan to alert on channels other than email, or disable or remove the ${gatedType} channel.`
});
}
};
return {
resourceType: CERT_MANAGER_APPLICATION_RESOURCE_TYPE,
+ supportsScopeWideAlerts: true,
events: [
{
key: CertificateAlertEvent.Expiry,
@@ -405,11 +628,13 @@ export const certManagerApplicationAlertProviderFactory = ({
},
assertPermission,
assertResourceInScope,
+ assertConditionInScope,
assertChannelTypesAllowed,
recipientPolicy: { atOrgScope: true, allowEmailAddresses: true },
includeLastRun: true,
getAuditEvent,
getWebhookSource,
+ getFilters,
resolveProjectId,
getResourceNames: async ({ orgId, resourceIds }) =>
new Map(
diff --git a/backend/src/services/certificate/certificate-alert-events.test.ts b/backend/src/services/certificate/certificate-alert-events.test.ts
new file mode 100644
index 0000000000..b2c98d8f97
--- /dev/null
+++ b/backend/src/services/certificate/certificate-alert-events.test.ts
@@ -0,0 +1,59 @@
+import {
+ CERT_MANAGER_APPLICATION_RESOURCE_TYPE,
+ CertificateAlertEvent,
+ certificateAlertEventEmitterFactory
+} from "./certificate-alert-events";
+
+const buildEmitter = () => {
+ const emitted: { eventType: string; payload: Record<string, unknown> }[] = [];
+ const emitter = certificateAlertEventEmitterFactory({
+ eventEmitter: {
+ emit: async (event: { eventType: string; payload: Record<string, unknown> }) => {
+ emitted.push(event);
+ }
+ } as never,
+ projectDAL: { findById: async () => ({ orgId: "org-1" }) } as never
+ });
+ return { emitter, emitted };
+};
+
+describe("certificate alert event emitter", () => {
+ test("emits one event without a resource for a certificate outside any application", async () => {
+ const { emitter, emitted } = buildEmitter();
+ await emitter.emit(
+ { certificateId: "cert-1", projectId: "proj-1", eventType: CertificateAlertEvent.Issuance },
+ {} as never
+ );
+
+ expect(emitted).toEqual([
+ {
+ eventType: CertificateAlertEvent.Issuance,
+ payload: {
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceType: CERT_MANAGER_APPLICATION_RESOURCE_TYPE,
+ resourceId: null,
+ targetIds: ["cert-1"]
+ }
+ }
+ ]);
+ });
+
+ test("emits one event bound to the application for an application certificate", async () => {
+ const { emitter, emitted } = buildEmitter();
+ await emitter.emit(
+ {
+ certificateId: "cert-1",
+ projectId: "proj-1",
+ orgId: "org-1",
+ applicationId: "app-1",
+ eventType: CertificateAlertEvent.Revocation
+ },
+ {} as never
+ );
+
+ expect(emitted.map((event) => [event.eventType, event.payload.resourceType, event.payload.resourceId])).toEqual([
+ [CertificateAlertEvent.Revocation, CERT_MANAGER_APPLICATION_RESOURCE_TYPE, "app-1"]
+ ]);
+ });
+});
diff --git a/backend/src/services/certificate/certificate-alert-events.ts b/backend/src/services/certificate/certificate-alert-events.ts
index 30bd509837..9f5feea73e 100644
--- a/backend/src/services/certificate/certificate-alert-events.ts
+++ b/backend/src/services/certificate/certificate-alert-events.ts
@@ -36,8 +36,6 @@ export const certificateAlertEventEmitterFactory = ({ eventEmitter, projectDAL }
{ certificateId, projectId, orgId, applicationId, eventType }: TCertificateAlertEventInput,
tx?: Knex
) => {
- if (!applicationId) return;
-
const resolvedOrgId = orgId ?? (await projectDAL.findById(projectId, tx))?.orgId;
if (!resolvedOrgId) return;
@@ -47,7 +45,7 @@ export const certificateAlertEventEmitterFactory = ({ eventEmitter, projectDAL }
orgId: resolvedOrgId,
projectId,
resourceType: CERT_MANAGER_APPLICATION_RESOURCE_TYPE,
- resourceId: applicationId,
+ resourceId: applicationId ?? null,
targetIds: [certificateId]
}
};
diff --git a/backend/src/services/smtp/emails/AlertNotificationTemplate.tsx b/backend/src/services/smtp/emails/AlertNotificationTemplate.tsx
index fd4152b5a8..a79e854aa0 100644
--- a/backend/src/services/smtp/emails/AlertNotificationTemplate.tsx
+++ b/backend/src/services/smtp/emails/AlertNotificationTemplate.tsx
@@ -97,7 +97,7 @@ export const AlertNotificationTemplate = ({
<Text className="text-[11px] text-gray-400 text-center leading-[16px] mt-[16px] mb-[0px]">
You are receiving this because you are a recipient of this alert. Manage recipients and channels in the{" "}
- {resourceOwnerKind.toLowerCase()}&apos;s alert settings in Infisical.
+ {resourceOwnerKind} alert settings in Infisical.
</Text>
</BaseEmailWrapper>
);
diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.ts
index 50135f85b0..92db46cb28 100644
--- a/backend/src/services/telemetry/telemetry-types.ts
+++ b/backend/src/services/telemetry/telemetry-types.ts
@@ -1627,12 +1627,18 @@ export type TPkiSyncExecutedEvent = {
};
};
+export enum PkiAlertScope {
+ CertificateManager = "certificate-manager",
+ Application = "application"
+}
+
export type TPkiAlertCreatedEvent = {
event: PostHogEventTypes.PkiAlertCreated;
properties: {
orgId: string;
projectId: string;
- applicationId: string;
+ applicationId?: string;
+ alertScope: PkiAlertScope;
alertType?: string;
};
};
@@ -1642,7 +1648,8 @@ export type TPkiAlertUpdatedEvent = {
properties: {
orgId: string;
projectId: string;
- applicationId: string;
+ applicationId?: string;
+ alertScope: PkiAlertScope;
};
};
@@ -1651,7 +1658,8 @@ export type TPkiAlertDeletedEvent = {
properties: {
orgId: string;
projectId: string;
- applicationId: string;
+ applicationId?: string;
+ alertScope: PkiAlertScope;
};
};
diff --git a/docs/docs.json b/docs/docs.json
index 2c81725317..e330bc42f9 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -631,6 +631,7 @@
"documentation/platform/pki/settings/policies",
"documentation/platform/pki/settings/profiles",
"documentation/platform/pki/settings/certificate-cleanup",
+ "documentation/platform/pki/settings/alerts",
{
"group": "HSM",
"pages": [
diff --git a/docs/documentation/platform/pki/applications/alerting/overview.mdx b/docs/documentation/platform/pki/applications/alerting/overview.mdx
index 7b8ff04cee..2378f83b79 100644
--- a/docs/documentation/platform/pki/applications/alerting/overview.mdx
+++ b/docs/documentation/platform/pki/applications/alerting/overview.mdx
@@ -4,7 +4,7 @@ sidebarTitle: "Overview"
description: "Get notified when certificates in an application expire, are issued, renewed, or revoked."
---
-Certificate alerting tells your team about certificate lifecycle events in an [Application](/documentation/platform/pki/applications/overview). You create alerts in the application, and each alert watches every certificate in the application for one event.
+Certificate alerting tells your team about certificate lifecycle events in an [Application](/documentation/platform/pki/applications/overview). You create alerts in the application, and each alert covers every certificate in the application for one event. To alert on certificates across Certificate Manager, including ones outside an application, create an alert under [**Settings** > **Alerts**](/documentation/platform/pki/settings/alerts).
## Alert events
@@ -36,7 +36,7 @@ Expiration alerts are checked once a day. Issuance, renewal, and revocation aler
Go to **Certificate Manager** > **Applications** and select your application.
</Step>
<Step>
- Select the **Settings** tab, then select **Create Alert** in the **Alerting** section.
+ Select the **Settings** tab, then select **Create Alert** in the **Alerts** section.
</Step>
<Step>
Choose the **Alert Type**, then enter an **Alert Name** and an optional **Description**.
diff --git a/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx b/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx
index 8f6b4d1c6a..83694cd52d 100644
--- a/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx
+++ b/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx
@@ -86,6 +86,7 @@ Each request is a [CloudEvents](https://cloudevents.io/) JSON payload. The `type
"notAfter": "2026-10-04T23:59:00.000Z",
"revokedAt": null,
"revocationReason": null,
+ "profileId": "<profile-id>",
"profileName": "tls-server",
"applicationId": "<application-id>",
"applicationName": "payments-api"
@@ -141,6 +142,7 @@ Each request is a [CloudEvents](https://cloudevents.io/) JSON payload. The `type
"notAfter": "2026-10-04T23:59:00.000Z",
"revokedAt": "2026-09-24T14:21:58.000Z",
"revocationReason": 1,
+ "profileId": "<profile-id>",
"profileName": "tls-server",
"applicationId": "<application-id>",
"applicationName": "payments-api"
diff --git a/docs/documentation/platform/pki/settings/alerts.mdx b/docs/documentation/platform/pki/settings/alerts.mdx
new file mode 100644
index 0000000000..964c1a69ad
--- /dev/null
+++ b/docs/documentation/platform/pki/settings/alerts.mdx
@@ -0,0 +1,85 @@
+---
+title: "Alerts"
+sidebarTitle: "Alerts"
+description: "Get notified about certificate events anywhere in Certificate Manager, inside or outside an application."
+---
+
+An alert under **Settings** > **Alerts** covers certificates across Certificate Manager for one event, whether or not they belong to an [Application](/documentation/platform/pki/applications/overview). Without filters, it covers every certificate. Use a Certificate Manager alert when a team needs to hear about certificates across several applications. To alert on a single application, create an [application alert](/documentation/platform/pki/applications/alerting/overview) instead.
+
+Certificate Manager alerts use the same events and [notification channels](/documentation/platform/pki/applications/alerting/overview#notification-channels) as application alerts.
+
+## 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 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)
+
+## Create an alert
+
+<Steps>
+ <Step>
+ Go to **Certificate Manager** > **Settings** and select the **Alerts** tab.
+ </Step>
+ <Step>
+ 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**.
+ </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**.
+ </Step>
+ <Step>
+ Select **Add Channel** and choose where to send notifications. You can add up to 10 channels. Select **Continue**.
+ </Step>
+ <Step>
+ Check the summary on the **Review** step, then select **Create Alert**.
+ </Step>
+</Steps>
+
+## Which certificates an alert covers
+
+If you don't add a filter, the alert covers every certificate in Certificate Manager. Each filter you add narrows the alert:
+
+| Applications filter | Certificate Profiles filter | Certificates covered |
+|---------------------|-----------------------------|----------------------|
+| None | None | Every certificate |
+| Added | None | Every certificate in the selected applications |
+| None | Added | Every certificate issued from the selected profiles |
+| Added | Added | Certificates in the selected applications that were issued from the selected profiles |
+
+You can select up to 100 applications and 100 profiles.
+
+## FAQ
+
+<AccordionGroup>
+ <Accordion title="What happens to an alert when I delete an application or profile it lists?">
+ The alert keeps the deleted application or profile in its list, and the deleted one matches no certificates. When you edit the alert, the **Filters** step shows it as **Unknown application** or **Unknown profile**, so you can remove it.
+ </Accordion>
+ <Accordion title="Why did I get two notifications for the same certificate?">
+ If a certificate is covered by a Certificate Manager alert and an older alert under **Legacy** > **Alerts** in the sidebar, each alert sends its own notification. Older alerts keep running until you delete them. You can also get one notification from a Certificate Manager alert and one from an application alert if both cover the certificate.
+ </Accordion>
+ <Accordion title="What do webhook receivers get from Certificate Manager alerts?">
+ The [application alert webhook payload](/documentation/platform/pki/applications/alerting/webhook-alerts#webhook-payload-format), with these differences:
+
+ | Field | Certificate Manager alert |
+ |-------|---------------------------|
+ | `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 |
+ </Accordion>
+</AccordionGroup>
+
+## What's next?
+
+<CardGroup cols={2}>
+ <Card title="Application alerts" icon="bell" href="/documentation/platform/pki/applications/alerting/overview">
+ Alert on the certificates in one application.
+ </Card>
+ <Card title="Webhook" icon="webhook" href="/documentation/platform/pki/applications/alerting/webhook-alerts">
+ Send alerts to your own endpoint.
+ </Card>
+</CardGroup>
diff --git a/frontend/src/components/pki-syncs/PkiSyncFilterBadges.tsx b/frontend/src/components/pki-syncs/PkiSyncFilterBadges.tsx
index e45a922a05..e7aecab13d 100644
--- a/frontend/src/components/pki-syncs/PkiSyncFilterBadges.tsx
+++ b/frontend/src/components/pki-syncs/PkiSyncFilterBadges.tsx
@@ -69,7 +69,7 @@ export const PkiSyncFilterCountLabel = ({ count, names }: TFilterCountLabelProps
);
};
-const PkiSyncFilterValueBadges = ({ values }: { values: string[] }) => {
+export const PkiSyncFilterValueBadges = ({ values }: { values: string[] }) => {
if (values.length === 0) return null;
return (
diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.ts
index 779c289a47..25e383c4ef 100644
--- a/frontend/src/hooks/api/alerts/types.ts
+++ b/frontend/src/hooks/api/alerts/types.ts
@@ -42,6 +42,7 @@ export enum CertificateAlertEventType {
export const MIN_ALERT_BEFORE_DAYS = 1;
export const MAX_ALERT_BEFORE_DAYS = 90;
export const MAX_CERTIFICATE_ALERT_BEFORE_DAYS = 365;
+export const MAX_CERTIFICATE_ALERT_FILTER_IDS = 100;
export const ALERT_RESOURCE_TYPE_LABELS: Record<AlertResourceType, string> = {
[AlertResourceType.IdentityAuthentication]: "Machine Identity Authentication"
@@ -80,6 +81,8 @@ export type TAlertChannelEmbedded = {
recipients: TAlertChannelRecipient[];
};
+export type TAlertFilterValue = { id: string; name: string | null };
+
export type TAlert = {
id: string;
name: string;
@@ -87,11 +90,17 @@ export type TAlert = {
resourceType: string;
resourceId: string | null;
eventType: string;
- condition: { alertBefore?: string; dailyReminder?: boolean } | null;
+ condition: {
+ alertBefore?: string;
+ dailyReminder?: boolean;
+ applicationIds?: string[];
+ profileIds?: string[];
+ } | null;
enabled: boolean;
orgId: string;
projectId: string | null;
resourceName: string | null;
+ filters?: Record<string, TAlertFilterValue[]>;
channels: TAlertChannelEmbedded[];
lastRun: { timestamp: string; status: AlertRunStatus } | null;
createdAt: string;
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index f5913a6f3b..de1d5e6bbd 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -124,6 +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_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 c082c59eac..84352694a4 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -140,6 +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_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 d215370b1b..9d4604c1f0 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx
@@ -54,7 +54,82 @@ import {
import { PkiDocsUrls } from "../../../pki-docs-urls";
import { CertificateAlertSheet } from "./CertificateAlertSheet";
-import { CERTIFICATE_ALERT_EVENT_LABELS, formatAlertBefore } from "./types";
+import {
+ CERTIFICATE_ALERT_EVENT_LABELS,
+ CERTIFICATE_FILTER_DEFINITIONS,
+ CertificateAlertScopeKind,
+ formatAlertBefore,
+ getAlertResourceId,
+ getFilterName,
+ pluralize,
+ TCertificateAlertScope,
+ TCertificateFilterKind,
+ toConditionNames
+} from "./types";
+
+const SCOPE_CARD_CONFIG: Record<
+ CertificateAlertScopeKind,
+ { description: string; emptyDescription: string; docsUrl: string; hasFiltersColumn: boolean }
+> = {
+ [CertificateAlertScopeKind.Application]: {
+ description: "Get notified about certificate events.",
+ emptyDescription:
+ "No alerts configured. Create one to get notified about certificate events for this application.",
+ docsUrl: PkiDocsUrls.applications.alerting.overview,
+ hasFiltersColumn: false
+ },
+ [CertificateAlertScopeKind.CertificateManager]: {
+ description:
+ "Get notified about certificate events anywhere in Certificate Manager, inside or outside an application.",
+ emptyDescription:
+ "No alerts configured. Create one to get notified about certificate events across Certificate Manager.",
+ docsUrl: PkiDocsUrls.settings.alerts,
+ hasFiltersColumn: true
+ }
+};
+
+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[]) =>
+ ids.map((id) => getFilterName(kind, id, conditionNames)).join(", ");
+
+ if (!applicationIds.length && !profileIds.length) {
+ return <span className="text-muted">All certificates</span>;
+ }
+
+ const summary = [
+ applicationIds.length ? pluralize(applicationIds.length, "application") : null,
+ profileIds.length ? pluralize(profileIds.length, "certificate profile") : null
+ ]
+ .filter(Boolean)
+ .join(", ");
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="cursor-default text-accent">{summary}</span>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="flex max-w-sm flex-col gap-1">
+ {applicationIds.length > 0 && (
+ <span>
+ <span className="text-muted">
+ {CERTIFICATE_FILTER_DEFINITIONS.applicationIds.label}:{" "}
+ </span>
+ {namesOf("applicationIds", applicationIds)}
+ </span>
+ )}
+ {profileIds.length > 0 && (
+ <span>
+ <span className="text-muted">{CERTIFICATE_FILTER_DEFINITIONS.profileIds.label}: </span>
+ {namesOf("profileIds", profileIds)}
+ </span>
+ )}
+ </TooltipContent>
+ </Tooltip>
+ );
+};
const LAST_RUN_BADGES: Record<
AlertRunStatus,
@@ -72,9 +147,18 @@ type AlertRowProps = {
onDelete: () => void;
canEdit: boolean;
canDelete: boolean;
+ scope: TCertificateAlertScope;
};
-const AlertRow = ({ alert, onView, onEdit, onDelete, canEdit, canDelete }: AlertRowProps) => {
+const AlertRow = ({
+ alert,
+ onView,
+ onEdit,
+ onDelete,
+ canEdit,
+ canDelete,
+ scope
+}: AlertRowProps) => {
const { mutate: updateAlert } = useUpdateAlert();
const handleToggleAlert = () =>
@@ -115,11 +199,16 @@ const AlertRow = ({ alert, onView, onEdit, onDelete, canEdit, canDelete }: Alert
{alert.enabled ? "Enabled" : "Disabled"}
</Badge>
</TableCell>
+ {SCOPE_CARD_CONFIG[scope.kind].hasFiltersColumn && (
+ <TableCell className="whitespace-nowrap">
+ <AlertFiltersSummary alert={alert} />
+ </TableCell>
+ )}
<TableCell className="whitespace-nowrap text-accent">
{alert.condition?.alertBefore ? (
formatAlertBefore(alert.condition.alertBefore)
) : (
- <span className="text-surface-selected">—</span>
+ <span className="text-surface-selected">-</span>
)}
</TableCell>
<TableCell className="whitespace-nowrap">
@@ -140,7 +229,7 @@ const AlertRow = ({ alert, onView, onEdit, onDelete, canEdit, canDelete }: Alert
</TooltipContent>
</Tooltip>
) : (
- <span className="text-surface-selected">—</span>
+ <span className="text-surface-selected">-</span>
)}
</TableCell>
<TableCell className="text-right">
@@ -178,8 +267,7 @@ const AlertRow = ({ alert, onView, onEdit, onDelete, canEdit, canDelete }: Alert
type Props = {
projectId: string;
- applicationId: string;
- applicationName: string;
+ scope: TCertificateAlertScope;
canCreate: boolean;
canEdit: boolean;
canDelete: boolean;
@@ -187,17 +275,34 @@ type Props = {
export const ApplicationAlertsCard = ({
projectId,
- applicationId,
- applicationName,
+ scope,
canCreate,
canEdit,
canDelete
}: Props) => {
+ const config = SCOPE_CARD_CONFIG[scope.kind];
+ const columns = [
+ { label: "Name", className: "w-1/3" },
+ { label: "Alert Type", className: "whitespace-nowrap" },
+ { label: "Status", className: "whitespace-nowrap" },
+ ...(config.hasFiltersColumn ? [{ label: "Filters", className: "whitespace-nowrap" }] : []),
+ { label: "Alert Before", className: "whitespace-nowrap" },
+ { label: "Last Run", className: "whitespace-nowrap" },
+ { label: "Actions", className: "w-5 text-right" }
+ ];
+ const resourceId = getAlertResourceId(scope);
const { data: alerts = [], isLoading: isAlertsLoading } = useListAlerts({
resourceType: CertificateAlertResourceType.Application,
projectId,
- resourceId: applicationId
+ ...(resourceId ? { resourceId } : {})
});
+ const usedEventTypes =
+ scope.kind === CertificateAlertScopeKind.Application
+ ? alerts.map((alert) => alert.eventType as CertificateAlertEventType)
+ : [];
+ const hasAllEventTypes = Object.values(CertificateAlertEventType).every((eventType) =>
+ usedEventTypes.includes(eventType)
+ );
const [alertModal, setAlertModal] = useState<{
isOpen: boolean;
alertId?: string;
@@ -212,11 +317,6 @@ export const ApplicationAlertsCard = ({
}>({ isOpen: false });
const { mutateAsync: deleteAlert } = useDeleteAlert();
- const usedEventTypes = alerts.map((a) => a.eventType as CertificateAlertEventType);
- const hasAllEventTypes = Object.values(CertificateAlertEventType).every((event) =>
- usedEventTypes.includes(event)
- );
-
const handleDeleteAlert = async () => {
if (!deleteAlertModal.alertId) return;
await deleteAlert({ alertId: deleteAlertModal.alertId });
@@ -229,10 +329,10 @@ export const ApplicationAlertsCard = ({
<Card>
<CardHeader>
<CardTitle>
- Alerting
- <DocumentationLinkBadge href={PkiDocsUrls.applications.alerting.overview} />
+ Alerts
+ <DocumentationLinkBadge href={config.docsUrl} />
</CardTitle>
- <CardDescription>Get notified about certificate events.</CardDescription>
+ <CardDescription>{config.description}</CardDescription>
<CardAction>
<Tooltip>
<TooltipTrigger asChild>
@@ -267,29 +367,25 @@ export const ApplicationAlertsCard = ({
<EmptyMedia variant="icon">
<BellIcon />
</EmptyMedia>
- <EmptyDescription>
- No alerts configured. Create one to get notified about certificate events for this
- application.
- </EmptyDescription>
+ <EmptyDescription>{config.emptyDescription}</EmptyDescription>
</Empty>
) : (
<Table>
<TableHeader>
<TableRow>
- <TableHead className="w-1/3">Name</TableHead>
- <TableHead className="whitespace-nowrap">Alert Type</TableHead>
- <TableHead className="whitespace-nowrap">Status</TableHead>
- <TableHead className="whitespace-nowrap">Alert Before</TableHead>
- <TableHead className="whitespace-nowrap">Last Run</TableHead>
- <TableHead className="w-5 text-right">Actions</TableHead>
+ {columns.map((column) => (
+ <TableHead key={column.label} className={column.className}>
+ {column.label}
+ </TableHead>
+ ))}
</TableRow>
</TableHeader>
<TableBody>
{isAlertsLoading &&
Array.from({ length: 3 }, (_, idx) => (
<TableRow key={`alert-skeleton-${idx + 1}`}>
- {Array.from({ length: 6 }, (__, cellIdx) => (
- <TableCell key={`alert-skeleton-cell-${cellIdx + 1}`}>
+ {columns.map((column) => (
+ <TableCell key={column.label}>
<Skeleton className="h-4 w-24" />
</TableCell>
))}
@@ -309,6 +405,7 @@ export const ApplicationAlertsCard = ({
}
canEdit={canEdit}
canDelete={canDelete}
+ scope={scope}
/>
))}
</TableBody>
@@ -320,8 +417,7 @@ export const ApplicationAlertsCard = ({
isOpen={alertModal.isOpen}
onOpenChange={(isOpen) => setAlertModal({ isOpen, alertId: undefined })}
projectId={projectId}
- applicationId={applicationId}
- applicationName={applicationName}
+ scope={scope}
alert={alerts.find((a) => a.id === alertModal.alertId)}
isReadOnly={alertModal.isReadOnly}
usedEventTypes={usedEventTypes}
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 ddb4c8d984..f3d1e50e0d 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { FormProvider, useFieldArray, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { BellIcon } from "lucide-react";
@@ -6,6 +6,7 @@ import { BellIcon } from "lucide-react";
import { createNotification } from "@app/components/notifications";
import {
Button,
+ DiscardChangesAlertDialog,
Sheet,
SheetContent,
SheetDescription,
@@ -32,17 +33,23 @@ import {
useCreateAlert,
useUpdateAlert
} from "@app/hooks/api/alerts";
+import { useDiscardChangesGuard } from "@app/hooks/useDiscardChangesGuard";
import { buildNextChannel, canReceiveAlerts } from "@app/views/Alerts";
import { CertificateAlertAddChannelMenu, ChannelsStep } from "./ChannelsStep";
import { DetailsStep } from "./DetailsStep";
+import { FiltersStep } from "./FiltersStep";
import { ReviewStep } from "./ReviewStep";
import {
certificateAlertFormSchema,
+ CertificateAlertScopeKind,
+ CertificateAlertStep,
emptyCertificateAlertForm,
+ getAlertResourceId,
+ getSteps,
STEP_FIELDS,
- STEPS,
TCertificateAlertForm,
+ TCertificateAlertScope,
TMemberEmails,
toCertificateAlertForm,
toCondition
@@ -52,27 +59,30 @@ type Props = {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
projectId: string;
- applicationId: string;
- applicationName: string;
+ scope: TCertificateAlertScope;
alert?: TAlert;
isReadOnly?: boolean;
usedEventTypes: CertificateAlertEventType[];
};
-type WizardProps = Omit<Props, "isOpen"> & { members: TMemberEmails };
+type WizardProps = Omit<Props, "isOpen"> & {
+ members: TMemberEmails;
+ onDirtyChange: (isDirty: boolean) => void;
+};
const CertificateAlertWizard = ({
onOpenChange,
projectId,
- applicationId,
- applicationName,
+ scope,
alert,
isReadOnly = false,
usedEventTypes,
- members
+ members,
+ onDirtyChange
}: WizardProps) => {
const isEditing = Boolean(alert);
- const [step, setStep] = useState(isReadOnly ? STEPS.length - 1 : 0);
+ const steps = getSteps(scope);
+ const [step, setStep] = useState(isReadOnly ? steps.length - 1 : 0);
const createAlert = useCreateAlert();
const updateAlert = useUpdateAlert();
@@ -86,10 +96,15 @@ const CertificateAlertWizard = ({
)
});
const { fields, append, remove } = useFieldArray({ control: form.control, name: "channels" });
+ const { isDirty } = form.formState;
+
+ useEffect(() => {
+ onDirtyChange(isDirty);
+ }, [isDirty, onDirtyChange]);
const onSubmit = async (values: TCertificateAlertForm) => {
const channels = values.channels.map(toChannelInput);
- const condition = toCondition(values);
+ const condition = toCondition(scope, values);
try {
if (alert) {
@@ -107,7 +122,7 @@ const CertificateAlertWizard = ({
name: values.name,
description: values.description || undefined,
resourceType: CertificateAlertResourceType.Application,
- resourceId: applicationId,
+ resourceId: getAlertResourceId(scope),
eventType: values.eventType,
condition,
enabled: values.enabled,
@@ -127,16 +142,17 @@ const CertificateAlertWizard = ({
};
const goNext = async () => {
- if (step < STEP_FIELDS.length) {
- if (await form.trigger(STEP_FIELDS[step])) setStep(step + 1);
+ const stepFields = STEP_FIELDS[steps[step].key];
+ if (stepFields) {
+ if (await form.trigger(stepFields)) setStep(step + 1);
return;
}
await form.handleSubmit(onSubmit)();
};
- const isLast = step === STEPS.length - 1;
+ const isLast = step === steps.length - 1;
const { isSubmitting } = form.formState;
- const currentStep = STEPS[step];
+ const currentStep = steps[step];
const submitLabel = isEditing ? "Update Alert" : "Create Alert";
let title = isEditing ? "Edit Certificate Alert" : "Create Certificate Alert";
if (isReadOnly) title = "Certificate Alert Details";
@@ -152,7 +168,9 @@ const CertificateAlertWizard = ({
<div>
<div className="text-label">{title}</div>
<SheetDescription>
- Get notified about certificate events in {applicationName}.
+ {scope.kind === CertificateAlertScopeKind.Application
+ ? `Get notified about certificate events in ${scope.applicationName}.`
+ : "Get notified about certificate events across Certificate Manager."}
</SheetDescription>
</div>
</div>
@@ -171,7 +189,7 @@ const CertificateAlertWizard = ({
}}
>
<StepperList>
- {STEPS.map((item, index) => (
+ {steps.map((item, index) => (
<StepperStep
key={item.name}
index={index}
@@ -190,26 +208,36 @@ const CertificateAlertWizard = ({
<h2 className="text-lg font-semibold text-foreground">{currentStep.title}</h2>
{!isReadOnly && <p className="mt-1 text-sm text-muted">{currentStep.subtitle}</p>}
</div>
- {step === 1 && (
+ {currentStep.key === CertificateAlertStep.Channels && (
<CertificateAlertAddChannelMenu channelCount={fields.length} onAdd={addChannel} />
)}
</div>
- {step === 0 && (
- <DetailsStep form={form} isEditing={isEditing} usedEventTypes={usedEventTypes} />
+ {currentStep.key === CertificateAlertStep.Details && (
+ <DetailsStep
+ form={form}
+ scope={scope}
+ isEditing={isEditing}
+ usedEventTypes={usedEventTypes}
+ />
+ )}
+ {currentStep.key === CertificateAlertStep.Filters && (
+ <FiltersStep form={form} projectId={projectId} />
)}
- {step === 1 && (
+ {currentStep.key === CertificateAlertStep.Channels && (
<ChannelsStep
form={form}
fields={fields}
onRemove={remove}
projectId={projectId}
- applicationId={applicationId}
+ scope={scope}
alertId={alert?.id}
members={members}
/>
)}
- {step === 2 && <ReviewStep form={form} members={members} />}
+ {currentStep.key === CertificateAlertStep.Review && (
+ <ReviewStep form={form} scope={scope} members={members} />
+ )}
</div>
</div>
@@ -221,7 +249,7 @@ const CertificateAlertWizard = ({
) : (
<>
<span className="text-xs text-muted">
- Step {step + 1} of {STEPS.length}
+ Step {step + 1} of {steps.length}
</span>
<div className="flex items-center gap-3">
{step > 0 && (
@@ -272,23 +300,50 @@ export const CertificateAlertSheet = ({ isOpen, onOpenChange, ...props }: Props)
};
}, [orgUsers]);
+ const [isDirty, setIsDirty] = useState(false);
+ const closeSheet = () => {
+ setIsDirty(false);
+ onOpenChange(false);
+ };
+ const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =
+ useDiscardChangesGuard({ isDirty, onDiscard: closeSheet });
+
+ const handleSheetOpenChange = (open: boolean) => {
+ if (!open) {
+ requestDiscard();
+ return;
+ }
+ onOpenChange(true);
+ };
+
return (
- <Sheet open={isOpen} onOpenChange={onOpenChange}>
- <SheetContent size="wide" className="flex h-full max-h-full flex-col gap-y-0">
- {isOpen && isUsersPending && (
- <div className="flex flex-1 items-center justify-center">
- <Spinner />
- </div>
- )}
- {isOpen && !isUsersPending && (
- <CertificateAlertWizard
- key={props.alert?.id ?? "new"}
- onOpenChange={onOpenChange}
- members={members}
- {...props}
- />
- )}
- </SheetContent>
- </Sheet>
+ <>
+ <Sheet open={isOpen} onOpenChange={handleSheetOpenChange}>
+ <SheetContent size="wide" className="flex h-full max-h-full flex-col gap-y-0">
+ {isOpen && isUsersPending && (
+ <div className="flex flex-1 items-center justify-center">
+ <Spinner />
+ </div>
+ )}
+ {isOpen && !isUsersPending && (
+ <CertificateAlertWizard
+ key={props.alert?.id ?? "new"}
+ onOpenChange={(open) => (open ? onOpenChange(true) : closeSheet())}
+ onDirtyChange={setIsDirty}
+ members={members}
+ {...props}
+ />
+ )}
+ </SheetContent>
+ </Sheet>
+
+ <DiscardChangesAlertDialog
+ open={isDiscardDialogOpen}
+ onOpenChange={setIsDiscardDialogOpen}
+ onDiscard={confirmDiscard}
+ title="Discard Changes?"
+ description="Your unsaved changes to this alert will be lost."
+ />
+ </>
);
};
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateFilterSelects.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateFilterSelects.tsx
new file mode 100644
index 0000000000..b2794551c8
--- /dev/null
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateFilterSelects.tsx
@@ -0,0 +1,105 @@
+import { useMemo, useState } from "react";
+
+import { Combobox } from "@app/components/v3";
+import { useDebounce } from "@app/hooks";
+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";
+
+type TFilterOption = { id: string; name: string };
+
+type Props = {
+ value: string[];
+ conditionNames: Record<string, string>;
+ onChange: (selected: TFilterOption[]) => void;
+};
+
+const FilterCombobox = ({
+ kind,
+ value,
+ conditionNames,
+ onChange,
+ options,
+ isLoading,
+ onSearchChange,
+ placeholder
+}: Props & {
+ kind: TCertificateFilterKind;
+ options: TFilterOption[];
+ isLoading: boolean;
+ onSearchChange: (search: string) => void;
+ placeholder: string;
+}) => {
+ const optionNames = useMemo(
+ () => new Map(options.map((option) => [option.id, option.name])),
+ [options]
+ );
+
+ return (
+ <Combobox
+ multiple
+ isClearable
+ options={options}
+ value={value.map((id) => ({
+ id,
+ name: optionNames.get(id) ?? getFilterName(kind, id, conditionNames)
+ }))}
+ onValueChange={(selected) => onChange([...selected])}
+ getOptionValue={(option) => option.id}
+ getOptionLabel={(option) => option.name}
+ onSearchChange={onSearchChange}
+ isLoading={isLoading}
+ placeholder={placeholder}
+ />
+ );
+};
+
+export const ApplicationFilterSelect = (props: Props) => {
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search);
+ const { data, isPending } = useListPkiApplications({
+ limit: MAX_CERTIFICATE_ALERT_FILTER_IDS,
+ ...(debouncedSearch ? { search: debouncedSearch } : {})
+ });
+ const options = useMemo(
+ () => (data?.applications ?? []).map(({ id, name }) => ({ id, name })),
+ [data]
+ );
+
+ return (
+ <FilterCombobox
+ {...props}
+ kind="applicationIds"
+ options={options}
+ isLoading={isPending}
+ onSearchChange={setSearch}
+ placeholder="Select applications"
+ />
+ );
+};
+
+export const ProfileFilterSelect = (props: Props) => {
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search);
+ const { data, isPending } = useListCertificateProfiles({
+ limit: MAX_CERTIFICATE_ALERT_FILTER_IDS,
+ ...(debouncedSearch ? { search: debouncedSearch } : {})
+ });
+ const options = useMemo(
+ () => (data?.certificateProfiles ?? []).map(({ id, slug }) => ({ id, name: slug })),
+ [data]
+ );
+
+ return (
+ <FilterCombobox
+ {...props}
+ kind="profileIds"
+ options={options}
+ isLoading={isPending}
+ onSearchChange={setSearch}
+ placeholder="Select profiles"
+ />
+ );
+};
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 3b7d370777..d51b57be77 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ChannelsStep.tsx
@@ -21,9 +21,11 @@ import {
import { AddChannelMenu, ChannelCard, TChannelRecipientsRenderProps } from "@app/views/Alerts";
import {
+ getAlertResourceId,
MAX_CHANNELS,
normalizeEmail,
TCertificateAlertForm,
+ TCertificateAlertScope,
TMemberEmails,
toRecipientEmails
} from "./types";
@@ -134,7 +136,7 @@ export const ChannelsStep = ({
fields,
onRemove,
projectId,
- applicationId,
+ scope,
alertId,
members
}: {
@@ -142,7 +144,7 @@ export const ChannelsStep = ({
fields: TChannelField[];
onRemove: (index: number) => void;
projectId: string;
- applicationId: string;
+ scope: TCertificateAlertScope;
alertId?: string;
members: TMemberEmails;
}) => {
@@ -172,7 +174,7 @@ export const ChannelsStep = ({
index={index}
projectId={projectId}
resourceType={CertificateAlertResourceType.Application}
- resourceId={applicationId}
+ resourceId={getAlertResourceId(scope)}
alertId={alertId}
canRemove
onRemove={() => onRemove(index)}
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 e9f1553b99..734e9e0332 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/DetailsStep.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/DetailsStep.tsx
@@ -19,18 +19,20 @@ import {
import { CertificateAlertEventType } from "@app/hooks/api/alerts";
import {
- CERTIFICATE_ALERT_EVENT_DESCRIPTIONS,
CERTIFICATE_ALERT_EVENT_LABELS,
- TCertificateAlertForm
+ getAlertEventDescription,
+ TCertificateAlertForm,
+ TCertificateAlertScope
} from "./types";
type Props = {
form: UseFormReturn<TCertificateAlertForm>;
+ scope: TCertificateAlertScope;
isEditing: boolean;
usedEventTypes: CertificateAlertEventType[];
};
-export const DetailsStep = ({ form, isEditing, usedEventTypes }: Props) => {
+export const DetailsStep = ({ form, scope, isEditing, usedEventTypes }: Props) => {
const eventType = useWatch({ control: form.control, name: "eventType" });
return (
@@ -58,9 +60,7 @@ export const DetailsStep = ({ form, isEditing, usedEventTypes }: Props) => {
))}
</SelectContent>
</Select>
- <FieldDescription>
- {CERTIFICATE_ALERT_EVENT_DESCRIPTIONS[field.value]}
- </FieldDescription>
+ <FieldDescription>{getAlertEventDescription(scope, field.value)}</FieldDescription>
</FieldContent>
</Field>
)}
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/FiltersStep.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/FiltersStep.tsx
new file mode 100644
index 0000000000..80183e51dd
--- /dev/null
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/FiltersStep.tsx
@@ -0,0 +1,245 @@
+import { Fragment, useState } from "react";
+import { UseFormReturn, useWatch } from "react-hook-form";
+import { FilterIcon, PlusIcon, RefreshCwIcon, TrashIcon, TriangleAlertIcon } from "lucide-react";
+
+import { PkiSyncMatchedCertificatesTable } from "@app/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable";
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyMedia,
+ Field,
+ FieldContent,
+ FieldError,
+ FieldLabel,
+ IconButton,
+ Pagination,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { useListWorkspaceCertificates } from "@app/hooks/api";
+import { CertStatus } from "@app/hooks/api/certificates/enums";
+
+import { ApplicationFilterSelect, ProfileFilterSelect } from "./CertificateFilterSelects";
+import {
+ CERTIFICATE_FILTER_DEFINITIONS,
+ hasUnfinishedFilter,
+ NO_FILTERS_DESCRIPTION,
+ TCertificateAlertForm,
+ TCertificateFilterKind
+} from "./types";
+
+const MATCHED_PAGE_SIZE = 20;
+
+const FILTER_KINDS = Object.keys(CERTIFICATE_FILTER_DEFINITIONS) as TCertificateFilterKind[];
+
+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 conditionNames = useWatch({ control: form.control, name: "conditionNames" });
+ const filters = { applicationIds, profileIds };
+
+ const [previewFilters, setPreviewFilters] = useState(filters);
+ const [page, setPage] = useState(1);
+ const isStale = JSON.stringify(filters) !== JSON.stringify(previewFilters);
+ const isUnfinished = hasUnfinishedFilter(filters);
+
+ const {
+ data: preview,
+ isFetching: isPreviewing,
+ refetch: refetchPreview
+ } = useListWorkspaceCertificates({
+ projectId,
+ offset: (page - 1) * MATCHED_PAGE_SIZE,
+ limit: MATCHED_PAGE_SIZE,
+ status: CertStatus.ACTIVE,
+ applicationIds: previewFilters.applicationIds,
+ profileIds: previewFilters.profileIds
+ });
+
+ const reloadPreview = () => {
+ setPage(1);
+ if (isStale) setPreviewFilters(filters);
+ else refetchPreview().catch(() => {});
+ };
+
+ const setFilter = (kind: TCertificateFilterKind, ids: string[] | undefined) =>
+ form.setValue(kind, ids, { shouldDirty: true, shouldValidate: true });
+ const addFilter = (kind: TCertificateFilterKind) =>
+ 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 certificatesLabel = `${matchedCount} active certificate${matchedCount === 1 ? "" : "s"}`;
+ let previewSummary = "Loading the certificates this alert covers.";
+ if (preview && !isPreviewing) {
+ previewSummary = isPreviewFiltered
+ ? `${certificatesLabel} ${matchedCount === 1 ? "matches" : "match"} these filters.`
+ : `${certificatesLabel} in Certificate Manager.`;
+ }
+
+ 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>
+ );
+
+ return (
+ <div className="flex flex-col">
+ <div>
+ <p className="text-sm font-medium text-foreground">Filters</p>
+ <p className="mt-0.5 text-xs text-muted">
+ A certificate is covered only when it matches every filter below.
+ </p>
+ </div>
+
+ {presentKinds.length > 0 ? (
+ <div className="mt-3 flex flex-col gap-3">
+ {presentKinds.map((kind, index) => {
+ const Select =
+ kind === "applicationIds" ? ApplicationFilterSelect : ProfileFilterSelect;
+ const { label } = CERTIFICATE_FILTER_DEFINITIONS[kind];
+ return (
+ <Fragment key={kind}>
+ {index > 0 && (
+ <div className="flex items-center gap-3">
+ <span className="h-px flex-1 bg-border" />
+ <span className="text-xs font-medium text-muted">AND</span>
+ <span className="h-px flex-1 bg-border" />
+ </div>
+ )}
+ <div className="flex items-start gap-3">
+ <Field className="min-w-0 flex-1">
+ <FieldLabel className="text-xs">{label}</FieldLabel>
+ <FieldContent>
+ <Select
+ value={filters[kind] ?? []}
+ conditionNames={conditionNames}
+ onChange={(selected) => {
+ form.setValue("conditionNames", {
+ ...conditionNames,
+ ...Object.fromEntries(selected.map(({ id, name }) => [id, name]))
+ });
+ setFilter(
+ kind,
+ selected.map(({ id }) => id)
+ );
+ }}
+ />
+ <FieldError errors={[form.formState.errors[kind]]} />
+ </FieldContent>
+ </Field>
+ <IconButton
+ type="button"
+ size="xs"
+ variant="ghost"
+ className="mt-6.5 hover:text-danger"
+ aria-label={`Remove ${label} filter`}
+ onClick={() => setFilter(kind, undefined)}
+ >
+ <TrashIcon className="size-4" />
+ </IconButton>
+ </div>
+ </Fragment>
+ );
+ })}
+ </div>
+ ) : (
+ <Empty className="mt-3 flex-none border py-8">
+ <EmptyMedia variant="icon">
+ <FilterIcon />
+ </EmptyMedia>
+ <EmptyDescription>{NO_FILTERS_DESCRIPTION} Add a filter to narrow it.</EmptyDescription>
+ </Empty>
+ )}
+
+ {addableKinds.length > 0 && (
+ <div className="mt-3">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button type="button" variant="outline" size="sm">
+ <PlusIcon className="size-3.5" />
+ Add Filter
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-64">
+ {addableKinds.map((kind) => (
+ <DropdownMenuItem key={kind} onClick={() => addFilter(kind)}>
+ <div className="flex flex-col">
+ <span>{CERTIFICATE_FILTER_DEFINITIONS[kind].label}</span>
+ <span className="text-xs text-muted">
+ {CERTIFICATE_FILTER_DEFINITIONS[kind].hint}
+ </span>
+ </div>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ )}
+
+ <div className="mt-8 flex items-start justify-between gap-4">
+ <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
+ )}
+ </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."
+ }
+ />
+ {matchedCount > MATCHED_PAGE_SIZE && (
+ <Pagination
+ className="mt-2"
+ count={matchedCount}
+ page={page}
+ perPage={MATCHED_PAGE_SIZE}
+ onChangePage={setPage}
+ onChangePerPage={() => {}}
+ perPageList={[MATCHED_PAGE_SIZE]}
+ />
+ )}
+ </div>
+ </div>
+ );
+};
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 59dabcf4ab..d9a1c5346c 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsx
@@ -1,6 +1,7 @@
import { ReactNode } from "react";
import { UseFormReturn, useWatch } from "react-hook-form";
+import { PkiSyncFilterValueBadges } from "@app/components/pki-syncs/PkiSyncFilterBadges";
import { Badge } from "@app/components/v3";
import {
ALERT_CHANNEL_TYPE_LABELS,
@@ -12,12 +13,22 @@ import {
import {
CERTIFICATE_ALERT_EVENT_LABELS,
+ CERTIFICATE_FILTER_DEFINITIONS,
+ CertificateAlertScopeKind,
+ formatAlertBefore,
+ getFilterName,
+ NO_FILTERS_DESCRIPTION,
TCertificateAlertForm,
+ TCertificateAlertScope,
TMemberEmails,
toRecipientEmails
} from "./types";
-type Props = { form: UseFormReturn<TCertificateAlertForm>; members: TMemberEmails };
+type Props = {
+ form: UseFormReturn<TCertificateAlertForm>;
+ scope: TCertificateAlertScope;
+ members: TMemberEmails;
+};
const Section = ({ title, children }: { title: string; children: ReactNode }) => (
<div className="flex flex-col gap-4">
@@ -27,9 +38,9 @@ const Section = ({ title, children }: { title: string; children: ReactNode }) =>
);
const Detail = ({ label, children }: { label: string; children: ReactNode }) => (
- <div className="flex flex-col gap-1">
+ <div className="flex min-w-0 flex-col gap-1">
<span className="text-xs text-muted">{label}</span>
- <span className="text-sm text-foreground">{children}</span>
+ <div className="text-sm break-words text-foreground">{children}</div>
</div>
);
@@ -59,7 +70,39 @@ const describeChannel = (channel: TChannelForm, members: TMemberEmails): string
}
};
-export const ReviewStep = ({ form, members }: Props) => {
+const FilterDetails = ({
+ applicationIds,
+ profileIds,
+ conditionNames
+}: {
+ applicationIds: string[];
+ profileIds: string[];
+ conditionNames: Record<string, string>;
+}) => {
+ const getApplicationName = (id: string) => getFilterName("applicationIds", id, conditionNames);
+ const getProfileName = (id: string) => getFilterName("profileIds", id, conditionNames);
+
+ return (
+ <>
+ <Detail label={CERTIFICATE_FILTER_DEFINITIONS.applicationIds.label}>
+ {applicationIds.length ? (
+ <PkiSyncFilterValueBadges values={applicationIds.map(getApplicationName)} />
+ ) : (
+ CERTIFICATE_FILTER_DEFINITIONS.applicationIds.allLabel
+ )}
+ </Detail>
+ <Detail label={CERTIFICATE_FILTER_DEFINITIONS.profileIds.label}>
+ {profileIds.length ? (
+ <PkiSyncFilterValueBadges values={profileIds.map(getProfileName)} />
+ ) : (
+ CERTIFICATE_FILTER_DEFINITIONS.profileIds.allLabel
+ )}
+ </Detail>
+ </>
+ );
+};
+
+export const ReviewStep = ({ form, scope, members }: Props) => {
const values = useWatch({ control: form.control }) as TCertificateAlertForm;
const isExpiry = values.eventType === CertificateAlertEventType.Expiry;
@@ -72,7 +115,9 @@ export const ReviewStep = ({ form, members }: Props) => {
<Detail label="Status">
<EnabledBadge enabled={values.enabled} />
</Detail>
- {isExpiry && <Detail label="Alert Before">{values.alertBefore}</Detail>}
+ {isExpiry && (
+ <Detail label="Alert Before">{formatAlertBefore(values.alertBefore)}</Detail>
+ )}
{isExpiry && (
<Detail label="Repeat daily">
<EnabledBadge enabled={values.dailyReminder} />
@@ -82,6 +127,22 @@ export const ReviewStep = ({ form, 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>
+ )}
+
<Section title="Notification Channels">
<div className="flex flex-col gap-3">
{values.channels.map((channel, index) => (
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 d03ffb7388..d0de0861f2 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts
@@ -5,11 +5,24 @@ import {
CertificateAlertEventType,
channelFormSchema,
MAX_CERTIFICATE_ALERT_BEFORE_DAYS,
+ MAX_CERTIFICATE_ALERT_FILTER_IDS,
TAlert,
TAlertChannelRecipient,
TChannelForm
} from "@app/hooks/api/alerts";
+export enum CertificateAlertScopeKind {
+ Application = "application",
+ CertificateManager = "certificate-manager"
+}
+
+export type TCertificateAlertScope =
+ | { kind: CertificateAlertScopeKind.Application; applicationId: string; applicationName: string }
+ | { kind: CertificateAlertScopeKind.CertificateManager };
+
+export const getAlertResourceId = (scope: TCertificateAlertScope) =>
+ scope.kind === CertificateAlertScopeKind.Application ? scope.applicationId : null;
+
export const CERTIFICATE_ALERT_EVENT_LABELS: Record<CertificateAlertEventType, string> = {
[CertificateAlertEventType.Expiry]: "Certificate Expiration",
[CertificateAlertEventType.Issuance]: "Certificate Issuance",
@@ -17,14 +30,24 @@ export const CERTIFICATE_ALERT_EVENT_LABELS: Record<CertificateAlertEventType, s
[CertificateAlertEventType.Revocation]: "Certificate Revocation"
};
-export const CERTIFICATE_ALERT_EVENT_DESCRIPTIONS: Record<CertificateAlertEventType, string> = {
- [CertificateAlertEventType.Expiry]: "Fires ahead of a certificate's expiry date.",
- [CertificateAlertEventType.Issuance]:
- "Fires when Infisical issues a certificate in this application.",
- [CertificateAlertEventType.Renewal]: "Fires when a certificate in this application is renewed.",
- [CertificateAlertEventType.Revocation]: "Fires when a certificate in this application is revoked."
+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.`
};
+export const getAlertEventDescription = (
+ scope: TCertificateAlertScope,
+ eventType: CertificateAlertEventType
+) =>
+ ALERT_EVENT_DESCRIPTIONS[eventType](
+ scope.kind === CertificateAlertScopeKind.Application
+ ? "in this application"
+ : "in Certificate Manager"
+ );
+
export const MAX_CHANNELS = 10;
const ALERT_BEFORE_PATTERN = /^(\d{1,4})([dwmy])$/;
@@ -50,6 +73,9 @@ export const formatAlertBefore = (alertBefore?: string | null, fallback = "-"):
return `${value} ${ALERT_BEFORE_UNIT_LABELS[match[2]]}${value === 1 ? "" : "s"}`;
};
+export const pluralize = (count: number, noun: string) =>
+ `${count} ${noun}${count === 1 ? "" : "s"}`;
+
export const normalizeEmail = (email: string) => email.trim().toLowerCase();
export type TMemberEmails = {
@@ -70,26 +96,96 @@ export const toRecipientEmails = (
return recipient.principalType === AlertPrincipalType.Email ? [recipient.principalId] : [];
});
-export const STEPS = [
- {
+export type TCertificateFilterKind = "applicationIds" | "profileIds";
+
+export const CERTIFICATE_FILTER_DEFINITIONS: Record<
+ TCertificateFilterKind,
+ { label: string; hint: string; allLabel: string; unknownLabel: string }
+> = {
+ applicationIds: {
+ label: "Applications",
+ hint: "Certificates in one of these applications",
+ allLabel: "All applications",
+ unknownLabel: "Unknown application"
+ },
+ profileIds: {
+ label: "Certificate Profiles",
+ hint: "Issued from one of these profiles",
+ allLabel: "All certificate profiles",
+ unknownLabel: "Unknown profile"
+ }
+};
+
+export const NO_FILTERS_DESCRIPTION =
+ "No filters. This alert covers every certificate in Certificate Manager.";
+
+export const getFilterName = (
+ kind: TCertificateFilterKind,
+ id: string,
+ conditionNames: Record<string, string>
+) => conditionNames[id] ?? CERTIFICATE_FILTER_DEFINITIONS[kind].unknownLabel;
+
+export const toConditionNames = (alert: TAlert): Record<string, string> =>
+ Object.fromEntries(
+ Object.values(alert.filters ?? {})
+ .flat()
+ .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 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"
+};
+
+export enum CertificateAlertStep {
+ Details = "details",
+ Filters = "filters",
+ Channels = "channels",
+ Review = "review"
+}
+
+const STEP_DEFINITIONS = {
+ [CertificateAlertStep.Details]: {
name: "Details",
shortDescription: "Event and name",
title: "Alert Details",
subtitle: "Choose the event that triggers this alert and name it."
},
- {
+ [CertificateAlertStep.Filters]: {
+ name: "Filters",
+ shortDescription: "Which certificates",
+ title: "Certificate Filters",
+ subtitle: "Narrow which certificates this alert covers, or leave it on every certificate."
+ },
+ [CertificateAlertStep.Channels]: {
name: "Channels",
shortDescription: "Where it is sent",
title: "Notification Channels",
subtitle: "Add at least one destination for this alert."
},
- {
+ [CertificateAlertStep.Review]: {
name: "Review",
shortDescription: "Confirm and save",
title: "Review",
subtitle: "Check the settings below before saving this alert."
}
-] as const;
+};
+
+export const getSteps = (scope: TCertificateAlertScope) =>
+ (scope.kind === CertificateAlertScopeKind.CertificateManager
+ ? [
+ CertificateAlertStep.Details,
+ CertificateAlertStep.Filters,
+ CertificateAlertStep.Channels,
+ CertificateAlertStep.Review
+ ]
+ : [CertificateAlertStep.Details, CertificateAlertStep.Channels, CertificateAlertStep.Review]
+ ).map((key) => ({ key, ...STEP_DEFINITIONS[key] }));
export const certificateAlertFormSchema = z
.object({
@@ -99,9 +195,29 @@ export const certificateAlertFormSchema = z
alertBefore: z.string().trim(),
dailyReminder: z.boolean(),
enabled: z.boolean(),
+ applicationIds: z
+ .array(z.string())
+ .max(
+ MAX_CERTIFICATE_ALERT_FILTER_IDS,
+ `Select up to ${MAX_CERTIFICATE_ALERT_FILTER_IDS} applications`
+ )
+ .optional(),
+ profileIds: z
+ .array(z.string())
+ .max(
+ MAX_CERTIFICATE_ALERT_FILTER_IDS,
+ `Select up to ${MAX_CERTIFICATE_ALERT_FILTER_IDS} profiles`
+ )
+ .optional(),
+ conditionNames: z.record(z.string()),
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) => {
+ if (isUnfinishedFilter(form[kind])) {
+ ctx.addIssue({ code: "custom", path: [kind], message: UNFINISHED_FILTER_MESSAGES[kind] });
+ }
+ });
if (form.eventType !== CertificateAlertEventType.Expiry) return;
const days = alertBeforeToDays(form.alertBefore);
if (days === null) {
@@ -121,10 +237,17 @@ export const certificateAlertFormSchema = z
export type TCertificateAlertForm = z.infer<typeof certificateAlertFormSchema>;
-export const STEP_FIELDS: (keyof TCertificateAlertForm)[][] = [
- ["eventType", "name", "description", "alertBefore", "dailyReminder"],
- ["channels"]
-];
+export const STEP_FIELDS: Partial<Record<CertificateAlertStep, (keyof TCertificateAlertForm)[]>> = {
+ [CertificateAlertStep.Details]: [
+ "eventType",
+ "name",
+ "description",
+ "alertBefore",
+ "dailyReminder"
+ ],
+ [CertificateAlertStep.Filters]: ["applicationIds", "profileIds"],
+ [CertificateAlertStep.Channels]: ["channels"]
+};
export const emptyCertificateAlertForm = (
eventType = CertificateAlertEventType.Expiry
@@ -135,6 +258,7 @@ export const emptyCertificateAlertForm = (
alertBefore: "30d",
dailyReminder: false,
enabled: true,
+ conditionNames: {},
channels: []
});
@@ -148,6 +272,9 @@ export const toCertificateAlertForm = (
alertBefore: alert.condition?.alertBefore ?? "30d",
dailyReminder: alert.condition?.dailyReminder ?? false,
enabled: alert.enabled,
+ applicationIds: alert.condition?.applicationIds,
+ profileIds: alert.condition?.profileIds,
+ conditionNames: toConditionNames(alert),
channels: alert.channels.map(
(channel): TChannelForm => ({
id: channel.id,
@@ -171,7 +298,21 @@ export const toCertificateAlertForm = (
)
});
-export const toCondition = (form: TCertificateAlertForm) =>
- form.eventType === CertificateAlertEventType.Expiry
- ? { alertBefore: form.alertBefore.trim(), dailyReminder: form.dailyReminder }
- : null;
+export const toCondition = (scope: TCertificateAlertScope, form: TCertificateAlertForm) => {
+ const filters =
+ scope.kind === CertificateAlertScopeKind.CertificateManager
+ ? {
+ ...(form.applicationIds?.length ? { applicationIds: form.applicationIds } : {}),
+ ...(form.profileIds?.length ? { profileIds: form.profileIds } : {})
+ }
+ : {};
+
+ if (form.eventType === CertificateAlertEventType.Expiry) {
+ return {
+ alertBefore: form.alertBefore.trim(),
+ dailyReminder: form.dailyReminder,
+ ...filters
+ };
+ }
+ return Object.keys(filters).length ? filters : null;
+};
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx
index 3081e9ebba..5b9806b3f6 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx
@@ -77,6 +77,7 @@ import { CreateProfileModal } from "@app/pages/cert-manager/PoliciesPage/compone
import { PkiDocsUrls } from "../../pki-docs-urls";
import { ApplicationAlertsCard } from "./ApplicationAlerts/ApplicationAlertsCard";
import { LegacyApplicationAlertsCard } from "./ApplicationAlerts/LegacyApplicationAlertsCard";
+import { CertificateAlertScopeKind } from "./ApplicationAlerts/types";
import {
ConfigureEnrollmentModal,
EnrollmentMethod,
@@ -620,8 +621,11 @@ export const ApplicationSettingsTab = ({ application, profiles }: Props) => {
<ApplicationAlertsCard
projectId={application.projectId}
- applicationId={application.id}
- applicationName={application.name}
+ scope={{
+ kind: CertificateAlertScopeKind.Application,
+ applicationId: application.id,
+ applicationName: application.name
+ }}
canCreate={canCreateAlerts}
canEdit={canEditAlerts}
canDelete={canDeleteAlerts}
diff --git a/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx b/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx
index 7664442d51..e6d890c00c 100644
--- a/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx
+++ b/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx
@@ -3,13 +3,14 @@ import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ProjectPermissionCan } from "@app/components/permissions";
import { PageHeader, Tabs, TabsContent, TabsList, TabsTrigger } from "@app/components/v3";
-import { ProjectPermissionSub } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
import {
ProjectPermissionAppConnectionActions,
ProjectPermissionHsmConnectorActions
} from "@app/context/ProjectPermissionContext/types";
import { ProjectType } from "@app/hooks/api/projects/types";
+import { AlertsTab } from "./components/AlertsTab";
import { AppConnectionsTab } from "./components/AppConnectionsTab";
import { CertificateCleanupTab } from "./components/CertificateCleanupTab";
import { HsmConnectorsTab } from "./components/HsmConnectorsTab";
@@ -29,7 +30,7 @@ export const SettingsPage = () => {
<PageHeader
scope={ProjectType.CertificateManager}
title="Settings"
- description="Configure app connections, HSM connectors, and cleanup rules."
+ description="Configure app connections, HSM connectors, cleanup rules, and alerts."
/>
<Tabs
@@ -46,6 +47,7 @@ export const SettingsPage = () => {
<TabsTrigger value="app-connections">App Connections</TabsTrigger>
<TabsTrigger value="hsm-connectors">HSM Connectors</TabsTrigger>
<TabsTrigger value="cleanup">Cleanup</TabsTrigger>
+ <TabsTrigger value="alerts">Alerts</TabsTrigger>
</TabsList>
<TabsContent value="app-connections">
@@ -71,6 +73,16 @@ export const SettingsPage = () => {
<TabsContent value="cleanup">
<CertificateCleanupTab />
</TabsContent>
+
+ <TabsContent value="alerts">
+ <ProjectPermissionCan
+ renderGuardBanner
+ I={ProjectPermissionActions.Read}
+ a={ProjectPermissionSub.PkiAlerts}
+ >
+ <AlertsTab />
+ </ProjectPermissionCan>
+ </TabsContent>
</Tabs>
</div>
</div>
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/AlertsTab.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/AlertsTab.tsx
new file mode 100644
index 0000000000..3c92a9efaf
--- /dev/null
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/AlertsTab.tsx
@@ -0,0 +1,39 @@
+import {
+ ProjectPermissionActions,
+ ProjectPermissionSub,
+ useProject,
+ useProjectPermission
+} from "@app/context";
+import { ProjectPermissionCertificateActions } from "@app/context/ProjectPermissionContext/types";
+
+import { ApplicationAlertsCard } from "../../ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard";
+import { CertificateAlertScopeKind } from "../../ApplicationDetailsByIDPage/components/ApplicationAlerts/types";
+
+export const AlertsTab = () => {
+ const { currentProject } = useProject();
+ const { permission } = useProjectPermission();
+
+ const certificateReadRules = permission.rulesFor(
+ ProjectPermissionCertificateActions.Read,
+ ProjectPermissionSub.Certificates
+ );
+ const canReadAllCertificates =
+ certificateReadRules.some((rule) => !rule.inverted && !rule.conditions) &&
+ !certificateReadRules.some((rule) => rule.inverted);
+
+ 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)
+ }
+ canDelete={permission.can(ProjectPermissionActions.Delete, ProjectPermissionSub.PkiAlerts)}
+ />
+ );
+};
diff --git a/frontend/src/pages/cert-manager/pki-docs-urls.ts b/frontend/src/pages/cert-manager/pki-docs-urls.ts
index 02ff293452..f76db1f843 100644
--- a/frontend/src/pages/cert-manager/pki-docs-urls.ts
+++ b/frontend/src/pages/cert-manager/pki-docs-urls.ts
@@ -31,6 +31,7 @@ export const PkiDocsUrls = {
policies: `${PKI_DOCS_BASE_URL}/settings/policies`,
profiles: `${PKI_DOCS_BASE_URL}/settings/profiles`,
certificateCleanup: `${PKI_DOCS_BASE_URL}/settings/certificate-cleanup`,
+ alerts: `${PKI_DOCS_BASE_URL}/settings/alerts`,
hsmConnectors: `${PKI_DOCS_BASE_URL}/settings/hsm-connectors`
},
diff --git a/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsx b/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsx
index 9154590bbc..9d7bbe512e 100644
--- a/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsx
+++ b/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsx
@@ -134,8 +134,8 @@ export const PkiAlertsV2Page = ({ hideContainer = false }: Props) => {
</span>
</div>
<p className="text-xs text-label-secondary">
- Legacy alerts can only be viewed or deleted. Create new alerts from the Alerting section
- of an application&apos;s Settings tab.
+ Legacy alerts can only be viewed or deleted. Create new alerts in an application&apos;s
+ Settings tab, or under Settings &gt; Alerts for all of Certificate Manager.
</p>
</div>