Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Add source filters to PKI alerts
Carlos Monastyrskibb2b6e8add0a
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 6f3a3b07d9..9439acf1fe 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -7941,6 +7941,7 @@ type TCertificateManagerAlertEventMetadata = {eventType: string;applications: { id: string; name: string | null }[];profiles: { id: string; name: string | null }[];+ sources: string[];};interface CreateCertificateManagerAlertEvent {diff --git a/backend/src/services/alert/providers/cert-manager-alert-fns.ts b/backend/src/services/alert/providers/cert-manager-alert-fns.tsindex 7ee98664a9..3167f124c1 100644--- a/backend/src/services/alert/providers/cert-manager-alert-fns.ts+++ b/backend/src/services/alert/providers/cert-manager-alert-fns.ts@@ -6,6 +6,7 @@ import { Event as TAuditEvent, EventType } from "@app/ee/services/audit-log/audiimport { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";+import { CertificateSource } from "@app/ee/services/pki-discovery/pki-discovery-types";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { TCertManagerProjectResolverFactory } from "@app/services/cert-manager-instance/cert-manager-project-resolver";import { getRevocationReasonLabel } from "@app/services/pki-alert-v2/pki-alert-v2-types";@@ -132,7 +133,11 @@ type TAlertFilterNames = { id: string; name: string | null }[];export const buildCertificateManagerAlertAuditEvent = (input: TAlertAuditInput,- { applications, profiles }: { applications: TAlertFilterNames; profiles: TAlertFilterNames }+ {+ applications,+ profiles,+ sources+ }: { applications: TAlertFilterNames; profiles: TAlertFilterNames; sources: CertificateSource[] }): TAuditEvent => {if (input.action === AlertAuditAction.TestChannel) {const { test } = input;@@ -152,7 +157,7 @@ export const buildCertificateManagerAlertAuditEvent = (}const { alert } = input;- const metadata = { alertId: alert.id, name: alert.name, eventType: alert.eventType, applications, profiles };+ const metadata = { alertId: alert.id, name: alert.name, eventType: alert.eventType, applications, profiles, sources };if (input.action === AlertAuditAction.Create) return { type: EventType.CREATE_CERTIFICATE_MANAGER_ALERT, metadata };if (input.action === AlertAuditAction.Update) return { type: EventType.UPDATE_CERTIFICATE_MANAGER_ALERT, metadata };return { type: EventType.DELETE_CERTIFICATE_MANAGER_ALERT, metadata };diff --git a/backend/src/services/alert/providers/cert-manager-alert-provider.test.ts b/backend/src/services/alert/providers/cert-manager-alert-provider.test.tsindex 80a81a7d59..d4635743e2 100644--- a/backend/src/services/alert/providers/cert-manager-alert-provider.test.ts+++ b/backend/src/services/alert/providers/cert-manager-alert-provider.test.ts@@ -180,6 +180,16 @@ describe("cert manager alert provider", () => {expect(schema.safeParse({ alertBefore: "30d", profileIds: [PROFILE_ID, PROFILE_ID] }).success).toBe(false);});+ test("the source filter takes issued, imported or discovered, each once", () => {+ const schema = expiryConditionSchema(buildProvider().provider);+ expect(schema.safeParse({ alertBefore: "30d", sources: ["imported", "discovered"] }).success).toBe(true);+ expect(schema.safeParse({ alertBefore: "30d", sources: ["issued"] }).success).toBe(true);+ expect(schema.safeParse({ alertBefore: "30d", sources: [] }).success).toBe(false);+ expect(schema.safeParse({ alertBefore: "30d", sources: ["external"] }).success).toBe(false);+ const duplicated = schema.safeParse({ alertBefore: "30d", sources: ["imported", "imported"] });+ expect(duplicated.error?.issues[0].message).toBe("sources lists the same source more than once");+ });+test("filter IDs match case-insensitively when checked and named", async () => {const { provider } = buildProvider();await expect(@@ -237,7 +247,7 @@ describe("cert manager alert provider", () => {projectId: "proj-1",resourceId: null,eventType: EXPIRY_EVENT,- condition: { alertBefore: "2w", profileIds: [PROFILE_ID] },+ condition: { alertBefore: "2w", profileIds: [PROFILE_ID], sources: ["imported"] },asOf: new Date(),alreadyAlerted: { alertId: "alert-1", channelIds: ["channel-1"], since: new Date() }});@@ -246,19 +256,21 @@ describe("cert manager alert provider", () => {projectId: "proj-1",resourceId: null,eventType: ISSUANCE_EVENT,- condition: { applicationIds: [APPLICATION_ID] },+ condition: { applicationIds: [APPLICATION_ID], sources: ["issued", "discovered"] },targetIds: ["cert-1"]} as never);expect(scheduledArgs).toMatchObject({projectId: "proj-1",profileIds: [PROFILE_ID],+ sources: ["imported"],alertBeforeInterval: "14 days"});expect(scheduledArgs?.applicationId).toBeUndefined();expect(eventArgs).toMatchObject({projectId: "proj-1",applicationIds: [APPLICATION_ID],+ sources: ["issued", "discovered"],certificateIds: ["cert-1"]});});@@ -385,7 +397,8 @@ describe("cert manager alert provider", () => {condition: {alertBefore: "30d",applicationIds: [APPLICATION_ID, OTHER_APPLICATION_ID],- profileIds: [PROFILE_ID]+ profileIds: [PROFILE_ID],+ sources: ["imported"]},filters: {applications: [{ id: APPLICATION_ID, name: "payments-api" }],@@ -400,7 +413,8 @@ describe("cert manager alert provider", () => {{ id: APPLICATION_ID, name: "payments-api" },{ id: OTHER_APPLICATION_ID, name: null }],- profiles: [{ id: PROFILE_ID, name: "tls-server" }]+ profiles: [{ id: PROFILE_ID, name: "tls-server" }],+ sources: ["imported"]};expect(provider.getAuditEvent?.({ action: AlertAuditAction.Create, alert })).toEqual({diff --git a/backend/src/services/alert/providers/cert-manager-alert-provider.ts b/backend/src/services/alert/providers/cert-manager-alert-provider.tsindex 1fd9958373..4168a19c96 100644--- a/backend/src/services/alert/providers/cert-manager-alert-provider.ts+++ b/backend/src/services/alert/providers/cert-manager-alert-provider.ts@@ -8,6 +8,7 @@ import {ProjectPermissionSet,ProjectPermissionSub} from "@app/ee/services/permission/project-permission";+import { CertificateSource } from "@app/ee/services/pki-discovery/pki-discovery-types";import { getConfig } from "@app/lib/config/env";import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { TCertManagerProjectResolverFactory } from "@app/services/cert-manager-instance/cert-manager-project-resolver";@@ -92,7 +93,12 @@ const filterIdsSchema = (field: string, noun: string) =>const CertificateFilterSchema = z.object({applicationIds: filterIdsSchema("applicationIds", "application"),- profileIds: filterIdsSchema("profileIds", "profile")+ profileIds: filterIdsSchema("profileIds", "profile"),+ sources: z+ .array(z.nativeEnum(CertificateSource))+ .min(1, "sources must list at least one source. Omit it to cover every source.")+ .refine((sources) => new Set(sources).size === sources.length, "sources lists the same source more than once")+ .optional()});const ExpirationConditionSchema = ExpiryFieldsSchema.merge(CertificateFilterSchema).strict();@@ -138,12 +144,13 @@ export const certManagerAlertProviderFactory = ({const findScheduledTargets = async (input: TFindScheduledTargetsInput): Promise<TApplicationAlertCertificate[]> => {if (!input.projectId || input.resourceId || !input.alreadyAlerted?.channelIds.length) return [];- const { alertBefore, applicationIds, profileIds } = ExpirationConditionSchema.parse(input.condition);+ const { alertBefore, applicationIds, profileIds, sources } = ExpirationConditionSchema.parse(input.condition);return certManagerApplicationAlertDAL.findExpiringCertificates({projectId: input.projectId,applicationIds,profileIds,+ sources,alertBeforeInterval: `${durationToDays(alertBefore)} days`,leadInterval: ALERT_SCAN_LEAD_INTERVAL,asOf: input.asOf,@@ -159,6 +166,7 @@ export const certManagerAlertProviderFactory = ({projectId: input.projectId,applicationIds: condition?.applicationIds,profileIds: condition?.profileIds,+ sources: condition?.sources,certificateIds: input.targetIds});};@@ -176,9 +184,9 @@ export const certManagerAlertProviderFactory = ({const getAuditEvent = (input: TAlertAuditInput) => {if (input.action === AlertAuditAction.TestChannel) {- return buildCertificateManagerAlertAuditEvent(input, { applications: [], profiles: [] });+ return buildCertificateManagerAlertAuditEvent(input, { applications: [], profiles: [], sources: [] });}- const { applicationIds = [], profileIds = [] } = parseFilters(input.alert.condition);+ const { applicationIds = [], profileIds = [], sources = [] } = parseFilters(input.alert.condition);const nameById = new Map(Object.values(input.alert.filters ?? {}).flat()@@ -187,7 +195,8 @@ export const certManagerAlertProviderFactory = ({const withNames = (ids: string[]) => ids.map((id) => ({ id, name: nameById.get(id) ?? null }));return buildCertificateManagerAlertAuditEvent(input, {applications: withNames(applicationIds),- profiles: withNames(profileIds)+ profiles: withNames(profileIds),+ sources});};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.tsindex 29df8d0879..aa694fe0ce 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@@ -1,6 +1,7 @@import knex, { Knex } from "knex";import { TDbClient } from "@app/db";+import { CertificateSource } from "@app/ee/services/pki-discovery/pki-discovery-types";import { certManagerApplicationAlertDALFactory } from "./cert-manager-application-alert-dal";@@ -164,6 +165,26 @@ describe("cert manager certificate alert DAL", () => {expect(queries[0].sql).toContain('"certificates"."id" in (?)');});+ test("the source filter matches the listed sources, and issued also matches certificates with no source", async () => {+ const { dal, queries } = buildDAL();++ await dal.findCertificatesByIds({+ projectId: PROJECT_ID,+ sources: [CertificateSource.Imported],+ certificateIds: ["c"]+ });+ await dal.findCertificatesByIds({+ projectId: PROJECT_ID,+ sources: [CertificateSource.Issued, CertificateSource.Discovered],+ certificateIds: ["c"]+ });++ expect(queries[0].sql).toContain('("certificates"."source" in (?))');+ expect(queries[0].sql).not.toContain('"certificates"."source" is null');+ expect(queries[0].bindings).toEqual(expect.arrayContaining(["imported"]));+ expect(queries[1].sql).toContain('("certificates"."source" in (?, ?) or "certificates"."source" is null)');+ });+test("application and profile id checks are scoped to the project", async () => {const { dal, queries } = buildDAL();diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts b/backend/src/services/alert/providers/cert-manager-application-alert-dal.tsindex 69a5657aab..9d8c6a5563 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@@ -2,6 +2,7 @@ import { Knex } from "knex";import { TDbClient } from "@app/db";import { TableName } from "@app/db/schemas";+import { CertificateSource } from "@app/ee/services/pki-discovery/pki-discovery-types";import { DatabaseError } from "@app/lib/errors";import { AlertRunStatus, TAlreadyAlertedFilter } from "@app/services/alert/alert-types";import { CertStatus } from "@app/services/certificate/certificate-types";@@ -36,6 +37,7 @@ type TCertificateScope = {applicationId?: string | null;applicationIds?: string[];profileIds?: string[];+ sources?: CertificateSource[];};const MAX_EXPIRING_CERTIFICATES_PER_RUN = 1000;@@ -43,7 +45,7 @@ const MAX_EXPIRING_CERTIFICATES_PER_RUN = 1000;export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {const $selectCertificates = (reader: Knex,- { projectId, applicationId, applicationIds, profileIds }: TCertificateScope+ { projectId, applicationId, applicationIds, profileIds, sources }: TCertificateScope) =>reader(TableName.Certificate).leftJoin(`${TableName.PkiCertificateProfile} as profile`, `${TableName.Certificate}.profileId`, "profile.id")@@ -53,6 +55,12 @@ export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {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);+ if (sources?.length) {+ void query.where((qb) => {+ void qb.whereIn(`${TableName.Certificate}.source`, sources);+ if (sources.includes(CertificateSource.Issued)) void qb.orWhereNull(`${TableName.Certificate}.source`);+ });+ }}).select(`${TableName.Certificate}.id`,diff --git a/backend/src/services/alert/providers/cert-manager-signer-alert-provider.test.ts b/backend/src/services/alert/providers/cert-manager-signer-alert-provider.test.tsindex 473515e53f..4666f2c6e3 100644--- a/backend/src/services/alert/providers/cert-manager-signer-alert-provider.test.ts+++ b/backend/src/services/alert/providers/cert-manager-signer-alert-provider.test.ts@@ -200,7 +200,14 @@ describe("cert manager signer alert provider", () => {expect(provider.getAuditEvent?.({ action: AlertAuditAction.Create, alert })).toEqual({type: EventType.CREATE_CERTIFICATE_MANAGER_ALERT,- metadata: { alertId: "alert-1", name: "signer-expiry", eventType: EXPIRY_EVENT, applications: [], profiles: [] }+ metadata: {+ alertId: "alert-1",+ name: "signer-expiry",+ eventType: EXPIRY_EVENT,+ applications: [],+ profiles: [],+ sources: []+ }});expect(provider.getTelemetryEvent?.({diff --git a/backend/src/services/alert/providers/cert-manager-signer-alert-provider.ts b/backend/src/services/alert/providers/cert-manager-signer-alert-provider.tsindex 14298cb817..c40505c9cd 100644--- a/backend/src/services/alert/providers/cert-manager-signer-alert-provider.ts+++ b/backend/src/services/alert/providers/cert-manager-signer-alert-provider.ts@@ -174,7 +174,8 @@ export const certManagerSignerAlertProviderFactory = ({assertChannelTypesAllowed: (input) => assertCertManagerAlertChannelTypesAllowed(licenseService, input),recipientPolicy: { atOrgScope: true, allowEmailAddresses: true },includeLastRun: true,- getAuditEvent: (input) => buildCertificateManagerAlertAuditEvent(input, { applications: [], profiles: [] }),+ getAuditEvent: (input) =>+ buildCertificateManagerAlertAuditEvent(input, { applications: [], profiles: [], sources: [] }),getWebhookSource,getTelemetryEvent,resolveProjectId: async ({ orgId, resourceId }) => {diff --git a/docs/documentation/platform/pki/settings/alerts.mdx b/docs/documentation/platform/pki/settings/alerts.mdxindex b24bb1316b..968d95500f 100644--- a/docs/documentation/platform/pki/settings/alerts.mdx+++ b/docs/documentation/platform/pki/settings/alerts.mdx@@ -29,7 +29,7 @@ Certificate Manager alerts use the same events and [notification channels](/docuSelect the **Alert Type** from the **Certificate Lifecycle** or **Code Signing** group, then enter an **Alert Name** and an optional **Description**. For an expiration alert, enter **Alert Before** as a number and a unit, for example `30d` or `2w`, up to 365 days. Turn on **Repeat daily until expiry** to get a reminder every day. See [how often expiration alerts repeat](/documentation/platform/pki/applications/alerting/overview#faq). Select **Continue**.</Step><Step>- On the **Filters** step, optionally select **Add Filter** to narrow the alert by **Applications** or **Certificate Profiles**. See [which certificates an alert covers](#which-certificates-an-alert-covers). **Matched Certificates** lists the active certificates the alert covers. The list updates as you change filters. Select **Continue**.+ On the **Filters** step, optionally select **Add Filter** to narrow the alert by **Applications**, **Certificate Profiles**, or **Source**. See [which certificates an alert covers](#which-certificates-an-alert-covers). **Matched Certificates** lists the active certificates the alert covers. The list updates as you change filters. Select **Continue**.</Step><Step>Select **Add Channel** and choose where to send notifications. You can add up to 10 channels. Select **Continue**.@@ -41,14 +41,15 @@ Certificate Manager alerts use the same events and [notification channels](/docu## 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:+If you don't add a filter, the alert covers every certificate in Certificate Manager. Each filter you add narrows the alert, and a certificate must match every filter:-| 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 |+| Filter | Certificates covered |+|--------|----------------------|+| **Applications** | Certificates in one of the selected applications |+| **Certificate Profiles** | Certificates issued from one of the selected profiles |+| **Source** | Certificates with one of the selected sources: **Managed** for certificates issued through Certificate Manager, **Imported**, or **Discovered** |++For example, a **Source** filter set to **Imported** covers every imported certificate, including ones outside any application or profile. Add an **Applications** filter as well, and the alert covers only the imported certificates in those applications.You can select up to 100 applications and 100 profiles.diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.tsindex a223f73e62..b8b1eefa80 100644--- a/frontend/src/hooks/api/alerts/types.ts+++ b/frontend/src/hooks/api/alerts/types.ts@@ -1,5 +1,7 @@import { z } from "zod";+import { CertSource } from "@app/hooks/api/certificates/enums";+export enum AlertResourceType {IdentityAuthentication = "identity.authentication"}@@ -105,6 +107,7 @@ export type TAlert = {dailyReminder?: boolean;applicationIds?: string[];profileIds?: string[];+ sources?: CertSource[];} | null;enabled: boolean;orgId: string;diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsxindex 81ac9f7bd5..32eab3c6db 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ApplicationAlertsCard.tsx@@ -97,6 +97,7 @@ const SCOPE_CARD_CONFIG: Record<const AlertFiltersSummary = ({ alert }: { alert: TAlert }) => {const applicationIds = alert.condition?.applicationIds ?? [];const profileIds = alert.condition?.profileIds ?? [];+ const sources = alert.condition?.sources ?? [];const conditionNames = toConditionNames(alert);const namesOf = (kind: CertificateFilterKind, ids: string[]) =>ids.map((id) => getFilterName(kind, id, conditionNames)).join(", ");@@ -105,13 +106,14 @@ const AlertFiltersSummary = ({ alert }: { alert: TAlert }) => {return <span className="text-muted">All signers</span>;}- if (!applicationIds.length && !profileIds.length) {+ if (!applicationIds.length && !profileIds.length && !sources.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+ profileIds.length ? pluralize(profileIds.length, "certificate profile") : null,+ sources.length ? pluralize(sources.length, "source") : null].filter(Boolean).join(", ");@@ -138,6 +140,14 @@ const AlertFiltersSummary = ({ alert }: { alert: TAlert }) => {{namesOf(CertificateFilterKind.Profiles, profileIds)}</span>)}+ {sources.length > 0 && (+ <span>+ <span className="text-muted">+ {CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Sources].label}:{" "}+ </span>+ {namesOf(CertificateFilterKind.Sources, sources)}+ </span>+ )}</TooltipContent></Tooltip>);diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateFilterSelects.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateFilterSelects.tsxindex 7a6a72d5d9..63b02b7b06 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateFilterSelects.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateFilterSelects.tsx@@ -4,6 +4,7 @@ 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 { CertSource } from "@app/hooks/api/certificates/enums";import { useListPkiApplications } from "@app/hooks/api/pkiApplications";import { CertificateFilterKind, getFilterName } from "./types";@@ -103,3 +104,19 @@ export const ProfileFilterSelect = (props: Props) => {/>);};++const SOURCE_OPTIONS = Object.values(CertSource).map((source) => ({+ id: source,+ name: getFilterName(CertificateFilterKind.Sources, source, {})+}));++export const SourceFilterSelect = (props: Props) => (+ <FilterCombobox+ {...props}+ kind={CertificateFilterKind.Sources}+ options={SOURCE_OPTIONS}+ isLoading={false}+ onSearchChange={() => {}}+ placeholder="Select sources"+ />+);diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/FiltersStep.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/FiltersStep.tsxindex 6ebd473d60..3303d08ed1 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/FiltersStep.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/FiltersStep.tsx@@ -22,7 +22,11 @@ import {import { useListWorkspaceCertificates } from "@app/hooks/api";import { CertStatus } from "@app/hooks/api/certificates/enums";-import { ApplicationFilterSelect, ProfileFilterSelect } from "./CertificateFilterSelects";+import {+ ApplicationFilterSelect,+ ProfileFilterSelect,+ SourceFilterSelect+} from "./CertificateFilterSelects";import {CERTIFICATE_FILTER_DEFINITIONS,CertificateFilterKind,@@ -34,6 +38,12 @@ const MATCHED_PAGE_SIZE = 20;const FILTER_KINDS = Object.values(CertificateFilterKind);+const FILTER_SELECTS = {+ [CertificateFilterKind.Applications]: ApplicationFilterSelect,+ [CertificateFilterKind.Profiles]: ProfileFilterSelect,+ [CertificateFilterKind.Sources]: SourceFilterSelect+};+type Props = { form: UseFormReturn<TCertificateAlertForm>; projectId: string };export const FiltersStep = ({ form, projectId }: Props) => {@@ -42,12 +52,14 @@ export const FiltersStep = ({ form, projectId }: Props) => {name: CertificateFilterKind.Applications});const profileIds = useWatch({ control: form.control, name: CertificateFilterKind.Profiles });+ const sources = useWatch({ control: form.control, name: CertificateFilterKind.Sources });const conditionNames = useWatch({ control: form.control, name: "conditionNames" });- const filters = { applicationIds, profileIds };+ const filters = { applicationIds, profileIds, sources };const previewFilters = {applicationIds: applicationIds?.length ? applicationIds : undefined,- profileIds: profileIds?.length ? profileIds : undefined+ profileIds: profileIds?.length ? profileIds : undefined,+ sources: sources?.length ? sources : undefined};const previewKey = JSON.stringify(previewFilters);const [page, setPage] = useState(1);@@ -67,11 +79,15 @@ export const FiltersStep = ({ form, projectId }: Props) => {limit: MATCHED_PAGE_SIZE,status: CertStatus.ACTIVE,applicationIds: previewFilters.applicationIds,- profileIds: previewFilters.profileIds+ profileIds: previewFilters.profileIds,+ source: previewFilters.sources});const setFilter = (kind: CertificateFilterKind, ids: string[] | undefined) =>- form.setValue(kind, ids, { shouldDirty: true, shouldValidate: true });+ form.setValue(kind, ids as TCertificateAlertForm[typeof kind], {+ shouldDirty: true,+ shouldValidate: true+ });const addFilter = (kind: CertificateFilterKind) => form.setValue(kind, [], { shouldDirty: true });const presentKinds = FILTER_KINDS.filter((kind) => filters[kind] !== undefined);@@ -124,10 +140,7 @@ export const FiltersStep = ({ form, projectId }: Props) => {{presentKinds.length > 0 ? (<div className="mt-3 flex flex-col gap-3">{presentKinds.map((kind, index) => {- const Select =- kind === CertificateFilterKind.Applications- ? ApplicationFilterSelect- : ProfileFilterSelect;+ const Select = FILTER_SELECTS[kind];const { label } = CERTIFICATE_FILTER_DEFINITIONS[kind];return (<Fragment key={kind}>@@ -146,10 +159,12 @@ export const FiltersStep = ({ form, projectId }: Props) => {value={filters[kind] ?? []}conditionNames={conditionNames}onChange={(selected) => {- form.setValue("conditionNames", {- ...conditionNames,- ...Object.fromEntries(selected.map(({ id, name }) => [id, name]))- });+ if (kind !== CertificateFilterKind.Sources) {+ form.setValue("conditionNames", {+ ...conditionNames,+ ...Object.fromEntries(selected.map(({ id, name }) => [id, name]))+ });+ }setFilter(kind,selected.map(({ id }) => id)diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsxindex 42b7eea1c2..f032b1fac4 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/ReviewStep.tsx@@ -75,10 +75,12 @@ const describeChannel = (channel: TChannelForm, members: TMemberEmails): stringconst FilterDetails = ({applicationIds,profileIds,+ sources,conditionNames}: {applicationIds: string[];profileIds: string[];+ sources: string[];conditionNames: Record<string, string>;}) => {const getApplicationName = (id: string) =>@@ -102,6 +104,17 @@ const FilterDetails = ({CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Profiles].allLabel)}</Detail>+ <Detail label={CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Sources].label}>+ {sources.length ? (+ <PkiSyncFilterValueBadges+ values={sources.map((source) =>+ getFilterName(CertificateFilterKind.Sources, source, conditionNames)+ )}+ />+ ) : (+ CERTIFICATE_FILTER_DEFINITIONS[CertificateFilterKind.Sources].allLabel+ )}+ </Detail></>);};@@ -134,11 +147,14 @@ export const ReviewStep = ({ form, scope, members }: Props) => {{scope.kind === CertificateAlertScopeKind.CertificateManager &&isFilterableEventType(values.eventType) && (<Section title="Certificate Filters">- {values.applicationIds?.length || values.profileIds?.length ? (+ {values.applicationIds?.length ||+ values.profileIds?.length ||+ values.sources?.length ? (<div className="grid grid-cols-2 gap-x-6 gap-y-4"><FilterDetailsapplicationIds={values.applicationIds ?? []}profileIds={values.profileIds ?? []}+ sources={values.sources ?? []}conditionNames={values.conditionNames}/></div>diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.tsindex 99cafe7a08..b45adb5105 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/types.ts@@ -12,6 +12,8 @@ import {TAlertChannelRecipient,TChannelForm} from "@app/hooks/api/alerts";+import { CertSource } from "@app/hooks/api/certificates/enums";+import { getCertSourceLabel } from "@app/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils";export enum CertificateAlertScopeKind {Application = "application",@@ -190,7 +192,8 @@ export const toRecipientEmails = (export enum CertificateFilterKind {Applications = "applicationIds",- Profiles = "profileIds"+ Profiles = "profileIds",+ Sources = "sources"}export const CERTIFICATE_FILTER_DEFINITIONS: Record<@@ -208,6 +211,12 @@ export const CERTIFICATE_FILTER_DEFINITIONS: Record<hint: "Issued from one of these profiles",allLabel: "All certificate profiles",unknownLabel: "Unknown profile"+ },+ [CertificateFilterKind.Sources]: {+ label: "Source",+ hint: "Managed, imported, or discovered certificates",+ allLabel: "All sources",+ unknownLabel: "Unknown source"}};@@ -217,7 +226,10 @@ export const getFilterName = (kind: CertificateFilterKind,id: string,conditionNames: Record<string, string>-) => conditionNames[id] ?? CERTIFICATE_FILTER_DEFINITIONS[kind].unknownLabel;+) =>+ kind === CertificateFilterKind.Sources+ ? getCertSourceLabel(id as CertSource)+ : (conditionNames[id] ?? CERTIFICATE_FILTER_DEFINITIONS[kind].unknownLabel);export const toConditionNames = (alert: TAlert): Record<string, string> =>Object.fromEntries(@@ -230,7 +242,8 @@ const isUnfinishedFilter = (ids?: string[]) => ids?.length === 0;const UNFINISHED_FILTER_MESSAGES: Record<CertificateFilterKind, string> = {[CertificateFilterKind.Applications]: "Select at least one application, or remove this filter",- [CertificateFilterKind.Profiles]: "Select at least one profile, or remove this filter"+ [CertificateFilterKind.Profiles]: "Select at least one profile, or remove this filter",+ [CertificateFilterKind.Sources]: "Select at least one source, or remove this filter"};export enum CertificateAlertStep {@@ -300,6 +313,7 @@ export const certificateAlertFormSchema = z`Select up to ${MAX_CERTIFICATE_ALERT_FILTER_IDS} profiles`).optional(),+ sources: z.array(z.nativeEnum(CertSource)).optional(),conditionNames: z.record(z.string()),channels: z.array(channelFormSchema).min(1, "Add at least one channel").max(MAX_CHANNELS)})@@ -365,6 +379,7 @@ export const toCertificateAlertForm = (enabled: alert.enabled,applicationIds: alert.condition?.applicationIds,profileIds: alert.condition?.profileIds,+ sources: alert.condition?.sources,conditionNames: toConditionNames(alert),channels: alert.channels.map((channel): TChannelForm => ({@@ -395,7 +410,8 @@ export const toCondition = (scope: TCertificateAlertScope, form: TCertificateAleisFilterableEventType(form.eventType)? {...(form.applicationIds?.length ? { applicationIds: form.applicationIds } : {}),- ...(form.profileIds?.length ? { profileIds: form.profileIds } : {})+ ...(form.profileIds?.length ? { profileIds: form.profileIds } : {}),+ ...(form.sources?.length ? { sources: form.sources } : {})}: {};