Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Address PR comments
Carlos Monastyrski4075f50a2be9
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex b5858337ba..e70cab1c89 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4277,5 +4277,7 @@ export const PKI_SYNC_FILTERS = {metadataKey: "Metadata key the certificate must carry.",metadataValue: "Metadata value the key must have. Omit it to match any value.",previewPkiSyncId: "Preview the filters against this existing PKI Sync.",- previewApplicationId: "Preview the filters against this Application, for a PKI Sync that does not exist yet."+ previewApplicationId: "Preview the filters against this Application, for a PKI Sync that does not exist yet.",+ previewOffset: "The offset to start from. If you enter 10, it will start from the 10th matching certificate.",+ previewLimit: "The number of matching certificates to return."};diff --git a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.tsindex 960549db6c..102b79a68d 100644--- a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts@@ -294,20 +294,22 @@ export const registerPkiSyncRouter = async (server: FastifyZodProvider, enableOpserver.route({method: "POST",- url: "/certificates/preview",+ url: "/certificates/search",config: {rateLimit: readLimit},schema: {hide: false,- ...(enableOperationId ? { operationId: "previewPkiSyncFilters" } : {}),+ ...(enableOperationId ? { operationId: "searchPkiSyncFilterCertificates" } : {}),tags: [ApiDocsTags.PkiSyncs],- description: "Preview the certificates a set of filters matches, for an existing PKI Sync or an Application.",+ description: "List the certificates a set of filters matches, for an existing PKI Sync or an Application.",body: z.object({pkiSyncId: z.string().uuid().optional().describe(PKI_SYNC_FILTERS.previewPkiSyncId),applicationId: z.string().uuid().optional().describe(PKI_SYNC_FILTERS.previewApplicationId),- filters: PkiSyncFiltersField+ filters: PkiSyncFiltersField,+ offset: z.coerce.number().min(0).default(0).describe(PKI_SYNC_FILTERS.previewOffset),+ limit: z.coerce.number().min(1).max(500).default(100).describe(PKI_SYNC_FILTERS.previewLimit)}).refine((body) => Boolean(body.pkiSyncId) !== Boolean(body.applicationId), {message: "Provide either pkiSyncId or applicationId."@@ -315,7 +317,6 @@ export const registerPkiSyncRouter = async (server: FastifyZodProvider, enableOpresponse: {200: z.object({matchedCount: z.number(),- hasMoreMatches: z.boolean(),certificates: PkiSyncCertificateRefSchema.array(),toUnlink: PkiSyncCertificateRefSchema.array(),willRemoveFromDestination: z.boolean()@@ -325,7 +326,13 @@ export const registerPkiSyncRouter = async (server: FastifyZodProvider, enableOponRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),handler: async (req) => {const preview = await server.services.pkiSync.previewPkiSyncFilters(- { pkiSyncId: req.body.pkiSyncId, applicationId: req.body.applicationId, filters: req.body.filters },+ {+ pkiSyncId: req.body.pkiSyncId,+ applicationId: req.body.applicationId,+ filters: req.body.filters,+ offset: req.body.offset,+ limit: req.body.limit+ },req.permission);@@ -333,6 +340,51 @@ export const registerPkiSyncRouter = async (server: FastifyZodProvider, enableOp}});+ server.route({+ method: "POST",+ url: "/certificate-orders/search",+ config: {+ rateLimit: readLimit+ },+ schema: {+ hide: false,+ ...(enableOperationId ? { operationId: "searchPkiSyncCertificateOrders" } : {}),+ tags: [ApiDocsTags.PkiSyncs],+ description: "Resolve certificate orders to the certificate each one currently holds.",+ body: z+ .object({+ pkiSyncId: z.string().uuid().optional().describe(PKI_SYNC_FILTERS.previewPkiSyncId),+ applicationId: z.string().uuid().optional().describe(PKI_SYNC_FILTERS.previewApplicationId),+ certificateOrderIds: z.string().uuid().array().max(200).describe(PKI_SYNC_FILTERS.certificateOrderIds)+ })+ .refine((body) => Boolean(body.pkiSyncId) !== Boolean(body.applicationId), {+ message: "Provide either pkiSyncId or applicationId."+ }),+ response: {+ 200: z.object({+ orders: z+ .object({+ certificateOrderId: z.string().uuid(),+ commonName: z.string(),+ altNames: z.string().nullish()+ })+ .array()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ return server.services.pkiSync.searchPkiSyncCertificateOrders(+ {+ pkiSyncId: req.body.pkiSyncId,+ applicationId: req.body.applicationId,+ certificateOrderIds: req.body.certificateOrderIds+ },+ req.permission+ );+ }+ });+server.route({method: "POST",url: "/:pkiSyncId/certificates",diff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.tsindex a0c1f7b2e7..1fdad857ab 100644--- a/backend/src/services/certificate/certificate-dal.ts+++ b/backend/src/services/certificate/certificate-dal.ts@@ -517,64 +517,150 @@ export const certificateDALFactory = (db: TDbClient) => {}};- const findCertificatesMatchingSyncFilters = async (+ const $buildSyncFilterMatchQuery = (filters: TPkiSyncMatchFilters | null | undefined,scope: { projectId: string; applicationId: string; certificateId?: string },- options?: { limit?: number }- ): Promise<TMatchedSyncCertificate[]> => {+ permissionFilters?: ProcessedPermissionRules+ ) => {+ let query = db(TableName.Certificate)+ .leftJoin(+ TableName.PkiCertificateProfile,+ `${TableName.Certificate}.profileId`,+ `${TableName.PkiCertificateProfile}.id`+ )+ .where(`${TableName.Certificate}.projectId`, scope.projectId)+ .andWhere(`${TableName.Certificate}.applicationId`, scope.applicationId);++ query = $applyActiveForSyncEligibility(query) as typeof query;++ if (scope.certificateId) {+ query = query.andWhere(`${TableName.Certificate}.id`, scope.certificateId);+ }++ if (filters?.certificateOrderIds) {+ query = query.whereIn(`${TableName.Certificate}.orderId`, filters.certificateOrderIds);+ }++ if (filters?.profileIds) {+ query = query.whereIn(`${TableName.Certificate}.profileId`, filters.profileIds);+ }++ if (filters?.metadata) {+ query = filters.metadata.length+ ? applyMetadataFilter(query, filters.metadata, "certificateId", TableName.Certificate)+ : query.whereRaw("1 = 0");+ }++ if (permissionFilters) {+ query = applyProcessedPermissionRulesToQuery(query, TableName.Certificate, permissionFilters) as typeof query;+ }++ return query;+ };++ const countCertificatesMatchingSyncFilters = async (+ filters: TPkiSyncMatchFilters | null | undefined,+ scope: { projectId: string; applicationId: string },+ permissionFilters?: ProcessedPermissionRules+ ): Promise<number> => {try {- let query = db(TableName.Certificate)- .distinctOn(`${TableName.Certificate}.orderId`)- .leftJoin(- TableName.PkiCertificateProfile,- `${TableName.Certificate}.profileId`,- `${TableName.PkiCertificateProfile}.id`- )- .where(`${TableName.Certificate}.projectId`, scope.projectId)- .andWhere(`${TableName.Certificate}.applicationId`, scope.applicationId);+ const result = (await $buildSyncFilterMatchQuery(filters, scope, permissionFilters).count(+ `${TableName.Certificate}.id as count`+ )) as unknown as Array<{ count: string }>;- query = $applyActiveForSyncEligibility(query) as typeof query;+ return Number(result?.[0]?.count ?? 0);+ } catch (error) {+ throw new DatabaseError({ error, name: "Count certificates matching sync filters" });+ }+ };- if (scope.certificateId) {- query = query.andWhere(`${TableName.Certificate}.id`, scope.certificateId);- }+ const findReadableCertificateIds = async (+ certificateIds: string[],+ projectId: string,+ permissionFilters?: ProcessedPermissionRules+ ): Promise<string[]> => {+ try {+ if (certificateIds.length === 0) return [];- if (filters?.certificateOrderIds) {- query = query.whereIn(`${TableName.Certificate}.orderId`, filters.certificateOrderIds);+ let query = db(TableName.Certificate)+ .where(`${TableName.Certificate}.projectId`, projectId)+ .whereIn(`${TableName.Certificate}.id`, certificateIds);++ if (permissionFilters) {+ query = applyProcessedPermissionRulesToQuery(query, TableName.Certificate, permissionFilters) as typeof query;}- if (filters?.profileIds) {- query = query.whereIn(`${TableName.Certificate}.profileId`, filters.profileIds);+ const rows = (await query.select(`${TableName.Certificate}.id`)) as { id: string }[];++ return rows.map((row) => row.id);+ } catch (error) {+ throw new DatabaseError({ error, name: "Find readable certificates by IDs" });+ }+ };++ const findLatestCertificatesByOrderIds = async (+ orderIds: string[],+ scope: { projectId: string; applicationId: string },+ permissionFilters?: ProcessedPermissionRules+ ): Promise<{ orderId: string; commonName: string; altNames: string | null }[]> => {+ try {+ if (orderIds.length === 0) return [];++ let query = db+ .replicaNode()(TableName.Certificate)+ .where(`${TableName.Certificate}.projectId`, scope.projectId)+ .andWhere(`${TableName.Certificate}.applicationId`, scope.applicationId)+ .whereIn(`${TableName.Certificate}.orderId`, orderIds);++ if (permissionFilters) {+ query = applyProcessedPermissionRulesToQuery(query, TableName.Certificate, permissionFilters) as typeof query;}- if (filters?.metadata) {- query = filters.metadata.length- ? applyMetadataFilter(query, filters.metadata, "certificateId", TableName.Certificate)- : query.whereRaw("1 = 0");+ const rows = await query+ .distinctOn(`${TableName.Certificate}.orderId`)+ .orderBy([+ { column: `${TableName.Certificate}.orderId`, order: "asc" },+ { column: `${TableName.Certificate}.notBefore`, order: "desc" },+ { column: `${TableName.Certificate}.createdAt`, order: "desc" }+ ])+ .select(+ `${TableName.Certificate}.orderId`,+ `${TableName.Certificate}.commonName`,+ `${TableName.Certificate}.altNames`+ );++ return rows as { orderId: string; commonName: string; altNames: string | null }[];+ } catch (error) {+ throw new DatabaseError({ error, name: "Find latest certificates by order IDs" });+ }+ };++ const findCertificatesMatchingSyncFilters = async (+ filters: TPkiSyncMatchFilters | null | undefined,+ scope: { projectId: string; applicationId: string; certificateId?: string },+ options?: { offset?: number; limit?: number; permissionFilters?: ProcessedPermissionRules }+ ): Promise<TMatchedSyncCertificate[]> => {+ try {+ let query = $buildSyncFilterMatchQuery(filters, scope, options?.permissionFilters);++ if (options?.offset) {+ query = query.offset(options.offset);}if (options?.limit) {query = query.limit(options.limit);}- const certificates = (await query- .orderBy([- { column: `${TableName.Certificate}.orderId` },- { column: `${TableName.Certificate}.notBefore`, order: "desc" }- ])+ return (await query+ .orderBy(`${TableName.Certificate}.commonName`, "asc").select(`${TableName.Certificate}.id`,`${TableName.Certificate}.commonName`,- `${TableName.Certificate}.altNames`,`${TableName.Certificate}.serialNumber`,`${TableName.Certificate}.notAfter`,`${TableName.Certificate}.orderId`,db.ref("slug").withSchema(TableName.PkiCertificateProfile).as("profileName"))) as TMatchedSyncCertificate[];-- return certificates.sort((a, b) =>- (a.altNames?.trim() || a.commonName).localeCompare(b.altNames?.trim() || b.commonName)- );} catch (error) {throw new DatabaseError({ error, name: "Find certificates matching sync filters" });}@@ -1329,6 +1415,9 @@ export const certificateDALFactory = (db: TDbClient) => {findActiveCertificatesByIds,findActiveCertificatesForSync,findCertificatesMatchingSyncFilters,+ countCertificatesMatchingSyncFilters,+ findReadableCertificateIds,+ findLatestCertificatesByOrderIds,findCertificatesEligibleForRenewal,getRequestEnrollmentTypeByCertId,getOriginatingRequestByCertId,diff --git a/backend/src/services/pki-sync/pki-sync-filter-fns.ts b/backend/src/services/pki-sync/pki-sync-filter-fns.tsindex bf376e2a64..2b576d2ba5 100644--- a/backend/src/services/pki-sync/pki-sync-filter-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-filter-fns.ts@@ -1,6 +1,7 @@import { TPkiSyncFilters } from "./pki-sync-types";-export const PKI_SYNC_MAX_LINKED_CERTIFICATES = 500;+export const PKI_SYNC_PREVIEW_PAGE_SIZE = 500;+export const PKI_SYNC_MAX_FILTER_ORDERS = 10_000;export const PKI_SYNC_FILTER_KINDS = ["profileIds", "certificateOrderIds", "metadata"] as const;diff --git a/backend/src/services/pki-sync/pki-sync-fns.test.ts b/backend/src/services/pki-sync/pki-sync-fns.test.tsindex 7aa858e8dd..77f4940c56 100644--- a/backend/src/services/pki-sync/pki-sync-fns.test.ts+++ b/backend/src/services/pki-sync/pki-sync-fns.test.ts@@ -1,5 +1,5 @@import { PkiSync } from "./pki-sync-enums";-import { hasAnyPkiSyncFilter, PKI_SYNC_MAX_LINKED_CERTIFICATES } from "./pki-sync-filter-fns";+import { hasAnyPkiSyncFilter } from "./pki-sync-filter-fns";import {assertFiltersCannotExceedCertificateCap,assertPkiSyncCanHoldCertificateCount,@@ -158,31 +158,15 @@ describe("parsePkiSyncErrorMessage", () => {describe("assertPkiSyncCanHoldCertificateCount", () => {const multiCertSchema = { certificateNameSchema: "Infisical-{{certificateId}}" };- test("allows a count within both the global cap and the destination cap", () => {+ test("a destination with no cap accepts any number of certificates", () => {expect(() =>assertPkiSyncCanHoldCertificateCount(PkiSync.AwsCertificateManager, multiCertSchema, undefined, 499)).not.toThrow();expect(() =>- assertPkiSyncCanHoldCertificateCount(- PkiSync.AwsCertificateManager,- multiCertSchema,- undefined,- PKI_SYNC_MAX_LINKED_CERTIFICATES- )+ assertPkiSyncCanHoldCertificateCount(PkiSync.AwsCertificateManager, multiCertSchema, undefined, 25_000)).not.toThrow();});- test("rejects a count over the global cap", () => {- expect(() =>- assertPkiSyncCanHoldCertificateCount(- PkiSync.AwsCertificateManager,- multiCertSchema,- undefined,- PKI_SYNC_MAX_LINKED_CERTIFICATES + 1- )- ).toThrow("at most 500 certificates");- });-test("rejects more than one certificate on a single-certificate destination", () => {expect(() =>assertPkiSyncCanHoldCertificateCount(PkiSync.NutanixPrismCentral, multiCertSchema, undefined, 1)diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.tsindex 28a33e718c..f0f4c50cd4 100644--- a/backend/src/services/pki-sync/pki-sync-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-fns.ts@@ -54,12 +54,7 @@ import {} from "./pki-sync-certificate-name-fns";import { PkiSync } from "./pki-sync-enums";import { PkiSyncError } from "./pki-sync-errors";-import {- hasAnyPkiSyncFilter,- PKI_SYNC_FILTER_KINDS,- PKI_SYNC_MAX_LINKED_CERTIFICATES,- TPkiSyncFilterKind-} from "./pki-sync-filter-fns";+import { hasAnyPkiSyncFilter, PKI_SYNC_FILTER_KINDS, TPkiSyncFilterKind } from "./pki-sync-filter-fns";import { getHealthCheckCommand } from "./pki-sync-health-check-command-fns";import {findSingleCertificateHostCommandVariables,@@ -778,15 +773,7 @@ export const assertPkiSyncCanHoldCertificateCount = (syncOptions: Record<string, unknown> | undefined,destinationConfig: Record<string, unknown> | undefined,resultingCertificateCount: number-) => {- if (resultingCertificateCount > PKI_SYNC_MAX_LINKED_CERTIFICATES) {- throw new BadRequestError({- message: `A PKI sync holds at most ${PKI_SYNC_MAX_LINKED_CERTIFICATES} certificates`- });- }-- assertPkiSyncCertificateCapsAllowCount(destination, syncOptions, destinationConfig, resultingCertificateCount);-};+) => assertPkiSyncCertificateCapsAllowCount(destination, syncOptions, destinationConfig, resultingCertificateCount);const PKI_SYNC_FILTER_LABELS: Record<TPkiSyncFilterKind, string> = {profileIds: "certificate profile",diff --git a/backend/src/services/pki-sync/pki-sync-host-command-fns.ts b/backend/src/services/pki-sync/pki-sync-host-command-fns.tsindex 15a69a0768..b4f205031d 100644--- a/backend/src/services/pki-sync/pki-sync-host-command-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-host-command-fns.ts@@ -138,7 +138,7 @@ export const buildHostCommandContext = (args: {singleCertificateVariables)}. A variable that names one certificate cannot be resolved for a run that ${delivered} ${certificates.length- } certificates. Unlink all but one certificate, or use {{certificateFiles}} instead.`,+ } certificates. Narrow this sync's filters to one certificate, or use {{certificateFiles}} instead.`,shouldRetry: false});}diff --git a/backend/src/services/pki-sync/pki-sync-schemas.ts b/backend/src/services/pki-sync/pki-sync-schemas.tsindex 7ed487d1e5..5344da27d4 100644--- a/backend/src/services/pki-sync/pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/pki-sync-schemas.ts@@ -6,7 +6,7 @@ import { HOSTNAME_MAX_LENGTH, isValidHostname } from "@app/lib/validator/validatimport { buildCertificateNameSchemaTestName } from "./pki-sync-certificate-name-fns";import { PkiSync, PkiSyncStatus } from "./pki-sync-enums";-import { PKI_SYNC_MAX_LINKED_CERTIFICATES } from "./pki-sync-filter-fns";+import { PKI_SYNC_MAX_FILTER_ORDERS } from "./pki-sync-filter-fns";import { HOST_COMMAND_MAX_LENGTH } from "./pki-sync-host-command-fns";export const HostCommandSchema = z@@ -114,7 +114,7 @@ const PkiSyncFiltersSchema = z.string().uuid().array()- .max(PKI_SYNC_MAX_LINKED_CERTIFICATES)+ .max(PKI_SYNC_MAX_FILTER_ORDERS).optional().describe(PKI_SYNC_FILTERS.certificateOrderIds),metadata: zdiff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.tsindex 439ba97e78..1ddf3915cd 100644--- a/backend/src/services/pki-sync/pki-sync-service.ts+++ b/backend/src/services/pki-sync/pki-sync-service.ts@@ -5,8 +5,13 @@ import { ActionProjectType, ResourceType, TCertificateSyncs } from "@app/db/scheimport { AuditLogInfo, EventType, TAuditLogServiceFactory } 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 { ProjectPermissionPkiSyncActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import {+ ProjectPermissionCertificateActions,+ ProjectPermissionPkiSyncActions,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";+import {+ ResourcePermissionCertificateActions,ResourcePermissionPkiSyncActions,ResourcePermissionSub} from "@app/ee/services/permission/resource-permission";@@ -32,7 +37,7 @@ import { encryptPkiSyncCredentials } from "./pki-sync-credentials-fns";import { TPkiSyncDALFactory } from "./pki-sync-dal";import { HEALTH_CHECK_COMMAND_OPTION_KEY, PkiSync, PkiSyncStatus } from "./pki-sync-enums";import { PkiSyncExportFormat } from "./pki-sync-export-fns";-import { hasAnyPkiSyncFilter, PKI_SYNC_FILTER_KINDS, PKI_SYNC_MAX_LINKED_CERTIFICATES } from "./pki-sync-filter-fns";+import { hasAnyPkiSyncFilter, PKI_SYNC_FILTER_KINDS, PKI_SYNC_PREVIEW_PAGE_SIZE } from "./pki-sync-filter-fns";import {applyPkiSyncCertificateDiff,assertPkiSyncCanHoldMatchedCertificates,@@ -78,12 +83,14 @@ import {TListPkiSyncsByProjectId,TPkiSync,TPkiSyncCertificate,+ TPkiSyncCertificateOrder,TPkiSyncCertificateRef,TPkiSyncFilterPreview,TPkiSyncFilters,TPkiSyncRaw,TPreviewPkiSyncFiltersDTO,TRemoveCertificatesFromPkiSyncDTO,+ TSearchPkiSyncCertificateOrdersDTO,TSetCertificateAsDefaultDTO,TTriggerPkiSyncImportCertificatesByIdDTO,TTriggerPkiSyncRemoveCertificatesByIdDTO,@@ -102,7 +109,15 @@ type TPkiSyncServiceFactoryDep = {| "deleteById"| "primaryNode">;- certificateDAL: Pick<TCertificateDALFactory, "find" | "findCertificatesMatchingSyncFilters" | "primaryNode">;+ certificateDAL: Pick<+ TCertificateDALFactory,+ | "find"+ | "findCertificatesMatchingSyncFilters"+ | "countCertificatesMatchingSyncFilters"+ | "findReadableCertificateIds"+ | "findLatestCertificatesByOrderIds"+ | "primaryNode"+ >;pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory, "findByApplicationId">;certificateSyncDAL: Pick<TCertificateSyncDALFactory,@@ -377,6 +392,84 @@ export const pkiSyncServiceFactory = ({$assertHostCommandsAreSupported(destination, nextSyncOptions, await resolveConnection());};+ const $certificateReadFilters = async (projectId: string, applicationId: string, actor: OrgServiceActor) => {+ const { permission: resourcePermission } = await permissionService.getResourcePermission({+ actor: actor.type,+ actorId: actor.id,+ projectId,+ resourceType: ResourceType.CertificateApplication,+ resourceId: applicationId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId+ });++ if (resourcePermission.can(ResourcePermissionCertificateActions.Read, ResourcePermissionSub.Certificates)) {+ return undefined;+ }++ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorId: actor.id,+ projectId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,+ actionProjectType: ActionProjectType.CertificateManager+ });++ return getProcessedPermissionRules(+ permission,+ ProjectPermissionCertificateActions.Read,+ ProjectPermissionSub.Certificates+ );+ };++ const $assertActorCanReadFilterMatches = async (+ projectId: string,+ applicationId: string | null | undefined,+ filters: TPkiSyncFilters | null | undefined,+ actor: OrgServiceActor+ ) => {+ if (!applicationId || !hasAnyPkiSyncFilter(filters)) return;++ const permissionFilters = await $certificateReadFilters(projectId, applicationId, actor);+ if (!permissionFilters) return;++ const scope = { projectId, applicationId };+ const [matchedCount, readableCount] = await Promise.all([+ certificateDAL.countCertificatesMatchingSyncFilters(filters, scope),+ certificateDAL.countCertificatesMatchingSyncFilters(filters, scope, permissionFilters)+ ]);++ if (matchedCount !== readableCount) {+ throw new ForbiddenRequestError({+ message: `These filters match ${matchedCount - readableCount} certificate${+ matchedCount - readableCount === 1 ? "" : "s"+ } you do not have access to read. Narrow the filters to the certificates you can access.`+ });+ }+ };++ const $assertActorCanReadCertificates = async (+ certificateIds: string[],+ projectId: string,+ applicationId: string | null | undefined,+ actor: OrgServiceActor+ ) => {+ if (!applicationId || certificateIds.length === 0) return;++ const permissionFilters = await $certificateReadFilters(projectId, applicationId, actor);+ if (!permissionFilters) return;++ const readableIds = new Set(+ await certificateDAL.findReadableCertificateIds(certificateIds, projectId, permissionFilters)+ );+ const hiddenIds = certificateIds.filter((id) => !readableIds.has(id));++ if (hiddenIds.length > 0) {+ throw new NotFoundError({ message: `Certificates not found: ${hiddenIds.join(", ")}` });+ }+ };+const $findApplicationCertificates = async (certificateIds: string[],expectedProjectId: string,@@ -406,12 +499,16 @@ export const pkiSyncServiceFactory = ({certificateIds: string[],expectedProjectId: string,expectedApplicationId: string | null | undefined,- { requireSyncable }: { requireSyncable: boolean }+ { requireSyncable, actor }: { requireSyncable: boolean; actor?: OrgServiceActor }): Promise<string[]> => {if (certificateIds.length === 0) return [];const certificates = await $findApplicationCertificates(certificateIds, expectedProjectId, expectedApplicationId);+ if (actor) {+ await $assertActorCanReadCertificates(certificateIds, expectedProjectId, expectedApplicationId, actor);+ }+const orderIds = [...new Set(certificates.map((cert) => cert.orderId))];if (requireSyncable && expectedApplicationId) {@@ -437,12 +534,17 @@ export const pkiSyncServiceFactory = ({const validateCertificatesForSync = async (certificateIds: string[],expectedProjectId: string,- expectedApplicationId: string | null | undefined+ expectedApplicationId: string | null | undefined,+ actor?: OrgServiceActor) => {if (certificateIds.length === 0) return [];const certificates = await $findApplicationCertificates(certificateIds, expectedProjectId, expectedApplicationId);+ if (actor) {+ await $assertActorCanReadCertificates(certificateIds, expectedProjectId, expectedApplicationId, actor);+ }+const now = new Date();const ineligibleReasons = certificates.filter(@@ -590,11 +692,13 @@ export const pkiSyncServiceFactory = ({? filters: {certificateOrderIds: await $resolveCertificateOrderIds(certificateIds ?? [], projectId, applicationId, {- requireSyncable: true+ requireSyncable: true,+ actor})};await $assertFilterProfilesInApplication(resolvedFilters, applicationId);+ await $assertActorCanReadFilterMatches(projectId, applicationId, resolvedFilters, actor);assertFiltersCannotExceedCertificateCap(destination, resolvedSyncOptions, destinationConfig, resolvedFilters);if (hasAnyPkiSyncFilter(resolvedFilters)) {@@ -816,6 +920,7 @@ export const pkiSyncServiceFactory = ({const effectiveSyncOptions = (resolvedSyncOptions ?? pkiSync.syncOptions) as Record<string, unknown> | undefined;await $assertFilterProfilesInApplication(filters, pkiSync.applicationId);+ await $assertActorCanReadFilterMatches(pkiSync.projectId, pkiSync.applicationId, filters, actor);await $assertHostCommandWrite({destination: pkiSync.destination,@@ -1180,7 +1285,7 @@ export const pkiSyncServiceFactory = ({}if (args.certificateIds?.length) {- await validateCertificatesForSync(args.certificateIds, args.projectId, args.applicationId);+ await validateCertificatesForSync(args.certificateIds, args.projectId, args.applicationId, actor);}await $assertFilterProfilesInApplication(args.filters, args.applicationId);@@ -1328,8 +1433,73 @@ export const pkiSyncServiceFactory = ({return { message: "PKI sync remove job added to queue successfully" };};+ const searchPkiSyncCertificateOrders = async (+ { applicationId, pkiSyncId, certificateOrderIds }: TSearchPkiSyncCertificateOrdersDTO,+ actor: OrgServiceActor+ ): Promise<{ orders: TPkiSyncCertificateOrder[] }> => {+ let scope: { projectId: string; applicationId: string };++ if (pkiSyncId) {+ const pkiSync = await pkiSyncDAL.findById(pkiSyncId);+ if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });+ if (!pkiSync.applicationId) return { orders: [] };++ const allowedByResource = await $resourceFallback(+ ResourcePermissionPkiSyncActions.Read,+ pkiSync.projectId,+ pkiSync.applicationId,+ actor+ );+ if (!allowedByResource) {+ throw new ForbiddenRequestError({ message: "User has insufficient privileges" });+ }++ scope = { projectId: pkiSync.projectId, applicationId: pkiSync.applicationId };+ } else {+ if (!applicationId) {+ throw new BadRequestError({ message: "Provide either pkiSyncId or applicationId." });+ }++ const application = await pkiApplicationDAL.findById(applicationId);+ if (!application) throw new NotFoundError({ message: "Application not found" });++ const allowedByResource = await $resourceFallback(+ ResourcePermissionPkiSyncActions.Read,+ application.projectId,+ applicationId,+ actor+ );+ if (!allowedByResource) {+ throw new ForbiddenRequestError({ message: "User has insufficient privileges" });+ }++ scope = { projectId: application.projectId, applicationId };+ }++ const permissionFilters = await $certificateReadFilters(scope.projectId, scope.applicationId, actor);+ const certificates = await certificateDAL.findLatestCertificatesByOrderIds(+ certificateOrderIds,+ scope,+ permissionFilters+ );++ return {+ orders: certificates.map(({ orderId, commonName, altNames }) => ({+ certificateOrderId: orderId,+ commonName,+ altNames+ }))+ };+ };+const previewPkiSyncFilters = async (- { applicationId, pkiSyncId, filters }: Omit<TPreviewPkiSyncFiltersDTO, "projectId">,+ {+ applicationId,+ pkiSyncId,+ filters,+ offset = 0,+ limit = PKI_SYNC_PREVIEW_PAGE_SIZE+ }: Omit<TPreviewPkiSyncFiltersDTO, "projectId">,actor: OrgServiceActor): Promise<TPkiSyncFilterPreview> => {if (pkiSyncId) {@@ -1360,11 +1530,37 @@ export const pkiSyncServiceFactory = ({(pkiSync.syncOptions as { canRemoveCertificates?: boolean } | null)?.canRemoveCertificates);+ const permissionFilters = pkiSync.applicationId+ ? await $certificateReadFilters(pkiSync.projectId, pkiSync.applicationId, actor)+ : undefined;++ if (!permissionFilters) {+ return {+ matchedCount: diff.matched.length,+ certificates: diff.matched.slice(offset, offset + limit),+ toUnlink: diff.toUnlink,+ willRemoveFromDestination: canRemoveCertificates && diff.toUnlink.length > 0+ };+ }++ const scope = { projectId: pkiSync.projectId, applicationId: pkiSync.applicationId as string };++ const [matchedCount, certificates, readableUnlinkIds] = await Promise.all([+ certificateDAL.countCertificatesMatchingSyncFilters(filters, scope, permissionFilters),+ certificateDAL.findCertificatesMatchingSyncFilters(filters, scope, { permissionFilters, offset, limit }),+ certificateDAL.findReadableCertificateIds(+ diff.toUnlink.map((certificate) => certificate.id),+ pkiSync.projectId,+ permissionFilters+ )+ ]);++ const readableUnlinkIdSet = new Set(readableUnlinkIds);+return {- matchedCount: Math.min(diff.matched.length, PKI_SYNC_MAX_LINKED_CERTIFICATES),- hasMoreMatches: diff.matched.length > PKI_SYNC_MAX_LINKED_CERTIFICATES,- certificates: diff.matched.slice(0, PKI_SYNC_MAX_LINKED_CERTIFICATES),- toUnlink: diff.toUnlink,+ matchedCount,+ certificates,+ toUnlink: diff.toUnlink.filter((certificate) => readableUnlinkIdSet.has(certificate.id)),willRemoveFromDestination: canRemoveCertificates && diff.toUnlink.length > 0};}@@ -1388,18 +1584,21 @@ export const pkiSyncServiceFactory = ({await $assertFilterProfilesInApplication(filters, applicationId);- const matched = hasAnyPkiSyncFilter(filters)- ? await certificateDAL.findCertificatesMatchingSyncFilters(- filters,- { projectId: application.projectId, applicationId },- { limit: PKI_SYNC_MAX_LINKED_CERTIFICATES + 1 }- )- : [];+ if (!hasAnyPkiSyncFilter(filters)) {+ return { matchedCount: 0, certificates: [], toUnlink: [], willRemoveFromDestination: false };+ }++ const scope = { projectId: application.projectId, applicationId };+ const permissionFilters = await $certificateReadFilters(application.projectId, applicationId, actor);++ const [matchedCount, certificates] = await Promise.all([+ certificateDAL.countCertificatesMatchingSyncFilters(filters, scope, permissionFilters),+ certificateDAL.findCertificatesMatchingSyncFilters(filters, scope, { permissionFilters, offset, limit })+ ]);return {- matchedCount: Math.min(matched.length, PKI_SYNC_MAX_LINKED_CERTIFICATES),- hasMoreMatches: matched.length > PKI_SYNC_MAX_LINKED_CERTIFICATES,- certificates: matched.slice(0, PKI_SYNC_MAX_LINKED_CERTIFICATES),+ matchedCount,+ certificates,toUnlink: [],willRemoveFromDestination: false};@@ -1417,7 +1616,7 @@ export const pkiSyncServiceFactory = ({throw new BadRequestError({message: !filters? "This PKI sync has no filters, so certificates cannot be attached one at a time. Set its filters instead."- : "This PKI sync selects certificates by profile or metadata, so they cannot be attached one at a time. Edit its filters instead."+ : "This PKI sync selects certificates by another filter, so they cannot be attached one at a time. Edit its filters instead."});}@@ -1457,7 +1656,7 @@ export const pkiSyncServiceFactory = ({pkiSyncId: current.id,name: current.name,destination: current.destination,- hasFilters: true,+ hasFilters: hasAnyPkiSyncFilter(nextFilters),...(current.applicationId && { applicationId: current.applicationId })}}@@ -1496,7 +1695,7 @@ export const pkiSyncServiceFactory = ({certificateIds,pkiSync.projectId,pkiSync.applicationId,- { requireSyncable: true }+ { requireSyncable: true, actor });const { linked } = await $writeCertificateOrderIdsFilter(@@ -1710,6 +1909,7 @@ export const pkiSyncServiceFactory = ({triggerPkiSyncRemoveCertificatesById,getPkiSyncOptions,previewPkiSyncFilters,+ searchPkiSyncCertificateOrders,addCertificatesToPkiSync,removeCertificatesFromPkiSync,listPkiSyncCertificates,diff --git a/backend/src/services/pki-sync/pki-sync-types.ts b/backend/src/services/pki-sync/pki-sync-types.tsindex 463d436100..fe0f66d81f 100644--- a/backend/src/services/pki-sync/pki-sync-types.ts+++ b/backend/src/services/pki-sync/pki-sync-types.ts@@ -228,12 +228,25 @@ export type TPreviewPkiSyncFiltersDTO = {applicationId?: string;pkiSyncId?: string;filters?: TPkiSyncFilters | null;+ offset?: number;+ limit?: number;projectId?: string;};+export type TSearchPkiSyncCertificateOrdersDTO = {+ applicationId?: string;+ pkiSyncId?: string;+ certificateOrderIds: string[];+};++export type TPkiSyncCertificateOrder = {+ certificateOrderId: string;+ commonName: string;+ altNames?: string | null;+};+export type TPkiSyncFilterPreview = {matchedCount: number;- hasMoreMatches: boolean;certificates: TPkiSyncCertificateRef[];toUnlink: TPkiSyncCertificateRef[];willRemoveFromDestination: boolean;diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdxindex cb2bdcd67d..2080d07e71 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx@@ -115,7 +115,7 @@ flowchart LRConfigure:- **Destination**: Select the App Connection and target endpoint- - **Certificates**: Add filters describing the certificates this sync holds. A sync with no filters holds nothing+ - **Certificates**: Add filters describing the certificates this sync holds- **Options**: Configure sync behavior (see below)</Step><Step title="Certificates are synced">@@ -125,87 +125,29 @@ flowchart LR## Certificate filters-A sync holds whichever of the Application's certificates match its filters. Filters describe the certificates rather than naming them, so every certificate issued into the Application afterwards is attached automatically.+A sync holds whichever of the Application's certificates match its filters. Filters describe certificates instead of naming them, so a certificate issued into the Application later joins the sync as soon as it matches.-Filters live on the **Certificates** step of the sync, under the **Add Filter** menu. Three are available, and they can be combined:+### The filters-| Filter | Matches |-|--------|---------|-| **Certificate Order** | Every certificate belonging to the selected orders |-| **Certificate profile** | Certificates issued from any of the selected profiles |-| **Metadata** | Certificates carrying every key and value pair listed |+Filters live on the **Certificates** step of the sync, under **Add Filter**:-Each filter matches exactly, with no wildcards or patterns, and a certificate has to match **every** filter you set. Adding a filter always narrows the sync, never widens it. So `profile = Prod TLS Edge` plus `metadata tier = prod` holds only the certificates that are both.+| Filter | API field | Matches |+|--------|-----------|---------|+| **[Certificate Orders](/documentation/platform/pki/applications/certificates#certificate-orders)** | `certificateOrderIds` | The current certificate of each selected order, so the sync follows that order through its renewals |+| **[Certificate profile](/documentation/platform/pki/settings/profiles)** | `profileIds` | Certificates issued from any of the selected profiles |+| **Metadata** | `metadata` | Certificates carrying every key and value pair listed |-A sync with no filters holds nothing, so a new sync stays empty until you describe what it should take. To sync the whole Application, set a filter that matches all of it, such as **Certificate profile** listing every profile in the Application. Setting a filter to an empty list also matches nothing.+Matching is exact, and a certificate has to match every filter you set. Two filters are stricter than one, so `profile = Prod TLS Edge` together with `metadata tier = prod` holds the certificates that are both.-### Syncs with a certificate limit+<Warning>+ A sync with no filters syncs nothing. A new sync stays empty until you set one.+</Warning>-Four things limit how many certificates a sync can hold:--- **The destination itself.** Nutanix Prism Central replaces one cluster certificate, so it holds one.-- **A GCP Certificate Manager sync bound to a certificate map.** It holds four.-- **A name schema with no placeholder.** Every certificate needs a distinct name at the destination, so keep `{{certificateId}}` or `{{shortCertificateId}}` in the schema to hold more than one.-- **A health check or post-sync command naming one certificate.** `{{certificatePath}}` and `{{commonName}}` each resolve to a single certificate. Use `{{certificateFiles}}` or `{{certificateDirectory}}` in a command that has to cover every certificate in the run.--A limited sync takes **Certificate Order** and nothing else, naming at most as many orders as it can hold. **Certificate profile** and **Metadata** match every certificate issued into the Application, so they're rejected, on their own and alongside an order filter. A sync with no filters is accepted, since it holds nothing.--### Orders and renewals--A certificate id belongs to one certificate, and renewing it produces a new id. An order groups a certificate with every renewal of it, so naming an order keeps matching after a renewal. That is why syncs filter on orders rather than certificate ids.--At any moment an order matches exactly one certificate: its newest active one. A renewal therefore replaces its predecessor at the destination rather than joining it. Each certificate's order id is on its detail page, and the picker lets you choose an order by any certificate in it.--### Metadata pairs--Enter a key on its own to match any certificate carrying that key, whatever its value. Enter a key and a value to match that exact pair. A certificate has to carry every pair listed, so each pair narrows the filter further.--### Attaching and detaching one certificate--`POST` and `DELETE` on `/api/v1/cert-manager/syncs/:pkiSyncId/certificates` take certificate ids, resolve each to the order it belongs to, and add or remove that order in the **Certificate Order** filter. `infisical_certificate_sync_certificate` uses this in Terraform, so a client that names a certificate still follows its renewals.--The same resolution applies to the `certificateIds` field on sync creation.--Both work only on a sync whose **Certificate Order** filter is its only filter. On a sync that also filters by profile or metadata, or on one with no filters, they're rejected, because rewriting the order list would narrow the sync and detach everything else. Edit the filters instead.--### When certificates are attached and detached--One certificate is checked against the Application's syncs whenever it is:--- Issued through any enrollment method, including the API, ACME, EST, and SCEP-- Imported into the Application-- Renewed, either manually or by auto-renewal-- Updated with new metadata-- Assigned to the Application after being issued outside one-- Deleted--Editing a sync's filters re-checks every certificate in the Application instead. Certificates that now match are attached, and certificates that no longer match are detached.--Only active certificates are attached. Expired, revoked, and superseded certificates are skipped, so a renewal replaces its predecessor at the destination rather than joining it.--### Detaching can delete at the destination+### Dropping a certificate can delete it at the destinationA certificate that leaves a sync is deleted from the destination when **Allow to remove certificates from destination** is enabled, whether it left because it was deleted, because it stopped being active, or because a filter changed.-That makes a filter edit destructive. A load balancer serving a certificate loses it the moment that certificate stops matching. Before saving, Infisical lists the certificates a filter change would detach and asks you to confirm. Terraform prints the same list as a warning at plan. The API applies the change with no prompt, so call the [preview endpoint](#previewing-a-filter-change) first.--### Previewing a filter change--`POST /api/v1/cert-manager/syncs/certificates/preview` reports what a set of filters matches and changes nothing. Name the sync you intend to save them to:--```bash-curl -X POST "https://app.infisical.com/api/v1/cert-manager/syncs/certificates/preview" \- -H "Authorization: Bearer $TOKEN" \- -H "Content-Type: application/json" \- -d '{"pkiSyncId": "<sync-id>", "filters": {"profileIds": ["<profile-id>"]}}'-```--The response carries `matchedCount` and `certificates` for what the filters match, `hasMoreMatches` when they match more than a sync can hold, and `toUnlink` with `willRemoveFromDestination` for what the sync would lose. To try filters out before the sync exists, send `applicationId` instead of `pkiSyncId`: nothing can be detached yet, so `toUnlink` comes back empty.--<Note>- - A sync can hold up to 500 certificates.- - One filter can name at most 500 certificate orders, 20 certificate profiles, or 20 metadata pairs.-</Note>+So a filter edit can be destructive. A load balancer serving a certificate loses it the moment that certificate stops matching. Before you save, Infisical lists the certificates the change would drop and asks you to confirm.## Sync optionsdiff --git a/docs/documentation/platform/pki/applications/certificates.mdx b/docs/documentation/platform/pki/applications/certificates.mdxindex ce2c06ff3d..564eeaf953 100644--- a/docs/documentation/platform/pki/applications/certificates.mdx+++ b/docs/documentation/platform/pki/applications/certificates.mdx@@ -94,6 +94,22 @@ A profile backed by an external certificate authority needs the identifier the c</Tab></Tabs>+## Certificate orders++A certificate id belongs to one certificate. When you renew, you don't get that certificate back with a later expiry, you get a second certificate with its own id. The old one is marked **Renewed**, the new one becomes **Active**, and both stay in the inventory.++The order id is the part that stays put. It's stamped on the first certificate you issue, and every renewal of that certificate inherits it:++| `app.example.com` | Certificate id | Status |+|-------------------|----------------|--------|+| Issued in January | `a1b2c3d4` | Renewed |+| Renewed in April | `e5f6a7b8` | Renewed |+| Renewed in July | `c9d0e1f2` | Active |++Three certificates, one order. The order always points at the newest active one, `c9d0e1f2` here.++You'll find the order id on the certificate details page. It matters most over the API, where it lets you ask for whatever is current instead of chasing a new id after every renewal.+## Renewal| Type | How It Works |diff --git a/frontend/src/components/pki-syncs/CertificateManagementModal.tsx b/frontend/src/components/pki-syncs/CertificateManagementModal.tsxindex 7657468481..8532d6378c 100644--- a/frontend/src/components/pki-syncs/CertificateManagementModal.tsx+++ b/frontend/src/components/pki-syncs/CertificateManagementModal.tsx@@ -234,11 +234,12 @@ export const CertificateManagementModal = ({<Table><TableHeader><TableRow>- <TableHead className="w-12">+ <TableHead className="w-10">{!isSingleSelect && (<Checkboxid="select-all-certificates"variant="project"+ aria-label="Select every certificate on this page"isChecked={allCertificates.length > 0 &&allCertificates.every(@@ -263,6 +264,9 @@ export const CertificateManagementModal = ({const isAlreadySynced = Boolean(cert.orderId && preselectedOrderIds.includes(cert.orderId));+ const { orderId } = cert;+ const isSelectable = Boolean(orderId) && (!cannotBeAdded || isAlreadySynced);+ const isSelected = Boolean(orderId && selectedIds.includes(orderId));const { originalDisplayName, displayName, isTruncated } =getCertificateDisplayName(cert);@@ -271,26 +275,24 @@ export const CertificateManagementModal = ({return (<TableRowkey={cert.id}- className={`cursor-pointer ${- cannotBeAdded && !isAlreadySynced ? "opacity-50" : ""- }`}+ data-state={isSelected ? "selected" : undefined}+ className={+ isSelectable ? "cursor-pointer" : "cursor-not-allowed opacity-50"+ }onClick={() => {- if (cert.orderId && (!cannotBeAdded || isAlreadySynced)) {- handleToggleSelection(cert.orderId);- }+ if (orderId && isSelectable) handleToggleSelection(orderId);}}>- <TableCell className="max-w-0" onClick={(e) => e.stopPropagation()}>+ <TableCell onClick={(e) => e.stopPropagation()}><Checkbox- id={cert.id}+ id={`select-certificate-${cert.id}`}variant="project"- isChecked={Boolean(cert.orderId && selectedIds.includes(cert.orderId))}+ aria-label={`Select ${originalDisplayName}`}+ isChecked={isSelected}+ isDisabled={!isSelectable}onCheckedChange={() => {- if (cert.orderId && (!cannotBeAdded || isAlreadySynced)) {- handleToggleSelection(cert.orderId);- }+ if (orderId && isSelectable) handleToggleSelection(orderId);}}- isDisabled={cannotBeAdded && !isAlreadySynced}/></TableCell><TableCell className="max-w-0">diff --git a/frontend/src/components/pki-syncs/PkiSyncFilterBadges.tsx b/frontend/src/components/pki-syncs/PkiSyncFilterBadges.tsxindex f6e23cc049..e45a922a05 100644--- a/frontend/src/components/pki-syncs/PkiSyncFilterBadges.tsx+++ b/frontend/src/components/pki-syncs/PkiSyncFilterBadges.tsx@@ -3,7 +3,12 @@ import { ReactNode, useCallback, useState } from "react";import { Badge, HoverCard, HoverCardContent, HoverCardTrigger } from "@app/components/v3";import { TPkiSyncFilters } from "@app/hooks/api/pkiSyncs/types";-import { hasAnyFilter, isFilterPresent, TFilterKind } from "./forms/pki-sync-filter-fns";+import {+ FILTER_KINDS,+ hasAnyFilter,+ isFilterPresent,+ TFilterKind+} from "./forms/pki-sync-filter-fns";type TFilterCountLabelProps = { count: number; names: string[] };@@ -16,7 +21,7 @@ const FilterBadgeOverflow = ({ badges }: { badges: ReactNode[] }) => {{rest.length > 0 && (<HoverCard openDelay={100}><HoverCardTrigger asChild>- <Badge variant="neutral" className="cursor-default">+ <Badge variant="neutral" className="cursor-pointer hover:bg-neutral/35">+{rest.length}</Badge></HoverCardTrigger>@@ -40,21 +45,22 @@ export const PkiSyncFilterCountLabel = ({ count, names }: TFilterCountLabelPropsif (node) setPortalContainer(node.closest<HTMLElement>('[role="dialog"]'));}, []);- if (names.length === 0) return <span className="text-sm text-foreground">{count}</span>;+ if (names.length === 0) return <Badge variant="neutral">{count}</Badge>;return (<HoverCard openDelay={100}><HoverCardTrigger asChild>- <span ref={rootRef} className="text-sm text-foreground">+ <Badge ref={rootRef} variant="neutral" className="cursor-pointer hover:bg-neutral/35">{count}- </span>+ </Badge></HoverCardTrigger><HoverCardContentcontainer={portalContainer ?? undefined}className="flex max-h-64 w-64 flex-col gap-1 overflow-y-auto">- {names.map((name) => (- <span key={name} className="shrink-0 truncate font-mono text-xs">+ {names.map((name, index) => (+ // eslint-disable-next-line react/no-array-index-key+ <span key={`${name}-${index}`} className="shrink-0 truncate font-mono text-xs">{name}</span>))}@@ -80,11 +86,13 @@ const PkiSyncFilterValueBadges = ({ values }: { values: string[] }) => {export const buildPkiSyncFilterSummary = ({filters,profileNameById,- orderNameById+ orderNameById,+ visibleKinds = FILTER_KINDS}: {filters: TPkiSyncFilters | null | undefined;profileNameById: Map<string, string>;orderNameById: Map<string, string>;+ visibleKinds?: readonly TFilterKind[];}): { label: string; value: ReactNode }[] | null => {if (!hasAnyFilter(filters)) return null;@@ -96,10 +104,11 @@ export const buildPkiSyncFilterSummary = ({isFilterPresent(filters, kind) ? PkiSyncNoFilterLabel : PkiSyncAnyFilterLabel;const namesFor = (ids: string[] | undefined, lookup: Map<string, string>) =>- (ids ?? []).map((id) => lookup.get(id)).filter((name): name is string => Boolean(name));+ (ids ?? []).map((id) => lookup.get(id) ?? `Order ${id.slice(0, 8)}`);- return [+ const summary: { kind: TFilterKind; label: string; value: ReactNode }[] = [{+ kind: "profileIds",label: "Profiles",value: filters?.profileIds?.length ? (<PkiSyncFilterValueBadges@@ -110,6 +119,7 @@ export const buildPkiSyncFilterSummary = ({)},{+ kind: "certificateOrderIds",label: "Certificate Orders",value: filters?.certificateOrderIds?.length ? (<PkiSyncFilterCountLabel@@ -121,6 +131,7 @@ export const buildPkiSyncFilterSummary = ({)},{+ kind: "metadata",label: "Metadata",value: metadataPairs.length ? (<PkiSyncFilterCountLabel count={metadataPairs.length} names={metadataPairs} />@@ -129,4 +140,8 @@ export const buildPkiSyncFilterSummary = ({)}];++ return summary+ .filter(({ kind }) => visibleKinds.includes(kind))+ .map(({ label, value }) => ({ label, value }));};diff --git a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsxindex cd43850b13..704782f62a 100644--- a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx+++ b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx@@ -113,7 +113,7 @@ const STEP_META: Record<subtitle: "Link the certificates this sync pushes.",rightLabel: "CERTIFICATES",rightDescription:- "Anything in the Application matching these filters is attached as it is issued. A sync with no filters holds nothing."+ "Anything in the application matching these filters is synced as it is issued. A sync with no filters syncs nothing."},review: {short: "Confirm and create",diff --git a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsxindex 38e729822a..f1d77634f6 100644--- a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx+++ b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx@@ -151,7 +151,7 @@ const getFormSteps = (subtitle: "Describe the certificates this sync holds.",rightLabel: "CERTIFICATES",rightDescription:- "Anything in the Application matching these filters is attached as it is issued, and anything that stops matching is detached. Nothing changes until you save."+ "Anything in the application matching these filters is synced as it is issued, and anything that stops matching is no longer synced. Nothing changes until you save."});steps.push({@@ -464,11 +464,14 @@ export const EditPkiSyncForm = ({</AlertDialogMedia><AlertDialogTitle>{pendingUnlink?.preview.toUnlink.length} certificate- {pendingUnlink?.preview.toUnlink.length === 1 ? "" : "s"} will be detached+ {pendingUnlink?.preview.toUnlink.length === 1 ? "" : "s"} will no longer be synced</AlertDialogTitle><AlertDialogDescription asChild><div className="flex flex-col gap-2">- <p>These certificates no longer match the filters and will be detached:</p>+ <p>+ These certificates no longer match the filters, so this sync will stop holding+ them:+ </p><ul className="max-h-40 overflow-y-auto font-mono text-xs">{pendingUnlink?.preview.toUnlink.map((certificate) => (<li key={certificate.id}>@@ -497,7 +500,7 @@ export const EditPkiSyncForm = ({if (pending) applyUpdate(pending.formData).catch(() => {});}}>- Detach and save+ Save changes</AlertDialogAction></AlertDialogFooter></AlertDialogContent>diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncCertificateAddMenu.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncCertificateAddMenu.tsxindex 165b5051bb..fe169b96f1 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncCertificateAddMenu.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncCertificateAddMenu.tsx@@ -21,7 +21,7 @@ import {} from "./pki-sync-filter-fns";const FILTER_HINTS: Record<TFilterKind, string> = {- certificateOrderIds: "Follows every renewal of a certificate",+ certificateOrderIds: "An order is a certificate and its renewals",profileIds: "Issued from one of these profiles",metadata: "Carries this key and value"};@@ -44,15 +44,14 @@ export const PkiSyncCertificateAddMenu = ({ applicationId, onOpenPicker }: Propsconst supportsFilters = Boolean(applicationId);- const addableFilterKinds = FILTER_KINDS.filter(- (kind) =>- (certificateCap === undefined || kind === "certificateOrderIds") &&- (kind === "metadata" || !isFilterPresent(filters, kind))- );+ const addableFilterKinds = FILTER_KINDS.filter((kind) => {+ if (certificateCap !== undefined && kind !== "certificateOrderIds") return false;++ return kind === "metadata" || !isFilterPresent(filters, kind);+ });const addFilter = (kind: TFilterKind) => {if (kind === "certificateOrderIds") {- setValue("filters", { ...filters, [kind]: [] }, { shouldDirty: true });onOpenPicker();return;}diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncCertificatesFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncCertificatesFields.tsxindex 81177e1fcb..407d055423 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncCertificatesFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncCertificatesFields.tsx@@ -1,21 +1,29 @@import { useMemo, useState } from "react";import { useFormContext } from "react-hook-form";-import { FilterIcon, RefreshCwIcon, TriangleAlertIcon } from "lucide-react";+import { FilterIcon, RefreshCwIcon, TrashIcon, TriangleAlertIcon } from "lucide-react";import {Alert,AlertDescription,AlertTitle,+ Badge,Button,Empty,EmptyDescription,EmptyMedia,+ IconButton,+ Pagination,Tooltip,TooltipContent,TooltipTrigger} from "@app/components/v3";import { useProject } from "@app/context";-import { PkiSync, usePkiSyncOption, usePkiSyncPreviewCertificates } from "@app/hooks/api/pkiSyncs";+import {+ PkiSync,+ usePkiSyncCertificateOrders,+ usePkiSyncOption,+ usePkiSyncPreviewCertificates+} from "@app/hooks/api/pkiSyncs";import { TPkiSyncFilters } from "@app/hooks/api/pkiSyncs/types";import { CertificateManagementModal } from "../CertificateManagementModal";@@ -24,7 +32,8 @@ import {buildOrderNameMap,getPkiSyncCertificateCap,hasAnyFilter,- hasUnfinishedFilter+ hasUnfinishedFilter,+ isCertificateOrderTheOnlyFilter} from "./pki-sync-filter-fns";import { PkiSyncCertificateAddMenu } from "./PkiSyncCertificateAddMenu";import { PkiSyncFilterFields } from "./PkiSyncFilterFields";@@ -33,6 +42,8 @@ import {TMatchedCertificateRow} from "./PkiSyncMatchedCertificatesTable";+const MATCHED_PAGE_SIZE = 20;+type Props = {applicationId?: string;pkiSyncId?: string;@@ -59,6 +70,7 @@ export const PkiSyncCertificatesFields = ({ applicationId, pkiSyncId }: Props) =const [isPickerOpen, setIsPickerOpen] = useState(false);const [previewFilters, setPreviewFilters] = useState<TPkiSyncFilters | null>(filters ?? null);+ const [page, setPage] = useState(1);const previewKey = JSON.stringify(previewFilters ?? null);const isStale = filtersKey !== previewKey;@@ -73,43 +85,67 @@ export const PkiSyncCertificatesFields = ({ applicationId, pkiSyncId }: Props) =applicationId,pkiSyncId,filters: previewFilters,+ offset: (page - 1) * MATCHED_PAGE_SIZE,+ limit: MATCHED_PAGE_SIZE,enabled: Boolean(applicationId) && hasAnyFilter(previewFilters)});const reloadPreview = () => {+ setPage(1);if (isStale) setPreviewFilters(filters ?? null);else refetchPreview().catch(() => {});};const [pickedOrderNames, setPickedOrderNames] = useState<[string, string][]>([]);+ const { data: resolvedOrderNames } = usePkiSyncCertificateOrders({+ applicationId,+ pkiSyncId,+ certificateOrderIds: filters?.certificateOrderIds ?? []+ });+const orderNameById = useMemo(- () => new Map([...buildOrderNameMap(preview?.certificates), ...pickedOrderNames]),- [preview, pickedOrderNames]+ () =>+ new Map([+ ...(resolvedOrderNames ?? new Map<string, string>()),+ ...buildOrderNameMap(preview?.certificates),+ ...pickedOrderNames+ ]),+ [resolvedOrderNames, preview, pickedOrderNames]);const matchedRows: TMatchedCertificateRow[] = preview?.certificates ?? [];+ const matchedCount = preview?.totalCount ?? 0;- const matchedDescription = () => {- if (!preview) return "Loading the certificates these filters match.";- if (preview.hasMoreMatches) {- return `More than ${matchedRows.length} certificates match. Narrow the filters before saving.`;+ const setOrderIds = (certificateOrderIds: string[]) => {+ if (certificateOrderIds.length === 0) {+ const remaining = { ...(filters ?? {}) };+ delete remaining.certificateOrderIds;+ setValue("filters", Object.keys(remaining).length ? remaining : null, { shouldDirty: true });+ return;}- return `Showing ${matchedRows.length} certificate${matchedRows.length === 1 ? "" : "s"} matched by these filters.`;++ setValue("filters", { ...(filters ?? {}), certificateOrderIds }, { shouldDirty: true });};- 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>+ const certificatePicker = (+ <CertificateManagementModal+ isOpen={isPickerOpen}+ onClose={() => setIsPickerOpen(false)}+ destination={watch("destination")}+ applicationId={applicationId}+ maxSelectable={certificateCap}+ selectedOrderIds={filters?.certificateOrderIds ?? []}+ onOrderSelectionChange={(certificateOrderIds, orderNames) => {+ setPickedOrderNames((prev) => [...prev, ...orderNames]);+ setOrderIds(certificateOrderIds);+ }}+ title={+ certificateCap === 1 ? "Select a Certificate to Sync" : "Select Certificate Orders to Sync"+ }+ subtitle="Selecting a certificate selects its order, so the sync follows every renewal of it."+ saveButtonText="Update Selection"+ />);if (!applicationId) {@@ -119,30 +155,101 @@ export const PkiSyncCertificatesFields = ({ applicationId, pkiSyncId }: Props) =<FilterIcon /></EmptyMedia><EmptyDescription>- This sync is not attached to an Application, so its certificates cannot be changed. Create- a sync inside an Application to select certificates by filter.+ This sync is not attached to an application, so its certificates cannot be changed. Create+ a sync inside an application to select certificates by filter.</EmptyDescription></Empty>);}- return (- <div className="flex min-h-0 flex-1 flex-col">- <div className="flex items-start justify-between gap-4">- <div>- <p className="text-sm font-medium text-foreground">Filters</p>- <p className="mt-0.5 text-xs text-muted">- {certificateCap === undefined- ? "A certificate is synced only when it matches every filter below."- : `Holds at most ${certificateCap} certificate${- certificateCap === 1 ? "" : "s"- }, so it only accepts a certificate order filter.`}- </p>+ if (+ certificateCap === 1 &&+ (!hasAnyFilter(filters) || isCertificateOrderTheOnlyFilter(filters))+ ) {+ const selectedOrderId = filters?.certificateOrderIds?.[0];++ return (+ <div className="flex flex-col">+ <p className="text-sm font-medium text-foreground">Certificate</p>+ <p className="mt-0.5 text-xs text-muted">+ This destination holds one certificate. The order you pick stays synced through every+ renewal of it.+ </p>+ <div className="mt-3 flex items-center gap-3">+ {selectedOrderId ? (+ <>+ <Badge+ variant="outline"+ isTruncatable+ className="h-9 min-w-0 flex-1 pl-3 font-mono text-foreground"+ >+ <span className="truncate">+ {orderNameById.get(selectedOrderId) ?? selectedOrderId}+ </span>+ </Badge>+ <Button+ type="button"+ size="sm"+ variant="outline"+ className="h-9"+ onClick={() => setIsPickerOpen(true)}+ >+ Change+ </Button>+ <IconButton+ type="button"+ size="xs"+ variant="ghost"+ className="hover:text-danger"+ aria-label="Remove certificate"+ onClick={() => setValue("filters", null, { shouldDirty: true })}+ >+ <TrashIcon className="size-4" />+ </IconButton>+ </>+ ) : (+ <>+ <p className="flex-1 text-sm text-muted">No certificate selected.</p>+ <Button+ type="button"+ size="sm"+ variant="outline"+ className="h-9"+ onClick={() => setIsPickerOpen(true)}+ >+ Select Certificate+ </Button>+ </>+ )}</div>- <PkiSyncCertificateAddMenu- applicationId={applicationId}- onOpenPicker={() => setIsPickerOpen(true)}- />+ {certificatePicker}+ </div>+ );+ }++ 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">+ {certificateCap === undefined+ ? "A certificate is synced only when it matches every filter below."+ : `This destination holds up to ${certificateCap} certificates, so it only accepts a certificate order filter.`}+ </p></div>{certificateCap !== undefined && growableFilterKinds.length > 0 && (@@ -153,9 +260,7 @@ export const PkiSyncCertificatesFields = ({ applicationId, pkiSyncId }: Props) =: "Remove the filters below"}</AlertTitle><AlertDescription>- {`This sync holds at most ${certificateCap} certificate${- certificateCap === 1 ? "" : "s"- }, so it only accepts a certificate order filter.`}+ {`This destination holds up to ${certificateCap} certificates, so it only accepts a certificate order filter.`}</AlertDescription></Alert>)}@@ -172,17 +277,28 @@ export const PkiSyncCertificatesFields = ({ applicationId, pkiSyncId }: Props) =<FilterIcon /></EmptyMedia><EmptyDescription>- No filters, so this sync holds nothing. Add one to select certificates.+ Add a filter to choose which certificates this sync holds.</EmptyDescription></Empty>)}+ <div className="mt-3">+ <PkiSyncCertificateAddMenu+ applicationId={applicationId}+ onOpenPicker={() => setIsPickerOpen(true)}+ />+ </div>+{hasAnyFilter(filters) && (<><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">{matchedDescription()}</p>+ <p className="mt-0.5 text-xs text-muted">+ {preview+ ? `${matchedCount} certificate${matchedCount === 1 ? " matches" : "s match"} these filters.`+ : "Loading the certificates these filters match."}+ </p></div>{isStale ? (<Tooltip>@@ -200,32 +316,29 @@ export const PkiSyncCertificatesFields = ({ applicationId, pkiSyncId }: Props) =)}</div>- <div className="mt-3 min-h-0 flex-1 overflow-y-auto">+ <div className="mt-3"><PkiSyncMatchedCertificatesTablerows={matchedRows}isLoading={isPreviewing}emptyTitle="No certificates match"- emptyDescription="Nothing in this Application matches these filters yet."+ emptyDescription="Nothing in this application matches these filters 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></>)}- <CertificateManagementModal- isOpen={isPickerOpen}- onClose={() => setIsPickerOpen(false)}- destination={watch("destination")}- applicationId={applicationId}- maxSelectable={certificateCap}- selectedOrderIds={filters?.certificateOrderIds ?? []}- onOrderSelectionChange={(certificateOrderIds, orderNames) => {- setPickedOrderNames((prev) => [...prev, ...orderNames]);- setValue("filters", { ...(filters ?? {}), certificateOrderIds }, { shouldDirty: true });- }}- title="Select Certificate Orders for Sync"- subtitle="Selecting a certificate selects its order, which follows every renewal."- saveButtonText="Update Selection"- />+ {certificatePicker}</div>);};diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncFilterFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncFilterFields.tsxindex a86230197d..6b543cddd6 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncFilterFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncFilterFields.tsx@@ -1,17 +1,20 @@-import { useCallback, useMemo, useState } from "react";+import { Fragment, useCallback, useMemo, useState } from "react";import { Controller, useFormContext } from "react-hook-form";-import { PlusIcon, XIcon } from "lucide-react";+import { PlusIcon, TrashIcon, XIcon } from "lucide-react";import {Badge,Button,+ Field,+ FieldContent,FieldError,+ FieldLabel,FilterableSelect,+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,IconButton,- Input,- Popover,- PopoverContent,- PopoverTrigger+ Input} from "@app/components/v3";import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";import { TPkiSyncFilters } from "@app/hooks/api/pkiSyncs/types";@@ -77,7 +80,16 @@ export const PkiSyncFilterFields = ({ applicationId, orderNameById, onOpenPickerconst kind = "certificateOrderIds" as const;const ids = filters[kind] ?? [];const [first, ...rest] = ids;- const labelFor = (id: string) => orderNameById.get(id) ?? id;+ const labelFor = (id: string) => orderNameById.get(id) ?? `Order ${id.slice(0, 8)}`;+ const removeId = (id: string) => {+ const remaining = ids.filter((candidate) => candidate !== id);+ if (remaining.length === 0) {+ removeFilter(kind);+ return;+ }++ setFilter(kind, remaining);+ };return (<div className="flex h-9 w-full min-w-0 items-center justify-between gap-1.5">@@ -86,62 +98,61 @@ export const PkiSyncFilterFields = ({ applicationId, orderNameById, onOpenPicker<Badgevariant="outline"isTruncatable- className="h-9 min-w-0 flex-1 font-mono text-foreground"+ className="h-9 min-w-0 flex-1 pl-3 font-mono text-foreground">- <span className="truncate">{labelFor(first)}</span>- <IconButton- type="button"- size="xs"- variant="ghost-muted"- className="ml-auto"- aria-label={`Remove ${labelFor(first)}`}- onClick={() =>- setFilter(- kind,- ids.filter((candidate) => candidate !== first)- )- }- >- <XIcon />- </IconButton>- </Badge>- )}- {rest.length > 0 && (- <Popover>- <PopoverTrigger asChild>- <Badge asChild variant="outline" className="h-9 shrink-0 text-foreground">- <button type="button">+{rest.length}</button>- </Badge>- </PopoverTrigger>- <PopoverContent- align="end"- container={portalContainer ?? undefined}- className="flex max-h-64 w-64 flex-col gap-1.5 overflow-y-auto p-2.5"- >- {rest.map((id) => (- <div key={id} className="flex items-center justify-between gap-2">- <span className="min-w-0 flex-1 truncate font-mono text-xs">- {labelFor(id)}- </span>- <IconButton- type="button"- size="xs"- variant="ghost-muted"- className="shrink-0"- aria-label={`Remove ${labelFor(id)}`}- onClick={() =>- setFilter(- kind,- ids.filter((candidate) => candidate !== id)- )- }+ <span className="truncate" title={first}>+ {labelFor(first)}+ </span>+ <span className="ml-auto flex shrink-0 items-center gap-1">+ {rest.length > 0 && (+ <HoverCard openDelay={100}>+ <HoverCardTrigger asChild>+ <Badge+ variant="neutral"+ className="cursor-pointer font-sans hover:bg-neutral/35"+ >+ +{rest.length}+ </Badge>+ </HoverCardTrigger>+ <HoverCardContent+ align="end"+ container={portalContainer ?? undefined}+ className="flex max-h-64 w-64 flex-col gap-1.5 overflow-y-auto p-2.5">- <XIcon />- </IconButton>- </div>- ))}- </PopoverContent>- </Popover>+ {rest.map((id) => (+ <div key={id} className="flex items-center justify-between gap-2">+ <span+ className="min-w-0 flex-1 truncate font-mono text-xs"+ title={id}+ >+ {labelFor(id)}+ </span>+ <IconButton+ type="button"+ size="xs"+ variant="ghost-muted"+ className="shrink-0"+ aria-label={`Remove ${labelFor(id)}`}+ onClick={() => removeId(id)}+ >+ <XIcon />+ </IconButton>+ </div>+ ))}+ </HoverCardContent>+ </HoverCard>+ )}+ <IconButton+ type="button"+ size="xs"+ variant="ghost-muted"+ aria-label={`Remove ${labelFor(first)}`}+ onClick={() => removeId(first)}+ >+ <XIcon />+ </IconButton>+ </span>+ </Badge>)}</div><Button@@ -180,10 +191,10 @@ export const PkiSyncFilterFields = ({ applicationId, orderNameById, onOpenPickerif (kind === "metadata") {return (- <div className="flex flex-col gap-2">+ <div className="flex flex-col gap-3">{metadata.map((pair, index) => (// eslint-disable-next-line react/no-array-index-key- <div key={index} className="flex items-center gap-2">+ <div key={index} className="flex items-center gap-3"><InputclassName="min-w-0 flex-1 font-mono"placeholder="Key"@@ -212,9 +223,9 @@ export const PkiSyncFilterFields = ({ applicationId, orderNameById, onOpenPicker/><IconButtontype="button"- size="sm"+ size="xs"variant="ghost"- className="ml-2"+ className="hover:text-danger"aria-label="Remove metadata pair"onClick={() => {if (metadata.length === 1) {@@ -227,7 +238,7 @@ export const PkiSyncFilterFields = ({ applicationId, orderNameById, onOpenPicker);}}>- <XIcon />+ <TrashIcon className="size-4" /></IconButton></div>))}@@ -245,25 +256,35 @@ export const PkiSyncFilterFields = ({ applicationId, orderNameById, onOpenPicker};return (- <div ref={rootRef} className="mt-3 divide-y divide-border">- {kinds.map((kind) => (- <div key={kind} className="flex items-start gap-4 py-4">- <div className="w-40 shrink-0 pt-1.5">- <p className="text-sm text-foreground">{FILTER_LABELS[kind]}</p>- </div>- <div className="min-w-0 flex-1">{renderBody(kind)}</div>- {kind !== "metadata" && (- <IconButton- type="button"- size="sm"- variant="ghost"- aria-label={`Remove ${FILTER_LABELS[kind]} filter`}- onClick={() => removeFilter(kind)}- >- <XIcon />- </IconButton>+ <div ref={rootRef} className="mt-3 flex flex-col gap-3">+ {kinds.map((kind, index) => (+ <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>+ <div className="flex items-start gap-3">+ <Field className="min-w-0 flex-1">+ <FieldLabel className="text-xs">{FILTER_LABELS[kind]}</FieldLabel>+ <FieldContent>{renderBody(kind)}</FieldContent>+ </Field>+ {kind !== "metadata" && (+ <IconButton+ type="button"+ size="xs"+ variant="ghost"+ className="mt-6.5 hover:text-danger"+ aria-label={`Remove ${FILTER_LABELS[kind]} filter`}+ onClick={() => removeFilter(kind)}+ >+ <TrashIcon className="size-4" />+ </IconButton>+ )}+ </div>+ </Fragment>))}</div>);diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable.tsxindex b3535643af..1290bae5ce 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable.tsx@@ -42,7 +42,7 @@ export const PkiSyncMatchedCertificatesTable = ({}: Props) => {if (isLoading) {return (- <div className="flex flex-col gap-2">+ <div className="flex min-h-40 flex-col gap-2"><Skeleton className="h-8 w-full" /><Skeleton className="h-8 w-full" /><Skeleton className="h-8 w-full" />@@ -52,7 +52,7 @@ export const PkiSyncMatchedCertificatesTable = ({if (rows.length === 0) {return (- <Empty className="border py-8">+ <Empty className="min-h-40 border py-8"><EmptyMedia variant="icon"><ScrollText /></EmptyMedia>diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsxindex 9e095c6a20..a3827611fc 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx@@ -66,10 +66,10 @@ export const PkiSyncOptionsFields = ({ destination, isUpdate }: Props) => {label="Allow to remove certificates from destination"description={<>- When enabled, Infisical deletes a certificate from the destination once it leaves this- sync, whether it stopped being active, was deleted, was unlinked, or stopped matching- the sync's filters. Disable this if you manage some certificates manually outside- of Infisical.+ When enabled, Infisical deletes a certificate from the destination once this sync+ stops holding it, whether it stopped being active, was deleted, was removed from the+ sync, or stopped matching the sync's filters. Disable this if you manage some+ certificates manually outside of Infisical.{currentDestination === PkiSync.AwsElasticLoadBalancer &&" For AWS Elastic Load Balancer, this removes the certificate from both the load balancer listeners and AWS Certificate Manager, affecting only certificates managed by this sync."}</>diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsxindex c76a0f2ac6..c5aaebe19c 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx@@ -1,9 +1,16 @@-import { ReactNode } from "react";+import { ReactNode, useState } from "react";import { useFormContext } from "react-hook-form";import { FilterIcon } from "lucide-react";import { buildPkiSyncFilterSummary } from "@app/components/pki-syncs/PkiSyncFilterBadges";-import { Badge, CodeBlock, Empty, EmptyDescription, EmptyMedia } from "@app/components/v3";+import {+ Badge,+ CodeBlock,+ Empty,+ EmptyDescription,+ EmptyMedia,+ Pagination+} from "@app/components/v3";import { useProject } from "@app/context";import {BOOLEAN_SYNC_OPTION_FIELDS,@@ -12,13 +19,15 @@ import {VALUE_SYNC_OPTION_FIELDS} from "@app/helpers/pkiSyncs";import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";-import { usePkiSyncPreviewCertificates } from "@app/hooks/api/pkiSyncs";+import { usePkiSyncOption, usePkiSyncPreviewCertificates } from "@app/hooks/api/pkiSyncs";import { TPkiSyncFilters } from "@app/hooks/api/pkiSyncs/types";import { TPkiSyncForm } from "./schemas/pki-sync-schema";-import { buildOrderNameMap, hasAnyFilter } from "./pki-sync-filter-fns";+import { buildOrderNameMap, getPkiSyncCertificateCap, hasAnyFilter } from "./pki-sync-filter-fns";import { PkiSyncMatchedCertificatesTable } from "./PkiSyncMatchedCertificatesTable";+const MATCHED_PAGE_SIZE = 20;+const ReviewFieldLabel = ({ label, children }: { label: string; children?: ReactNode }) => (<div className="row-span-2 grid min-w-0 grid-rows-subgrid pb-2"><p className="mb-1 text-xs font-medium text-muted">{label}</p>@@ -57,22 +66,36 @@ export const PkiSyncReviewFields = ({ applicationId }: Props = {}) => {const destinationName = PKI_SYNC_MAP[destination].name;+ const { syncOption } = usePkiSyncOption(destination);+ const acceptsOnlyCertificateOrders =+ getPkiSyncCertificateCap({+ destinationMaxCertificates: syncOption?.maxCertificates,+ syncOptions: syncOptions as Record<string, unknown> | undefined,+ destinationConfig: destinationConfig as Record<string, unknown> | undefined+ }) !== undefined;++ const [page, setPage] = useState(1);+const { data: preview, isPending: isPreviewPending } = usePkiSyncPreviewCertificates({projectId: currentProject?.id || "",applicationId,filters: (filters ?? null) as TPkiSyncFilters | null,+ offset: (page - 1) * MATCHED_PAGE_SIZE,+ limit: MATCHED_PAGE_SIZE,enabled: Boolean(applicationId) && hasAnyFilter(filters)});const orderNameById = buildOrderNameMap(preview?.certificates);const matchedRows = hasAnyFilter(filters) ? (preview?.certificates ?? []) : [];+ const matchedCount = hasAnyFilter(filters) ? (preview?.totalCount ?? 0) : 0;const filterFields = buildPkiSyncFilterSummary({filters: (filters ?? null) as TPkiSyncFilters | null,profileNameById: new Map((profileData?.certificateProfiles ?? []).map(({ id, slug }) => [id, slug])),- orderNameById+ orderNameById,+ visibleKinds: acceptsOnlyCertificateOrders ? ["certificateOrderIds"] : undefined});const postSyncCommand =syncOptions && "postSyncCommand" in syncOptions ? syncOptions.postSyncCommand : undefined;@@ -88,7 +111,10 @@ export const PkiSyncReviewFields = ({ applicationId }: Props = {}) => {<div className="w-full"><p className="mb-2 text-sm font-medium text-foreground">Filters</p>{filterFields ? (- <div className="mb-4 grid grid-cols-3 gap-x-8">+ <div+ className="mb-4 grid gap-x-8"+ style={{ gridTemplateColumns: `repeat(${filterFields.length}, minmax(0, 1fr))` }}+ >{filterFields.map(({ label, value }) => (<ReviewFieldLabel key={label} label={label}>{value}@@ -100,23 +126,32 @@ export const PkiSyncReviewFields = ({ applicationId }: Props = {}) => {<EmptyMedia variant="icon"><FilterIcon /></EmptyMedia>- <EmptyDescription>No filters, so this sync holds nothing.</EmptyDescription>+ <EmptyDescription>No filters set. Nothing will be synced.</EmptyDescription></Empty>)}{hasAnyFilter(filters) && (<><p className="mb-2 text-sm font-medium text-foreground">Matched Certificates</p><p className="mb-2 text-xs text-muted">- {preview?.hasMoreMatches- ? `More than ${matchedRows.length} certificates match. Narrow the filters before saving.`- : `${matchedRows.length} certificate${matchedRows.length === 1 ? "" : "s"} will be synced.`}+ {matchedCount} certificate{matchedCount === 1 ? "" : "s"} will be synced.</p><PkiSyncMatchedCertificatesTablerows={matchedRows}isLoading={isPreviewPending}emptyTitle="No certificates match"- emptyDescription="Nothing in this Application matches these filters yet."+ emptyDescription="Nothing in this application matches these filters 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>diff --git a/frontend/src/components/pki-syncs/forms/pki-sync-filter-fns.ts b/frontend/src/components/pki-syncs/forms/pki-sync-filter-fns.tsindex 5609665e60..e78cea93e0 100644--- a/frontend/src/components/pki-syncs/forms/pki-sync-filter-fns.ts+++ b/frontend/src/components/pki-syncs/forms/pki-sync-filter-fns.ts@@ -6,16 +6,16 @@ export const FILTER_KINDS = ["certificateOrderIds", "profileIds", "metadata"] asexport type TFilterKind = (typeof FILTER_KINDS)[number];export const FILTER_LABELS: Record<TFilterKind, string> = {- certificateOrderIds: "Certificate Order",+ certificateOrderIds: "Certificate Orders",profileIds: "Certificate profile",metadata: "Metadata"};-export const hasAnyFilter = (filters: TPkiSyncFilters | null | undefined) =>- Boolean(filters && FILTER_KINDS.some((kind) => filters[kind] !== undefined));-export const isFilterPresent = (filters: TPkiSyncFilters | null | undefined, kind: TFilterKind) =>- Boolean(filters && filters[kind] !== undefined);+ filters?.[kind] !== undefined;++export const hasAnyFilter = (filters: TPkiSyncFilters | null | undefined) =>+ FILTER_KINDS.some((kind) => isFilterPresent(filters, kind));export const presentFilterKinds = (filters: TPkiSyncFilters | null | undefined): TFilterKind[] =>FILTER_KINDS.filter((kind) => isFilterPresent(filters, kind));diff --git a/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.tsindex d6c3bcba1a..4efafa85ed 100644--- a/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts+++ b/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts@@ -4,6 +4,8 @@ import { AppConnection } from "@app/hooks/api/appConnections/enums";export const HOST_COMMAND_MAX_LENGTH = 8192;+export const MAX_FILTER_CERTIFICATE_ORDERS = 10_000;+export const HostCommandSchema = z.string().trim()@@ -103,8 +105,19 @@ export const BasePkiSyncSchema = <T extends AnyZodObject | undefined = undefinedsubscriberId: z.string().nullable().optional(),filters: z.object({- profileIds: z.array(z.string().uuid()).max(20).optional(),- certificateOrderIds: z.string().uuid().array().max(500).optional(),+ profileIds: z+ .array(z.string().uuid())+ .max(20, "A filter can use at most 20 profiles")+ .optional(),+ certificateOrderIds: z+ .string()+ .uuid()+ .array()+ .max(+ MAX_FILTER_CERTIFICATE_ORDERS,+ `A filter can name at most ${MAX_FILTER_CERTIFICATE_ORDERS} certificate orders`+ )+ .optional(),metadata: z.array(z.object({diff --git a/frontend/src/hooks/api/pkiSyncs/mutations.tsx b/frontend/src/hooks/api/pkiSyncs/mutations.tsxindex 6399488350..ef8c6abbf1 100644--- a/frontend/src/hooks/api/pkiSyncs/mutations.tsx+++ b/frontend/src/hooks/api/pkiSyncs/mutations.tsx@@ -312,7 +312,7 @@ export const usePreviewPkiSyncFilters = () => {filters?: TPkiSyncFilters | null;}) => {const { data } = await apiRequest.post<TPkiSyncFilterPreview>(- "/api/v1/cert-manager/syncs/certificates/preview",+ "/api/v1/cert-manager/syncs/certificates/search",{ pkiSyncId, filters: filters ?? null });diff --git a/frontend/src/hooks/api/pkiSyncs/queries.tsx b/frontend/src/hooks/api/pkiSyncs/queries.tsxindex c83471b405..5ea1655443 100644--- a/frontend/src/hooks/api/pkiSyncs/queries.tsx+++ b/frontend/src/hooks/api/pkiSyncs/queries.tsx@@ -1,6 +1,7 @@import { useQuery, UseQueryOptions } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";+import { getCertificateDisplayName } from "@app/helpers/pkiSyncs";import { PkiSync, TPkiSyncOption } from "@app/hooks/api/pkiSyncs";import {TAwsListener,@@ -10,6 +11,7 @@ import {TListPkiSyncs,TPkiSync,TPkiSyncCertificate,+ TPkiSyncCertificateOrder,TPkiSyncFilterPreview,TPkiSyncFilters} from "@app/hooks/api/pkiSyncs/types";@@ -37,17 +39,23 @@ export const pkiSyncKeys = {[...pkiSyncKeys.all, "aws-listeners", connectionId, region, loadBalancerArn] as const,kempVirtualServices: (connectionId: string) =>[...pkiSyncKeys.all, "kemp-virtual-services", connectionId] as const,+ certificateOrders: (scopeId: string, certificateOrderIds: string[]) =>+ [...pkiSyncKeys.all, "certificate-orders", scopeId, certificateOrderIds] as const,matchingCertificateIds: (projectId: string,- applicationId: string,- filters?: TPkiSyncFilters | null+ scopeId: string,+ filters?: TPkiSyncFilters | null,+ offset?: number,+ limit?: number) =>[...pkiSyncKeys.all,"matching-certificate-ids",projectId,- applicationId,- filters ?? null+ scopeId,+ filters ?? null,+ offset ?? 0,+ limit ?? 20] as const};@@ -56,34 +64,39 @@ export const usePkiSyncPreviewCertificates = ({applicationId,pkiSyncId,filters,+ offset = 0,+ limit = 20,enabled = false}: {projectId: string;applicationId?: string | null;pkiSyncId?: string | null;filters?: TPkiSyncFilters | null;+ offset?: number;+ limit?: number;enabled?: boolean;}) => {return useQuery({queryKey: pkiSyncKeys.matchingCertificateIds(projectId,pkiSyncId ?? applicationId ?? "",- filters+ filters,+ offset,+ limit),enabled,staleTime: Infinity,queryFn: async () => {const { data } = await apiRequest.post<TPkiSyncFilterPreview>(- "/api/v1/cert-manager/syncs/certificates/preview",+ "/api/v1/cert-manager/syncs/certificates/search",pkiSyncId- ? { pkiSyncId, filters: filters ?? null }- : { applicationId, filters: filters ?? null }+ ? { pkiSyncId, filters: filters ?? null, offset, limit }+ : { applicationId, filters: filters ?? null, offset, limit });return {certificates: data.certificates,totalCount: data.matchedCount,- hasMoreMatches: data.hasMoreMatches,toUnlink: data.toUnlink,willRemoveFromDestination: data.willRemoveFromDestination};@@ -91,6 +104,41 @@ export const usePkiSyncPreviewCertificates = ({});};+export const MAX_RESOLVED_CERTIFICATE_ORDERS = 200;++export const usePkiSyncCertificateOrders = ({+ applicationId,+ pkiSyncId,+ certificateOrderIds+}: {+ applicationId?: string | null;+ pkiSyncId?: string | null;+ certificateOrderIds: string[];+}) => {+ const ids = certificateOrderIds.slice(0, MAX_RESOLVED_CERTIFICATE_ORDERS);++ return useQuery({+ queryKey: pkiSyncKeys.certificateOrders(pkiSyncId ?? applicationId ?? "", ids),+ enabled: Boolean((pkiSyncId || applicationId) && ids.length),+ staleTime: 60_000,+ queryFn: async () => {+ const { data } = await apiRequest.post<{ orders: TPkiSyncCertificateOrder[] }>(+ "/api/v1/cert-manager/syncs/certificate-orders/search",+ pkiSyncId+ ? { pkiSyncId, certificateOrderIds: ids }+ : { applicationId, certificateOrderIds: ids }+ );++ return new Map(+ data.orders.map(({ certificateOrderId, commonName, altNames }) => [+ certificateOrderId,+ getCertificateDisplayName({ commonName, altNames }).originalDisplayName+ ])+ );+ }+ });+};+export const usePkiSyncOptions = (options?: Omit<UseQueryOptions<diff --git a/frontend/src/hooks/api/pkiSyncs/types/common.ts b/frontend/src/hooks/api/pkiSyncs/types/common.tsindex cb1063c5bf..e930b5951f 100644--- a/frontend/src/hooks/api/pkiSyncs/types/common.ts+++ b/frontend/src/hooks/api/pkiSyncs/types/common.ts@@ -118,9 +118,14 @@ export type TPkiSyncPreviewCertificate = {profileName?: string | null;};+export type TPkiSyncCertificateOrder = {+ certificateOrderId: string;+ commonName: string;+ altNames?: string | null;+};+export type TPkiSyncFilterPreview = {matchedCount: number;- hasMoreMatches: boolean;certificates: TPkiSyncPreviewCertificate[];toUnlink: { id: string; commonName: string; altNames?: string | null }[];willRemoveFromDestination: boolean;diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsxindex 49a3f0e7ab..ea7dba657f 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx@@ -49,7 +49,7 @@ type Props = {const getSyncUnavailableReason = (sync: TPkiSync): string | null => {if (!sync.applicationId) return "Not attached to an Application";- if (!hasAnyFilter(sync.filters)) return "No filters, so it holds nothing";+ if (!hasAnyFilter(sync.filters)) return "No filters set";if (!isCertificateOrderTheOnlyFilter(sync.filters))return "Selects certificates by profile or metadata";return null;diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCertificatesSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCertificatesSection.tsxindex 7fdea644ca..aa6c610d1b 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCertificatesSection.tsx+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCertificatesSection.tsx@@ -7,12 +7,11 @@ import {PencilIcon,RotateCwIcon,ScrollTextIcon,- Trash2Icon,TriangleAlertIcon} from "lucide-react";import { createNotification } from "@app/components/notifications";-import { isCertificateOrderTheOnlyFilter } from "@app/components/pki-syncs/forms/pki-sync-filter-fns";+import { getPkiSyncCertificateCap } from "@app/components/pki-syncs/forms/pki-sync-filter-fns";import { buildPkiSyncFilterSummary } from "@app/components/pki-syncs/PkiSyncFilterBadges";import { getCertificateDisplayName } from "@app/components/utilities/certificateDisplayUtils";import {@@ -23,7 +22,6 @@ import {CardHeader,CardTitle,CopyButton,- DeleteConfirmDialog,DropdownMenu,DropdownMenuContent,DropdownMenuItem,@@ -46,7 +44,7 @@ import {import {useClearDefaultCertificate,useListPkiSyncCertificates,- useRemoveCertificatesFromPkiSync,+ usePkiSyncCertificateOrders,useSetCertificateAsDefault} from "@app/hooks/api";import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";@@ -54,6 +52,7 @@ import {CertificateSyncStatus,PkiSync,TPkiSync,+ usePkiSyncOption,usePkiSyncPermissions} from "@app/hooks/api/pkiSyncs";@@ -101,11 +100,6 @@ const truncateSerialNumber = (serial?: string | null) => {};export const PkiSyncCertificatesSection = ({ pkiSync, onEditCertificates }: Props) => {- const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);- const [certificateToDelete, setCertificateToDelete] = useState<{- id: string;- displayName: string;- } | null>(null);const [currentPage, setCurrentPage] = useState(1);const pageSize = 10;@@ -115,7 +109,6 @@ export const PkiSyncCertificatesSection = ({ pkiSync, onEditCertificates }: Prop});const syncCertificates = data?.certificates || [];const totalCount = data?.totalCount || 0;- const removeCertificatesFromSync = useRemoveCertificatesFromPkiSync();const setCertificateAsDefault = useSetCertificateAsDefault();const clearDefaultCertificate = useClearDefaultCertificate();@@ -130,32 +123,18 @@ export const PkiSyncCertificatesSection = ({ pkiSync, onEditCertificates }: PropapplicationId: pkiSync.applicationId ?? undefined});- const { orderIdByCertificateId, orderNameById } = useMemo(() => {- const byCertificate = new Map<string, string>();- const nameByOrder = new Map<string, string>();-- syncCertificates.forEach(({ certificateId, certificateOrderId, certificateCommonName }) => {- if (!certificateOrderId) return;- byCertificate.set(certificateId, certificateOrderId);- if (certificateCommonName) nameByOrder.set(certificateOrderId, certificateCommonName);- });-- return { orderIdByCertificateId: byCertificate, orderNameById: nameByOrder };- }, [syncCertificates]);-- const explicitOrderIds = useMemo(- () => new Set(pkiSync.filters?.certificateOrderIds ?? []),- [pkiSync.filters]- );-- const canDetachOneCertificate = isCertificateOrderTheOnlyFilter(pkiSync.filters);-- const isExplicitlyNamed = (certificateId: string) => {- if (!canDetachOneCertificate) return false;+ const { data: orderNameById } = usePkiSyncCertificateOrders({+ pkiSyncId: pkiSync.id,+ certificateOrderIds: pkiSync.filters?.certificateOrderIds ?? []+ });- const orderId = orderIdByCertificateId.get(certificateId);- return Boolean(orderId && explicitOrderIds.has(orderId));- };+ const { syncOption } = usePkiSyncOption(pkiSync.destination);+ const acceptsOnlyCertificateOrders =+ getPkiSyncCertificateCap({+ destinationMaxCertificates: syncOption?.maxCertificates,+ syncOptions: pkiSync.syncOptions as Record<string, unknown> | undefined,+ destinationConfig: pkiSync.destinationConfig as Record<string, unknown> | undefined+ }) !== undefined;const filterFields = useMemo(() =>@@ -164,38 +143,12 @@ export const PkiSyncCertificatesSection = ({ pkiSync, onEditCertificates }: PropprofileNameById: new Map((profileData?.certificateProfiles ?? []).map(({ id, slug }) => [id, slug])),- orderNameById+ orderNameById: orderNameById ?? new Map<string, string>(),+ visibleKinds: acceptsOnlyCertificateOrders ? ["certificateOrderIds"] : undefined}),- [pkiSync.filters, profileData, orderNameById]+ [pkiSync.filters, profileData, orderNameById, acceptsOnlyCertificateOrders]);- const handleRemoveCertificate = async (certificateId: string) => {- try {- await removeCertificatesFromSync.mutateAsync({- pkiSyncId: pkiSync.id,- certificateIds: [certificateId]- });-- await refetchSyncCertificates();-- createNotification({- text: "Certificate removed from sync",- type: "success"- });-- setIsDeleteModalOpen(false);- setCertificateToDelete(null);- } catch {- setIsDeleteModalOpen(false);- setCertificateToDelete(null);- }- };-- const handleDeleteClick = (certificateId: string, displayName: string) => {- setCertificateToDelete({ id: certificateId, displayName });- setIsDeleteModalOpen(true);- };-const handleSetAsDefault = async (certificateId: string) => {try {await setCertificateAsDefault.mutateAsync({@@ -240,190 +193,195 @@ export const PkiSyncCertificatesSection = ({ pkiSync, onEditCertificates }: Prop};return (- <>- <Card>- <CardHeader className="border-b">- <CardTitle>Certificates</CardTitle>- <CardAction>- <IconButton- variant="ghost"- size="xs"- aria-label="Manage certificates and filters"- isDisabled={!canEdit}- onClick={onEditCertificates}- >- <PencilIcon />- </IconButton>- </CardAction>- </CardHeader>- <CardContent>- <p className="mb-2 text-xs font-medium tracking-wide text-muted uppercase">Filters</p>- {filterFields ? (- <div className="mb-4 grid grid-cols-3 gap-x-8">- {filterFields.map(({ label, value }) => (- <div key={label} className="min-w-0">- <p className="mb-1 text-xs font-medium text-muted">{label}</p>- {value}- </div>- ))}- </div>- ) : (- <p className="mb-4 text-sm text-muted">- {pkiSync.applicationId- ? "No filters, so this sync holds nothing. Edit it to select certificates."- : "This sync is not attached to an Application, so its certificates cannot be changed."}- </p>- )}- {syncCertificates.length === 0 ? (- <Empty className="border py-8">- <EmptyMedia variant="icon">- <ScrollTextIcon />- </EmptyMedia>- <EmptyTitle>No certificates are part of this certificate sync</EmptyTitle>- </Empty>- ) : (- <>- <Table>- <TableHeader>- <TableRow>- <TableHead className="w-full">SAN / CN</TableHead>- <TableHead>Certificate Status</TableHead>- <TableHead>Serial Number</TableHead>- <TableHead>External ID</TableHead>- <TableHead>Sync Status</TableHead>- <TableHead>Expires At</TableHead>- <TableHead />- </TableRow>- </TableHeader>- <TableBody>- {syncCertificates.map((syncCert) => {- const isExpired = syncCert.certificateNotAfter- ? new Date(syncCert.certificateNotAfter) < new Date()- : false;- const isRevoked = syncCert.certificateStatus === "revoked";-- const hasAutoRenewal = Boolean(- syncCert.certificateRenewBeforeDays &&- syncCert.certificateRenewBeforeDays > 0 &&- !syncCert.certificateRenewalError &&- syncCert.certificateNotAfter- );-- const daysUntilRenewal =- hasAutoRenewal && syncCert.certificateNotAfter- ? (() => {- const expiryDate = new Date(syncCert.certificateNotAfter);- const renewalDate = new Date(- expiryDate.getTime() -- syncCert.certificateRenewBeforeDays! * 24 * 60 * 60 * 1000- );- const now = new Date();- const diffInMs = renewalDate.getTime() - now.getTime();- return Math.max(0, Math.ceil(diffInMs / (24 * 60 * 60 * 1000)));- })()- : null;-- const { originalDisplayName } = getCertificateDisplayName(- {- altNames: syncCert.certificateAltNames,- commonName: syncCert.certificateCommonName- },- undefined,- "Unknown"- );-- const isDefaultCertificate = syncCert.syncMetadata?.isDefault === true;-- return (- <TableRow key={syncCert.id}>- <TableCell isTruncatable>- <div className="flex items-center gap-2">+ <Card>+ <CardHeader className="border-b">+ <CardTitle>Certificates</CardTitle>+ <CardAction>+ <IconButton+ variant="ghost"+ size="xs"+ aria-label="Manage certificates and filters"+ isDisabled={!canEdit}+ onClick={onEditCertificates}+ >+ <PencilIcon />+ </IconButton>+ </CardAction>+ </CardHeader>+ <CardContent>+ <p className="mb-2 text-xs font-medium tracking-wide text-muted uppercase">Filters</p>+ {filterFields ? (+ <div+ className="mb-4 grid gap-x-8"+ style={{ gridTemplateColumns: `repeat(${filterFields.length}, minmax(0, 1fr))` }}+ >+ {filterFields.map(({ label, value }) => (+ <div key={label} className="min-w-0">+ <p className="mb-1 text-xs font-medium text-muted">{label}</p>+ {value}+ </div>+ ))}+ </div>+ ) : (+ <p className="mb-4 text-sm text-muted">+ {pkiSync.applicationId+ ? "No filters set. Edit this sync to choose certificates."+ : "This sync is not attached to an Application, so its certificates cannot be changed."}+ </p>+ )}+ {syncCertificates.length === 0 ? (+ <Empty className="border py-8">+ <EmptyMedia variant="icon">+ <ScrollTextIcon />+ </EmptyMedia>+ <EmptyTitle>No certificates are part of this certificate sync</EmptyTitle>+ </Empty>+ ) : (+ <>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-full">SAN / CN</TableHead>+ <TableHead>Certificate Status</TableHead>+ <TableHead>Serial Number</TableHead>+ <TableHead>External ID</TableHead>+ <TableHead>Sync Status</TableHead>+ <TableHead>Expires At</TableHead>+ {supportsDefaultCertificate && <TableHead />}+ </TableRow>+ </TableHeader>+ <TableBody>+ {syncCertificates.map((syncCert) => {+ const isExpired = syncCert.certificateNotAfter+ ? new Date(syncCert.certificateNotAfter) < new Date()+ : false;+ const isRevoked = syncCert.certificateStatus === "revoked";++ const hasAutoRenewal = Boolean(+ syncCert.certificateRenewBeforeDays &&+ syncCert.certificateRenewBeforeDays > 0 &&+ !syncCert.certificateRenewalError &&+ syncCert.certificateNotAfter+ );++ const daysUntilRenewal =+ hasAutoRenewal && syncCert.certificateNotAfter+ ? (() => {+ const expiryDate = new Date(syncCert.certificateNotAfter);+ const renewalDate = new Date(+ expiryDate.getTime() -+ syncCert.certificateRenewBeforeDays! * 24 * 60 * 60 * 1000+ );+ const now = new Date();+ const diffInMs = renewalDate.getTime() - now.getTime();+ return Math.max(0, Math.ceil(diffInMs / (24 * 60 * 60 * 1000)));+ })()+ : null;++ const { originalDisplayName } = getCertificateDisplayName(+ {+ altNames: syncCert.certificateAltNames,+ commonName: syncCert.certificateCommonName+ },+ undefined,+ "Unknown"+ );++ const isDefaultCertificate = syncCert.syncMetadata?.isDefault === true;++ return (+ <TableRow key={syncCert.id}>+ <TableCell isTruncatable>+ <div className="flex items-center gap-2">+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="truncate">{originalDisplayName}</span>+ </TooltipTrigger>+ <TooltipContent className="max-w-lg break-words">+ {originalDisplayName}+ </TooltipContent>+ </Tooltip>+ {supportsDefaultCertificate && isDefaultCertificate && (+ <Badge variant="neutral">Default</Badge>+ )}+ </div>+ </TableCell>+ <TableCell>+ <Badge variant={getCertificateStatusVariant(isExpired, isRevoked)}>+ {getCertificateStatusText(isExpired, isRevoked)}+ </Badge>+ </TableCell>+ <TableCell isTruncatable>+ <div+ className="truncate"+ title={syncCert.certificateSerialNumber || "Unknown"}+ >+ {truncateSerialNumber(syncCert.certificateSerialNumber)}+ </div>+ </TableCell>+ <TableCell isTruncatable>+ {syncCert.externalIdentifier ? (+ <div className="flex items-center gap-1"><Tooltip><TooltipTrigger asChild>- <span className="truncate">{originalDisplayName}</span>+ <span className="truncate">{syncCert.externalIdentifier}</span></TooltipTrigger>- <TooltipContent className="max-w-lg break-words">- {originalDisplayName}+ <TooltipContent className="max-w-none whitespace-nowrap">+ {syncCert.externalIdentifier}</TooltipContent></Tooltip>- {supportsDefaultCertificate && isDefaultCertificate && (- <Badge variant="neutral">Default</Badge>- )}+ <CopyButton+ value={syncCert.externalIdentifier}+ ariaLabel="Copy external identifier"+ /></div>- </TableCell>- <TableCell>- <Badge variant={getCertificateStatusVariant(isExpired, isRevoked)}>- {getCertificateStatusText(isExpired, isRevoked)}+ ) : (+ <span className="text-muted">-</span>+ )}+ </TableCell>+ <TableCell>+ {syncCert.lastSyncMessage &&+ syncCert.syncStatus === CertificateSyncStatus.Failed ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="inline-block">+ <Badge variant="danger">+ <TriangleAlertIcon />+ Failed+ </Badge>+ </span>+ </TooltipTrigger>+ <TooltipContent>{syncCert.lastSyncMessage}</TooltipContent>+ </Tooltip>+ ) : (+ <Badge variant={getSyncStatusVariant(syncCert.syncStatus)}>+ {getSyncStatusIcon(syncCert.syncStatus)}+ {getSyncStatusText(syncCert.syncStatus)}</Badge>- </TableCell>- <TableCell isTruncatable>- <div- className="truncate"- title={syncCert.certificateSerialNumber || "Unknown"}- >- {truncateSerialNumber(syncCert.certificateSerialNumber)}- </div>- </TableCell>- <TableCell isTruncatable>- {syncCert.externalIdentifier ? (- <div className="flex items-center gap-1">- <Tooltip>- <TooltipTrigger asChild>- <span className="truncate">{syncCert.externalIdentifier}</span>- </TooltipTrigger>- <TooltipContent className="max-w-none whitespace-nowrap">- {syncCert.externalIdentifier}- </TooltipContent>- </Tooltip>- <CopyButton- value={syncCert.externalIdentifier}- ariaLabel="Copy external identifier"- />- </div>- ) : (- <span className="text-muted">-</span>- )}- </TableCell>- <TableCell>- {syncCert.lastSyncMessage &&- syncCert.syncStatus === CertificateSyncStatus.Failed ? (+ )}+ </TableCell>+ <TableCell>+ <div className="flex items-center gap-1.5">+ <span className={isExpired ? "text-danger" : undefined}>+ {syncCert.certificateNotAfter+ ? new Date(syncCert.certificateNotAfter).toLocaleDateString()+ : "Unknown"}+ </span>+ {hasAutoRenewal && daysUntilRenewal !== null && (<Tooltip><TooltipTrigger asChild>- <span className="inline-block">- <Badge variant="danger">- <TriangleAlertIcon />- Failed- </Badge>+ <span className="inline-block text-accent">+ <HistoryIcon className="size-3.5" /></span></TooltipTrigger>- <TooltipContent>{syncCert.lastSyncMessage}</TooltipContent>+ <TooltipContent>Auto-renews in {daysUntilRenewal}d</TooltipContent></Tooltip>- ) : (- <Badge variant={getSyncStatusVariant(syncCert.syncStatus)}>- {getSyncStatusIcon(syncCert.syncStatus)}- {getSyncStatusText(syncCert.syncStatus)}- </Badge>)}- </TableCell>- <TableCell>- <span className={isExpired ? "text-danger" : undefined}>- {syncCert.certificateNotAfter- ? new Date(syncCert.certificateNotAfter).toLocaleDateString()- : "Unknown"}- </span>- </TableCell>+ </div>+ </TableCell>+ {supportsDefaultCertificate && (<TableCell>- <div className="flex items-center justify-end gap-2">- {hasAutoRenewal && daysUntilRenewal !== null && (- <Tooltip>- <TooltipTrigger asChild>- <span className="inline-block text-accent">- <HistoryIcon className="size-3.5" />- </span>- </TooltipTrigger>- <TooltipContent>Auto-renews in {daysUntilRenewal}d</TooltipContent>- </Tooltip>- )}+ <div className="flex items-center justify-end"><DropdownMenu><DropdownMenuTrigger asChild><IconButton@@ -436,74 +394,40 @@ export const PkiSyncCertificatesSection = ({ pkiSync, onEditCertificates }: Prop</IconButton></DropdownMenuTrigger><DropdownMenuContent align="end">- {supportsDefaultCertificate && !isDefaultCertificate && (- <DropdownMenuItem- onClick={() => handleSetAsDefault(syncCert.certificateId)}- >- Set as Default- </DropdownMenuItem>- )}- {supportsDefaultCertificate && isDefaultCertificate && (+ {isDefaultCertificate ? (<DropdownMenuItem onClick={handleClearDefault}>Unset Default</DropdownMenuItem>- )}- {isExplicitlyNamed(syncCert.certificateId) ? (+ ) : (<DropdownMenuItem- variant="danger"- onClick={() =>- handleDeleteClick(syncCert.certificateId, originalDisplayName)- }+ onClick={() => handleSetAsDefault(syncCert.certificateId)}>- <Trash2Icon />- Remove from Sync- </DropdownMenuItem>- ) : (- <DropdownMenuItem onClick={onEditCertificates}>- <Trash2Icon />- Edit Filters to Remove+ Set as Default</DropdownMenuItem>)}</DropdownMenuContent></DropdownMenu></div></TableCell>- </TableRow>- );- })}- </TableBody>- </Table>- {totalCount > pageSize && (- <Pagination- className="mt-4"- count={totalCount}- page={currentPage}- perPage={pageSize}- onChangePage={(page: number) => setCurrentPage(page)}- onChangePerPage={() => {}}- />- )}- </>- )}- </CardContent>- </Card>-- <DeleteConfirmDialog- isOpen={isDeleteModalOpen}- onOpenChange={(isOpen) => {- setIsDeleteModalOpen(isOpen);- if (!isOpen) setCertificateToDelete(null);- }}- title="Remove Certificate from Sync"- description={`Are you sure you want to remove "${certificateToDelete?.displayName}" from this certificate sync?`}- confirmKey="confirm"- onConfirm={async () => {- if (certificateToDelete) {- await handleRemoveCertificate(certificateToDelete.id);- }- }}- confirmLabel="Remove Certificate"- />- </>+ )}+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ {totalCount > pageSize && (+ <Pagination+ className="mt-4"+ count={totalCount}+ page={currentPage}+ perPage={pageSize}+ onChangePage={(page: number) => setCurrentPage(page)}+ onChangePerPage={() => {}}+ />+ )}+ </>+ )}+ </CardContent>+ </Card>);};