Skip to content

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

feat(pki-syncs): choose sync certificates by filter

Carlos Monastyrskif29460391bf0
diff --git a/backend/src/db/migrations/20260910091447_pki-sync-filters.ts b/backend/src/db/migrations/20260910091447_pki-sync-filters.ts
new file mode 100644
index 0000000000..0b4f38ced9
--- /dev/null
+++ b/backend/src/db/migrations/20260910091447_pki-sync-filters.ts
@@ -0,0 +1,39 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ const hasFilters = await knex.schema.hasColumn(TableName.PkiSync, "filters");
+
+ if (!hasFilters) {
+ await knex.schema.alterTable(TableName.PkiSync, (t) => {
+ t.jsonb("filters").nullable();
+ });
+ }
+
+ await knex.raw(`
+ UPDATE "${TableName.PkiSync}" AS s
+ SET "filters" = jsonb_build_object(
+ 'certificateOrderIds',
+ COALESCE(
+ (
+ SELECT jsonb_agg(DISTINCT c."orderId")
+ FROM "${TableName.CertificateSync}" cs
+ JOIN "${TableName.Certificate}" c ON c.id = cs."certificateId"
+ WHERE cs."pkiSyncId" = s.id
+ ),
+ '[]'::jsonb
+ )
+ )
+ WHERE s."filters" IS NULL AND s."applicationId" IS NOT NULL
+ `);
+}
+
+export async function down(knex: Knex): Promise<void> {
+ const hasFilters = await knex.schema.hasColumn(TableName.PkiSync, "filters");
+ if (hasFilters) {
+ await knex.schema.alterTable(TableName.PkiSync, (t) => {
+ t.dropColumn("filters");
+ });
+ }
+}
diff --git a/backend/src/db/schemas/pki-syncs.ts b/backend/src/db/schemas/pki-syncs.ts
index dcf5403576..f25122746b 100644
--- a/backend/src/db/schemas/pki-syncs.ts
+++ b/backend/src/db/schemas/pki-syncs.ts
@@ -39,7 +39,8 @@ export const PkiSyncsSchema = z.object({
encryptedCredentials: zodBuffer.nullable().optional(),
lastHealthCheckRanAt: z.date().nullable().optional(),
lastHealthCheckStatus: z.string().nullable().optional(),
- lastHealthCheckMessage: z.string().nullable().optional()
+ lastHealthCheckMessage: z.string().nullable().optional(),
+ filters: z.unknown().nullable().optional()
});
export type TPkiSyncs = z.infer<typeof PkiSyncsSchema>;
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 01fbf13473..6e1928e450 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -46,6 +46,7 @@ import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types
import { PkiItemType } from "@app/services/pki-collection/pki-collection-types";
import { THealthCheckCommandResult } from "@app/services/pki-sync/pki-sync-health-check-command-fns";
import { TPostSyncCommandResult } from "@app/services/pki-sync/pki-sync-post-sync-command-fns";
+import { TPkiSyncFilters } from "@app/services/pki-sync/pki-sync-types";
import { SecretSync, SecretSyncImportBehavior } from "@app/services/secret-sync/secret-sync-enums";
import {
TCreateSecretSyncDTO,
@@ -586,6 +587,9 @@ export enum EventType {
PKI_SYNC_REMOVE_CERTIFICATES = "pki-sync-remove-certificates",
PKI_SYNC_HEALTH_CHECK = "pki-sync-health-check",
PKI_SYNC_TEST_HEALTH_CHECK = "pki-sync-test-health-check",
+ PKI_SYNC_LINK_CERTIFICATES = "pki-sync-link-certificates",
+ PKI_SYNC_UNLINK_CERTIFICATES = "pki-sync-unlink-certificates",
+ PKI_SYNC_SKIP_CERTIFICATE = "pki-sync-skip-certificate",
PKI_SYNC_SET_DEFAULT_CERTIFICATE = "pki-sync-set-default-certificate",
PKI_SYNC_CLEAR_DEFAULT_CERTIFICATE = "pki-sync-clear-default-certificate",
OIDC_GROUP_MEMBERSHIP_MAPPING_ASSIGN_USER = "oidc-group-membership-mapping-assign-user",
@@ -4579,6 +4583,7 @@ interface CreatePkiSyncEvent {
hasCredentials?: boolean;
hasPostSyncCommand?: boolean;
hasHealthCheckCommand?: boolean;
+ hasFilters?: boolean;
};
}
@@ -4594,6 +4599,7 @@ interface UpdatePkiSyncEvent {
targetHost?: string;
hasPostSyncCommand?: boolean;
hasHealthCheckCommand?: boolean;
+ hasFilters?: boolean;
};
}
@@ -4661,6 +4667,42 @@ interface PkiSyncRemoveCertificatesEvent {
};
}
+interface PkiSyncLinkCertificatesEvent {
+ type: EventType.PKI_SYNC_LINK_CERTIFICATES;
+ metadata: {
+ pkiSyncId: string;
+ name: string;
+ count: number;
+ certificates: { id: string; commonName: string }[];
+ filters?: TPkiSyncFilters;
+ applicationId?: string;
+ };
+}
+
+interface PkiSyncUnlinkCertificatesEvent {
+ type: EventType.PKI_SYNC_UNLINK_CERTIFICATES;
+ metadata: {
+ pkiSyncId: string;
+ name: string;
+ count: number;
+ certificates: { id: string; commonName: string }[];
+ removedFromDestination?: boolean;
+ applicationId?: string;
+ };
+}
+
+interface PkiSyncSkipCertificateEvent {
+ type: EventType.PKI_SYNC_SKIP_CERTIFICATE;
+ metadata: {
+ pkiSyncId: string;
+ name: string;
+ certificateId: string;
+ commonName: string;
+ reason: string;
+ applicationId?: string;
+ };
+}
+
interface PkiSyncSetDefaultCertificateEvent {
type: EventType.PKI_SYNC_SET_DEFAULT_CERTIFICATE;
metadata: {
@@ -7685,6 +7727,9 @@ export type Event =
| PkiSyncHealthCheckEvent
| PkiSyncTestHealthCheckEvent
| PkiSyncRemoveCertificatesEvent
+ | PkiSyncLinkCertificatesEvent
+ | PkiSyncUnlinkCertificatesEvent
+ | PkiSyncSkipCertificateEvent
| PkiSyncSetDefaultCertificateEvent
| PkiSyncClearDefaultCertificateEvent
| CreatePkiDiscoveryEvent
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index a04df5a307..e782330928 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -58,6 +58,7 @@ export const KeyStorePrefixes = {
`sync-integration-last-run-${projectId}-${environmentSlug}-${secretPath}` as const,
SecretSyncLock: (syncId: string) => `secret-sync-mutex-${syncId}` as const,
PkiSyncLock: (syncId: string) => `pki-sync-mutex-${syncId}` as const,
+ PkiSyncFilterLock: (syncId: string) => `pki-sync-filter-mutex-${syncId}` as const,
AppConnectionConcurrentJobs: (connectionId: string, targetHost?: string) =>
`app-connection-concurrency-${connectionId}${targetHost ? `-${targetHost.toLowerCase()}` : ""}` as const,
AppConnectionCommandLock: (connectionId: string, targetHost?: string) =>
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index aef689061c..4b87ddbc70 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -4183,3 +4183,19 @@ export const ENCRYPTION_KEY_ROTATION = {
"Remove the key even though an instance started on it recently. This overrides only that check: a label that does not match the key currently held still fails. Any instance still using that key will fail its next restart until it is given the new one."
}
};
+
+export const PKI_SYNC_FILTERS = {
+ filters:
+ "Which of the Application's certificates this sync holds. A certificate must match every field that is set, and a sync with no filters holds nothing.",
+ updateFilters:
+ "Replaces which of the Application's certificates this sync holds. Omit to leave them unchanged, or set to null to empty the sync.",
+ profileIds: "Match certificates issued from any one of these certificate profiles.",
+ certificateOrderIds:
+ "Match any certificate belonging to any one of these certificate orders. An order groups a certificate with every renewal of it, so this keeps matching as the certificate is renewed.",
+ metadata:
+ "Match certificates carrying every one of these metadata pairs. Give a key on its own to match any value for that key.",
+ 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."
+};
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 53c6101a40..2122fb385c 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -49,6 +49,7 @@ import { TCreateUserNotificationDTO } from "@app/services/notification/notificat
import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types";
import {
TQueuePkiSyncImportCertificatesByIdDTO,
+ TQueuePkiSyncLinkMatchingCertificatesDTO,
TQueuePkiSyncRemoveCertificatesByIdDTO,
TQueuePkiSyncRunHealthCheckByIdDTO,
TQueuePkiSyncSyncCertificatesByIdDTO
@@ -157,6 +158,7 @@ export enum QueueJobs {
SecretSyncRemoveSecrets = "secret-sync-remove-secrets",
SecretSyncSendActionFailedNotifications = "secret-sync-send-action-failed-notifications",
PkiSyncSyncCertificates = "pki-sync-sync-certificates",
+ PkiSyncLinkMatchingCertificates = "pki-sync-link-matching-certificates",
PkiSyncImportCertificates = "pki-sync-import-certificates",
PkiSyncRemoveCertificates = "pki-sync-remove-certificates",
PkiSyncRunHealthCheck = "pki-sync-run-health-check",
@@ -364,6 +366,10 @@ export type TQueueJobTypes = {
| {
name: QueueJobs.PkiSyncRemoveCertificates;
payload: TQueuePkiSyncRemoveCertificatesByIdDTO;
+ }
+ | {
+ name: QueueJobs.PkiSyncLinkMatchingCertificates;
+ payload: TQueuePkiSyncLinkMatchingCertificatesDTO;
};
[QueueName.PkiSyncHealthCheck]: {
name: QueueJobs.PkiSyncRunHealthCheck;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index f2f2e27032..54bda804b7 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -3311,6 +3311,7 @@ export const registerRoutes = async (
const pkiSyncCleanup = pkiSyncCleanupQueueServiceFactory({
cronJob,
pkiSyncDAL,
+ certificateSyncDAL,
pkiSyncQueue
});
@@ -3508,6 +3509,7 @@ export const registerRoutes = async (
pkiCollectionDAL,
pkiCollectionItemDAL,
certificateSyncDAL,
+ auditLogService,
pkiSyncDAL,
pkiSyncQueue,
certificateAuthorityService,
@@ -3593,7 +3595,8 @@ export const registerRoutes = async (
certificateIssuanceQueue,
resourceMetadataDAL,
pkiApplicationProfileDAL,
- apiEnrollmentConfigDAL
+ apiEnrollmentConfigDAL,
+ pkiSyncQueue
});
const approvalPolicyService = approvalPolicyServiceFactory({
@@ -3800,10 +3803,13 @@ export const registerRoutes = async (
appConnectionService,
permissionService,
licenseService,
+ keyStore,
pkiSyncQueue,
pkiSyncHealthCheckQueue,
auditLogService,
- kmsService
+ kmsService,
+ pkiApplicationProfileDAL,
+ pkiApplicationDAL
});
const pkiDiscoveryQueue = pkiDiscoveryQueueFactory({
diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.ts
index 17464fce15..8d43196227 100644
--- a/backend/src/server/routes/v1/certificate-router.ts
+++ b/backend/src/server/routes/v1/certificate-router.ts
@@ -1795,7 +1795,8 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
+ actorOrgId: req.permission.orgId,
+ auditLogInfo: req.auditLogInfo
});
await server.services.auditLog.createAuditLog({
diff --git a/backend/src/server/routes/v1/deprecated-certificate-router.ts b/backend/src/server/routes/v1/deprecated-certificate-router.ts
index 05559f67e4..052d0c53a0 100644
--- a/backend/src/server/routes/v1/deprecated-certificate-router.ts
+++ b/backend/src/server/routes/v1/deprecated-certificate-router.ts
@@ -544,7 +544,8 @@ export const registerDeprecatedCertRouter = async (server: FastifyZodProvider) =
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
+ actorOrgId: req.permission.orgId,
+ auditLogInfo: req.auditLogInfo
});
await server.services.auditLog.createAuditLog({
diff --git a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts
index 7afcc2982d..9bd8667d91 100644
--- a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts
+++ b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts
@@ -10,6 +10,7 @@ import { AuthMode } from "@app/services/auth/auth-type";
import { PkiSync, PkiSyncStatus } from "@app/services/pki-sync/pki-sync-enums";
import { PKI_SYNC_NAME_MAP } from "@app/services/pki-sync/pki-sync-maps";
import { getPkiSyncTargetHost } from "@app/services/pki-sync/pki-sync-target-host-fns";
+import { TPkiSyncFilters } from "@app/services/pki-sync/pki-sync-types";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
export const registerSyncPkiEndpoints = ({
@@ -35,6 +36,7 @@ export const registerSyncPkiEndpoints = ({
description?: string;
isAutoSyncEnabled?: boolean;
subscriberId?: string | null;
+ filters?: TPkiSyncFilters | null;
}>;
updateSchema: z.ZodType<{
connectionId?: string;
@@ -44,12 +46,14 @@ export const registerSyncPkiEndpoints = ({
description?: string;
isAutoSyncEnabled?: boolean;
subscriberId?: string | null;
+ filters?: TPkiSyncFilters | null;
}>;
healthCheckTestSchema?: z.ZodType<{
connectionId: string;
applicationId?: string;
syncId?: string;
certificateIds?: string[];
+ filters?: TPkiSyncFilters | null;
destinationConfig: Record<string, unknown>;
syncOptions: Record<string, unknown>;
}>;
@@ -169,7 +173,12 @@ export const registerSyncPkiEndpoints = ({
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
handler: async (req) => {
const pkiSync = await server.services.pkiSync.createPkiSync(
- { ...req.body, projectId: req.body.projectId ?? req.internalCertManagerProjectId, destination },
+ {
+ ...req.body,
+ projectId: req.body.projectId ?? req.internalCertManagerProjectId,
+ destination,
+ auditLogInfo: req.auditLogInfo
+ },
req.permission
);
@@ -190,6 +199,7 @@ export const registerSyncPkiEndpoints = ({
hasCredentials: Boolean(req.body.credentials?.exportPassword),
hasPostSyncCommand: Boolean(req.body.syncOptions?.postSyncCommand),
hasHealthCheckCommand: Boolean(req.body.syncOptions?.healthCheckCommand),
+ hasFilters: Boolean(req.body.filters),
...(pkiSync.applicationId && { applicationId: pkiSync.applicationId })
}
}
@@ -234,7 +244,10 @@ export const registerSyncPkiEndpoints = ({
handler: async (req) => {
const { pkiSyncId } = req.params;
- const pkiSync = await server.services.pkiSync.updatePkiSync({ ...req.body, id: pkiSyncId }, req.permission);
+ const pkiSync = await server.services.pkiSync.updatePkiSync(
+ { ...req.body, id: pkiSyncId, auditLogInfo: req.auditLogInfo },
+ req.permission
+ );
const targetHost = getPkiSyncTargetHost(pkiSync.destinationConfig);
@@ -252,7 +265,8 @@ export const registerSyncPkiEndpoints = ({
connectionName: pkiSync.appConnectionName,
...(targetHost && { targetHost }),
hasPostSyncCommand: Boolean(pkiSync.syncOptions?.postSyncCommand),
- hasHealthCheckCommand: Boolean(pkiSync.syncOptions?.healthCheckCommand)
+ hasHealthCheckCommand: Boolean(pkiSync.syncOptions?.healthCheckCommand),
+ hasFilters: Boolean(pkiSync.filters)
}
}
});
@@ -364,6 +378,7 @@ export const registerSyncPkiEndpoints = ({
applicationId: req.body.applicationId,
syncId: req.body.syncId,
certificateIds: req.body.certificateIds,
+ filters: req.body.filters,
destinationConfig: req.body.destinationConfig,
syncOptions: req.body.syncOptions,
projectId: req.internalCertManagerProjectId
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.ts
index f466fcc443..b4188e0abd 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
@@ -1,7 +1,7 @@
import { z } from "zod";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { ApiDocsTags } from "@app/lib/api-docs";
+import { ApiDocsTags, PKI_SYNC_FILTERS } from "@app/lib/api-docs";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { openApiHidden } from "@app/server/lib/schemas";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
@@ -10,6 +10,16 @@ import { AuthMode } from "@app/services/auth/auth-type";
import { CertificateSyncStatus } from "@app/services/certificate-sync/certificate-sync-enums";
import { SyncMetadataSchema } from "@app/services/certificate-sync/certificate-sync-schemas";
import { PkiSync, PkiSyncStatus } from "@app/services/pki-sync/pki-sync-enums";
+import { PkiSyncFiltersField, PkiSyncStoredFiltersField } from "@app/services/pki-sync/pki-sync-schemas";
+
+const PkiSyncCertificateRefSchema = z.object({
+ id: z.string().uuid(),
+ commonName: z.string(),
+ serialNumber: z.string().optional(),
+ notAfter: z.date().optional(),
+ orderId: z.string().uuid().optional(),
+ profileName: z.string().nullable().optional()
+});
export const PkiSyncSchema = z.object({
id: z.string().uuid(),
@@ -68,7 +78,8 @@ export const PkiSyncSchema = z.object({
})
.nullable()
.optional(),
- hasCertificate: z.boolean().optional()
+ hasCertificate: z.boolean().optional(),
+ filters: PkiSyncStoredFiltersField
});
const PkiSyncOptionsSchema = z.object({
@@ -99,6 +110,7 @@ const PkiSyncCertificateSchema = z.object({
updatedAt: z.date(),
certificateSerialNumber: z.string().optional(),
certificateCommonName: z.string().optional(),
+ certificateOrderId: z.string().uuid().optional(),
certificateAltNames: z.string().optional(),
certificateStatus: z.string().optional(),
certificateNotBefore: z.date().optional(),
@@ -279,6 +291,47 @@ export const registerPkiSyncRouter = async (server: FastifyZodProvider, enableOp
}
});
+ server.route({
+ method: "POST",
+ url: "/certificates/preview",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ ...(enableOperationId ? { operationId: "previewPkiSyncFilters" } : {}),
+ tags: [ApiDocsTags.PkiSyncs],
+ description: "Preview 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
+ })
+ .refine((body) => Boolean(body.pkiSyncId) !== Boolean(body.applicationId), {
+ message: "Provide either pkiSyncId or applicationId."
+ }),
+ response: {
+ 200: z.object({
+ matchedCount: z.number(),
+ hasMoreMatches: z.boolean(),
+ certificates: PkiSyncCertificateRefSchema.array(),
+ toUnlink: PkiSyncCertificateRefSchema.array(),
+ willRemoveFromDestination: z.boolean()
+ })
+ }
+ },
+ onRequest: 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 },
+ req.permission
+ );
+
+ return preview;
+ }
+ });
+
server.route({
method: "POST",
url: "/:pkiSyncId/certificates",
@@ -318,24 +371,11 @@ export const registerPkiSyncRouter = async (server: FastifyZodProvider, enableOp
const { pkiSyncId } = req.params;
const { certificateIds } = req.body;
- const { addedCertificates, pkiSyncInfo } = await server.services.pkiSync.addCertificatesToPkiSync(
- { pkiSyncId, certificateIds },
+ const { addedCertificates } = await server.services.pkiSync.addCertificatesToPkiSync(
+ { pkiSyncId, certificateIds, auditLogInfo: req.auditLogInfo },
req.permission
);
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- projectId: pkiSyncInfo.projectId,
- event: {
- type: EventType.UPDATE_PKI_SYNC,
- metadata: {
- pkiSyncId,
- name: pkiSyncInfo.name,
- ...(pkiSyncInfo.applicationId && { applicationId: pkiSyncInfo.applicationId })
- }
- }
- });
-
return { addedCertificates };
}
});
@@ -368,24 +408,11 @@ export const registerPkiSyncRouter = async (server: FastifyZodProvider, enableOp
const { pkiSyncId } = req.params;
const { certificateIds } = req.body;
- const { removedCount, pkiSyncInfo } = await server.services.pkiSync.removeCertificatesFromPkiSync(
- { pkiSyncId, certificateIds },
+ const { removedCount } = await server.services.pkiSync.removeCertificatesFromPkiSync(
+ { pkiSyncId, certificateIds, auditLogInfo: req.auditLogInfo },
req.permission
);
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- projectId: pkiSyncInfo.projectId,
- event: {
- type: EventType.UPDATE_PKI_SYNC,
- metadata: {
- pkiSyncId,
- name: pkiSyncInfo.name,
- ...(pkiSyncInfo.applicationId && { applicationId: pkiSyncInfo.applicationId })
- }
- }
- });
-
return { removedCount };
}
});
diff --git a/backend/src/services/certificate-authority/certificate-issuance-queue.ts b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
index 0d3cdd36ba..df4bc4d952 100644
--- a/backend/src/services/certificate-authority/certificate-issuance-queue.ts
+++ b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
@@ -46,7 +46,11 @@ import { TPkiApplicationProfileDALFactory } from "../pki-application/pki-applica
import { TPkiSubscriberDALFactory } from "../pki-subscriber/pki-subscriber-dal";
import { TPkiSyncDALFactory } from "../pki-sync/pki-sync-dal";
import { TPkiSyncQueueFactory } from "../pki-sync/pki-sync-queue";
-import { addRenewedCertificateToSyncs, triggerAutoSyncForCertificate } from "../pki-sync/pki-sync-utils";
+import {
+ addRenewedCertificateToSyncs,
+ queueCertificateFilterReconcile,
+ triggerAutoSyncForCertificate
+} from "../pki-sync/pki-sync-utils";
import { TResourceMetadataDALFactory } from "../resource-metadata/resource-metadata-dal";
import { copyMetadataFromRequestToCertificate } from "../resource-metadata/resource-metadata-fns";
import { runWithAcmeCancellation } from "./acme/acme-cancellation";
@@ -160,10 +164,14 @@ type TCertificateIssuanceQueueFactoryDep = {
queueService: TQueueServiceFactory;
pkiSubscriberDAL: Pick<TPkiSubscriberDALFactory, "findById" | "updateById">;
pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;
- pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;
+ pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById" | "queuePkiSyncLinkMatchingCertificates">;
certificateSyncDAL: Pick<
TCertificateSyncDALFactory,
- "findPkiSyncIdsByCertificateId" | "addCertificates" | "findByPkiSyncAndCertificate" | "updateSyncMetadata"
+ | "findPkiSyncIdsByCertificateId"
+ | "addCertificates"
+ | "findByPkiSyncAndCertificate"
+ | "updateSyncMetadata"
+ | "primaryNode"
>;
certificateProfileDAL?: Pick<TCertificateProfileDALFactory, "findById" | "findByIdWithConfigs">;
certificateRequestService?: Pick<
@@ -1131,16 +1139,18 @@ export const certificateIssuanceQueueFactory = ({
);
let scopedApplicationId: string | null = data.applicationId ?? null;
+ let issuedCertificateId: string | null | undefined;
try {
if (!scopedApplicationId && isRenewal && originalCertificateId) {
const orig = await certificateDAL.findById(originalCertificateId);
scopedApplicationId = orig?.applicationId ?? null;
}
- if (scopedApplicationId && certificateRequestId && certificateRequestDAL) {
- const req = await certificateRequestDAL.findById(certificateRequestId);
- if (req?.certificateId) {
- await certificateDAL.updateById(req.certificateId, { applicationId: scopedApplicationId });
- }
+ issuedCertificateId =
+ certificateRequestId && certificateRequestDAL
+ ? (await certificateRequestDAL.findById(certificateRequestId))?.certificateId
+ : certificateId;
+ if (scopedApplicationId && issuedCertificateId) {
+ await certificateDAL.updateById(issuedCertificateId, { applicationId: scopedApplicationId });
}
} catch (stampErr) {
logger.warn(
@@ -1150,28 +1160,25 @@ export const certificateIssuanceQueueFactory = ({
}
try {
- if (scopedApplicationId && profileId && certificateProfileDAL && certificateRequestDAL) {
- const req = await certificateRequestDAL.findById(certificateRequestId!);
- if (req?.certificateId) {
- const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
- if (profile) {
- const effectiveApiConfig = await resolveEffectiveApiConfig({
- applicationId: scopedApplicationId,
- profileId,
- profileApiConfig: profile.apiConfig,
- pkiApplicationProfileDAL,
- apiEnrollmentConfigDAL
- });
- const cert = await certificateDAL.findById(req.certificateId);
- if (cert && !cert.renewBeforeDays) {
- const finalRenewBeforeDays = calculateFinalRenewBeforeDays(
- { apiConfig: effectiveApiConfig },
- ttl,
- new Date(cert.notAfter)
- );
- if (finalRenewBeforeDays !== undefined) {
- await certificateDAL.updateById(req.certificateId, { renewBeforeDays: finalRenewBeforeDays });
- }
+ if (scopedApplicationId && profileId && certificateProfileDAL && issuedCertificateId) {
+ const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
+ if (profile) {
+ const effectiveApiConfig = await resolveEffectiveApiConfig({
+ applicationId: scopedApplicationId,
+ profileId,
+ profileApiConfig: profile.apiConfig,
+ pkiApplicationProfileDAL,
+ apiEnrollmentConfigDAL
+ });
+ const cert = await certificateDAL.findById(issuedCertificateId);
+ if (cert && !cert.renewBeforeDays) {
+ const finalRenewBeforeDays = calculateFinalRenewBeforeDays(
+ { apiConfig: effectiveApiConfig },
+ ttl,
+ new Date(cert.notAfter)
+ );
+ if (finalRenewBeforeDays !== undefined) {
+ await certificateDAL.updateById(issuedCertificateId, { renewBeforeDays: finalRenewBeforeDays });
}
}
}
@@ -1184,21 +1191,28 @@ export const certificateIssuanceQueueFactory = ({
}
try {
- if (isRenewal && originalCertificateId && certificateRequestId && certificateRequestDAL) {
- const req = await certificateRequestDAL.findById(certificateRequestId);
- if (req?.certificateId) {
- await addRenewedCertificateToSyncs(originalCertificateId, req.certificateId, { certificateSyncDAL });
- await triggerAutoSyncForCertificate(req.certificateId, {
- certificateSyncDAL,
- pkiSyncDAL,
- pkiSyncQueue
- });
+ if (isRenewal && originalCertificateId && issuedCertificateId) {
+ await addRenewedCertificateToSyncs(originalCertificateId, issuedCertificateId, { certificateSyncDAL });
+ await triggerAutoSyncForCertificate(issuedCertificateId, {
+ certificateSyncDAL,
+ pkiSyncDAL,
+ pkiSyncQueue
+ });
+ }
+
+ if (issuedCertificateId && scopedApplicationId) {
+ await queueCertificateFilterReconcile(issuedCertificateId, scopedApplicationId, pkiSyncQueue);
+
+ if (isRenewal && originalCertificateId) {
+ await queueCertificateFilterReconcile(originalCertificateId, scopedApplicationId, pkiSyncQueue);
}
}
} catch (syncErr) {
logger.warn(
syncErr,
- `Failed to link renewed certificate to PKI syncs [originalCertificateId=${originalCertificateId}] [certificateRequestId=${certificateRequestId}]`
+ `Failed to link certificate to PKI syncs [isRenewal=${String(isRenewal)}] [originalCertificateId=${
+ originalCertificateId ?? "none"
+ }] [certificateRequestId=${certificateRequestId}]`
);
}
diff --git a/backend/src/services/certificate-sync/certificate-sync-dal.ts b/backend/src/services/certificate-sync/certificate-sync-dal.ts
index af37f7ac88..ba8b9d13dd 100644
--- a/backend/src/services/certificate-sync/certificate-sync-dal.ts
+++ b/backend/src/services/certificate-sync/certificate-sync-dal.ts
@@ -4,6 +4,7 @@ import { TDbClient } from "@app/db";
import { TableName, TCertificateSyncs } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { buildFindFilter, ormify, selectAllTableCols } from "@app/lib/knex";
+import { CertStatus } from "@app/services/certificate/certificate-types";
import { CertificateSyncStatus } from "./certificate-sync-enums";
@@ -48,6 +49,33 @@ export const certificateSyncDALFactory = (db: TDbClient) => {
}
};
+ const findIneligibleFilteredLinks = async (
+ limit: number
+ ): Promise<Array<{ certificateId: string; applicationId: string }>> => {
+ try {
+ const docs = (await db
+ .replicaNode()(TableName.CertificateSync)
+ .join(TableName.Certificate, `${TableName.Certificate}.id`, `${TableName.CertificateSync}.certificateId`)
+ .join(TableName.PkiSync, `${TableName.PkiSync}.id`, `${TableName.CertificateSync}.pkiSyncId`)
+ .whereNotNull(`${TableName.PkiSync}.applicationId`)
+ .whereNotNull(`${TableName.PkiSync}.filters`)
+ .where((qb) => {
+ void qb
+ .whereNot(`${TableName.Certificate}.status`, CertStatus.ACTIVE)
+ .orWhere(`${TableName.Certificate}.notAfter`, "<=", new Date())
+ .orWhereNotNull(`${TableName.Certificate}.renewedByCertificateId`);
+ })
+ .select(`${TableName.CertificateSync}.certificateId`, `${TableName.PkiSync}.applicationId`)
+ .groupBy(`${TableName.CertificateSync}.certificateId`, `${TableName.PkiSync}.applicationId`)
+ .orderByRaw(`min(??) asc`, [`${TableName.CertificateSync}.updatedAt`])
+ .limit(limit)) as Array<{ certificateId: string; applicationId: string }>;
+
+ return docs;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindIneligibleFilteredLinks" });
+ }
+ };
+
const findCertificateIdsByPkiSyncId = async (pkiSyncId: string, tx?: Knex): Promise<string[]> => {
try {
const docs = (await (tx || db.replicaNode())(TableName.CertificateSync)
@@ -236,6 +264,7 @@ export const certificateSyncDALFactory = (db: TDbClient) => {
certificateDetails: (TCertificateSyncs & {
certificateSerialNumber?: string;
certificateCommonName?: string;
+ certificateOrderId?: string;
certificateAltNames?: string;
certificateStatus?: string;
certificateNotBefore?: Date;
@@ -271,6 +300,7 @@ export const certificateSyncDALFactory = (db: TDbClient) => {
.select(
db.ref("serialNumber").withSchema(TableName.Certificate).as("certificateSerialNumber"),
db.ref("commonName").withSchema(TableName.Certificate).as("certificateCommonName"),
+ db.ref("orderId").withSchema(TableName.Certificate).as("certificateOrderId"),
db.ref("altNames").withSchema(TableName.Certificate).as("certificateAltNames"),
db.ref("status").withSchema(TableName.Certificate).as("certificateStatus"),
db.ref("notBefore").withSchema(TableName.Certificate).as("certificateNotBefore"),
@@ -294,6 +324,7 @@ export const certificateSyncDALFactory = (db: TDbClient) => {
}
const certificateDetails = (await query) as (TCertificateSyncs & {
+ certificateOrderId?: string;
certificateSerialNumber?: string;
certificateCommonName?: string;
certificateAltNames?: string;
@@ -313,12 +344,16 @@ export const certificateSyncDALFactory = (db: TDbClient) => {
}
};
+ const primaryNode = () => db.primaryNode();
+
return {
+ primaryNode,
...certificateSyncOrm,
findByPkiSyncId,
findByCertificateId,
findByPkiSyncAndCertificate,
findCertificateIdsByPkiSyncId,
+ findIneligibleFilteredLinks,
findPkiSyncIdsByCertificateId,
findExternalIdentifiersInUse,
addCertificates,
diff --git a/backend/src/services/certificate-v3/certificate-approval-fns.ts b/backend/src/services/certificate-v3/certificate-approval-fns.ts
index 35adb4f25e..ea2b5c913a 100644
--- a/backend/src/services/certificate-v3/certificate-approval-fns.ts
+++ b/backend/src/services/certificate-v3/certificate-approval-fns.ts
@@ -38,6 +38,7 @@ import { TApiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TUsageCounterDALFactory } from "@app/services/license-client/usage/usage-counter-dal";
import { TPkiApplicationProfileDALFactory } from "@app/services/pki-application/pki-application-profile-dal";
+import { queueCertificateFilterReconcile } from "@app/services/pki-sync/pki-sync-utils";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
import { TResourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";
@@ -72,6 +73,7 @@ import {
} from "../certificate-common/certificate-utils";
import { TCertificateRequestDALFactory } from "../certificate-request/certificate-request-dal";
import { CertificateRequestStatus } from "../certificate-request/certificate-request-types";
+import { TPkiSyncQueueFactory } from "../pki-sync/pki-sync-queue";
import { applyProfileDefaults } from "./certificate-v3-fns";
import { TAltNameEntry, TCertificateIssuanceResponse } from "./certificate-v3-types";
@@ -83,6 +85,7 @@ export type TIssueCertificateFromApprovedRequestDeps = {
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;
internalCaService: Pick<TInternalCertificateAuthorityServiceFactory, "signCertFromCa" | "issueCertFromCa">;
certificateDAL: Pick<TCertificateDALFactory, "findById" | "updateById" | "transaction" | "create">;
+ pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById" | "queuePkiSyncLinkMatchingCertificates">;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey">;
@@ -205,7 +208,8 @@ export const certificateApprovalServiceFactory = (
certificateIssuanceQueue,
resourceMetadataDAL,
pkiApplicationProfileDAL,
- apiEnrollmentConfigDAL
+ apiEnrollmentConfigDAL,
+ pkiSyncQueue
} = deps;
const $validateProfileAndPermissions = async ({
@@ -640,6 +644,10 @@ export const certificateApprovalServiceFactory = (
const { certificate, certificateChain, issuingCaCertificate, serialNumber } = certResult;
+ if (certResult.certificateId && certRequest.applicationId) {
+ await queueCertificateFilterReconcile(certResult.certificateId, certRequest.applicationId, pkiSyncQueue);
+ }
+
const certificateString = extractCertificateFromBuffer(certificate as unknown as Buffer);
const certificateChainString = extractCertificateFromBuffer(certificateChain as unknown as Buffer);
@@ -887,6 +895,10 @@ export const certificateApprovalServiceFactory = (
const { selfSignedResult, certificateData } = result;
+ if (certificateData.id && applicationId) {
+ await queueCertificateFilterReconcile(certificateData.id, applicationId, pkiSyncQueue);
+ }
+
const subjectCommonName =
(selfSignedResult.certificateSubject.common_name as string) ||
certificateRequestInput.commonName ||
@@ -1037,6 +1049,10 @@ export const certificateApprovalServiceFactory = (
const finalCertificateChain = bufferToString(certificateChain);
+ if (cert.id && applicationId) {
+ await queueCertificateFilterReconcile(cert.id, applicationId, pkiSyncQueue);
+ }
+
return {
status: CertificateRequestStatus.ISSUED,
certificate: bufferToString(certificate),
diff --git a/backend/src/services/certificate-v3/certificate-renewal-service.ts b/backend/src/services/certificate-v3/certificate-renewal-service.ts
index bb1a054083..2ef2e7831d 100644
--- a/backend/src/services/certificate-v3/certificate-renewal-service.ts
+++ b/backend/src/services/certificate-v3/certificate-renewal-service.ts
@@ -83,7 +83,11 @@ import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync
import { TPkiApplicationProfileDALFactory } from "../pki-application/pki-application-profile-dal";
import { TPkiSyncDALFactory } from "../pki-sync/pki-sync-dal";
import { TPkiSyncQueueFactory } from "../pki-sync/pki-sync-queue";
-import { addRenewedCertificateToSyncs, triggerAutoSyncForCertificate } from "../pki-sync/pki-sync-utils";
+import {
+ addRenewedCertificateToSyncs,
+ queueCertificateFilterReconcile,
+ triggerAutoSyncForCertificate
+} from "../pki-sync/pki-sync-utils";
import { TResourceMetadataDALFactory } from "../resource-metadata/resource-metadata-dal";
import { copyMetadataFromCertificate } from "../resource-metadata/resource-metadata-fns";
import {
@@ -133,10 +137,14 @@ type TCertificateRenewalServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
certificateSyncDAL: Pick<
TCertificateSyncDALFactory,
- "findPkiSyncIdsByCertificateId" | "addCertificates" | "findByPkiSyncAndCertificate" | "updateSyncMetadata"
+ | "findPkiSyncIdsByCertificateId"
+ | "addCertificates"
+ | "findByPkiSyncAndCertificate"
+ | "updateSyncMetadata"
+ | "primaryNode"
>;
pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;
- pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;
+ pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById" | "queuePkiSyncLinkMatchingCertificates">;
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;
projectDAL: TProjectDALFactory;
certificateIssuanceQueue: Pick<TCertificateIssuanceQueueFactory, "queueCertificateIssuance">;
@@ -303,6 +311,11 @@ export const certificateRenewalServiceFactory = ({
}): Promise<TCertificateIssuanceResponse> => {
await triggerAutoSyncForCertificate(newCertificateId, { certificateSyncDAL, pkiSyncDAL, pkiSyncQueue });
+ if (originalCert.applicationId) {
+ await queueCertificateFilterReconcile(newCertificateId, originalCert.applicationId, pkiSyncQueue);
+ await queueCertificateFilterReconcile(originalCert.id, originalCert.applicationId, pkiSyncQueue);
+ }
+
try {
await pkiAlertV2Queue?.queueCertificateEvent({
certificateId: newCertificateId,
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
index 77c8e60746..2d03aa9276 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
@@ -88,9 +88,13 @@ describe("CertificateV3Service", () => {
| "find"
| "getRequestEnrollmentTypeByCertId"
| "getOriginatingRequestByCertId"
+ | "findCertificatesMatchingSyncFilters"
+ | "findActiveCertificatesByIds"
> = {
findOne: vi.fn(),
findById: vi.fn(),
+ findCertificatesMatchingSyncFilters: vi.fn().mockResolvedValue([]),
+ findActiveCertificatesByIds: vi.fn().mockResolvedValue([]),
updateById: vi.fn(),
getRequestEnrollmentTypeByCertId: vi.fn().mockResolvedValue(null),
getOriginatingRequestByCertId: vi.fn().mockResolvedValue({ enrollmentType: null, csr: null }),
@@ -307,13 +311,15 @@ describe("CertificateV3Service", () => {
findPkiSyncIdsByCertificateId: vi.fn().mockResolvedValue([]),
addCertificates: vi.fn().mockResolvedValue([]),
findByPkiSyncAndCertificate: vi.fn().mockResolvedValue(null),
- updateSyncMetadata: vi.fn().mockResolvedValue(null)
+ updateSyncMetadata: vi.fn().mockResolvedValue(null),
+ primaryNode: vi.fn()
},
pkiSyncDAL: {
find: vi.fn().mockResolvedValue([])
},
pkiSyncQueue: {
- queuePkiSyncSyncCertificatesById: vi.fn().mockResolvedValue(undefined)
+ queuePkiSyncSyncCertificatesById: vi.fn().mockResolvedValue(undefined),
+ queuePkiSyncLinkMatchingCertificates: vi.fn().mockResolvedValue(undefined)
},
certificateBodyDAL: {
create: vi.fn().mockResolvedValue({ id: "body-123" })
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index e4094c67ba..d05692f487 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -51,6 +51,7 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TUsageCounterDALFactory } from "@app/services/license-client/usage/usage-counter-dal";
import { TPkiAlertV2QueueServiceFactory } from "@app/services/pki-alert-v2/pki-alert-v2-queue";
import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types";
+import { queueCertificateFilterReconcile } from "@app/services/pki-sync/pki-sync-utils";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
import { TUserDALFactory } from "@app/services/user/user-dal";
@@ -145,10 +146,14 @@ type TCertificateV3ServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
certificateSyncDAL: Pick<
TCertificateSyncDALFactory,
- "findPkiSyncIdsByCertificateId" | "addCertificates" | "findByPkiSyncAndCertificate" | "updateSyncMetadata"
+ | "findPkiSyncIdsByCertificateId"
+ | "addCertificates"
+ | "findByPkiSyncAndCertificate"
+ | "updateSyncMetadata"
+ | "primaryNode"
>;
pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;
- pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;
+ pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById" | "queuePkiSyncLinkMatchingCertificates">;
kmsService: Pick<
TKmsServiceFactory,
"generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey" | "createCipherPairWithDataKey"
@@ -951,6 +956,10 @@ export const certificateV3ServiceFactory = ({
logger.debug("Failed to queue PKI issuance alert event");
}
+ if (certificateData.id && applicationId) {
+ await queueCertificateFilterReconcile(certificateData.id, applicationId, pkiSyncQueue);
+ }
+
await $reportCertificateIssued({
orgId: profile.project?.orgId ?? actorOrgId,
projectId: profile.projectId,
@@ -1185,6 +1194,10 @@ export const certificateV3ServiceFactory = ({
logger.debug("Failed to queue PKI issuance alert event");
}
+ if (cert.id && applicationId) {
+ await queueCertificateFilterReconcile(cert.id, applicationId, pkiSyncQueue);
+ }
+
await $reportCertificateIssued({
orgId: profile.project?.orgId ?? actorOrgId,
projectId: profile.projectId,
@@ -1649,6 +1662,10 @@ export const certificateV3ServiceFactory = ({
logger.debug("Failed to queue PKI issuance alert event");
}
+ if (certResult.certificateId && applicationId) {
+ await queueCertificateFilterReconcile(certResult.certificateId, applicationId, pkiSyncQueue);
+ }
+
await $reportCertificateIssued({
orgId: profile.project?.orgId ?? actorOrgId,
projectId: profile.projectId,
@@ -2138,6 +2155,10 @@ export const certificateV3ServiceFactory = ({
});
});
updatedMetadata = metadata;
+
+ if (certificate.applicationId) {
+ await queueCertificateFilterReconcile(certificateId, certificate.applicationId, pkiSyncQueue);
+ }
}
return { metadata: updatedMetadata, projectId: certificate.projectId, commonName: certificate.commonName };
diff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.ts
index e9897d95eb..1b60066ce2 100644
--- a/backend/src/services/certificate/certificate-dal.ts
+++ b/backend/src/services/certificate/certificate-dal.ts
@@ -134,6 +134,23 @@ export const certificateDALFactory = (db: TDbClient) => {
applicationIds?: string[];
};
+ type TSyncEligibilityFilterParams = Omit<TInventoryFilterParams, "status">;
+
+ type TPkiSyncMatchFilters = {
+ profileIds?: string[];
+ certificateOrderIds?: string[];
+ metadata?: { key: string; value?: string }[];
+ };
+
+ type TMatchedSyncCertificate = {
+ id: string;
+ commonName: string;
+ serialNumber: string;
+ notAfter: Date;
+ orderId: string;
+ profileName?: string | null;
+ };
+
const applyInventoryFilters = (
query: Knex.QueryBuilder,
filters: TInventoryFilterParams,
@@ -424,17 +441,17 @@ export const certificateDALFactory = (db: TDbClient) => {
}
};
- const findActiveCertificatesByIds = async (certificateIds: string[]): Promise<TCertificates[]> => {
+ const findActiveCertificatesByIds = async (certificateIds: string[], tx?: Knex): Promise<TCertificates[]> => {
try {
if (certificateIds.length === 0) {
return [];
}
- const certs = await db
- .replicaNode()(TableName.Certificate)
+ const certs = await (tx || db.replicaNode())(TableName.Certificate)
.whereIn("id", certificateIds)
.where({ status: CertStatus.ACTIVE })
.where("notAfter", ">", new Date())
+ .whereNull("renewedByCertificateId")
.orderBy("notBefore", "desc")
.select("*");
@@ -444,36 +461,36 @@ export const certificateDALFactory = (db: TDbClient) => {
}
};
+ const $applyActiveForSyncEligibility = (query: Knex.QueryBuilder): Knex.QueryBuilder =>
+ query
+ .where(`${TableName.Certificate}.status`, CertStatus.ACTIVE)
+ .where(`${TableName.Certificate}.notAfter`, ">", new Date())
+ .whereNull(`${TableName.Certificate}.renewedByCertificateId`);
+
const findActiveCertificatesForSync = async (
- filter: Partial<Omit<TCertificates, "status" | "keyAlgorithm" | "source"> & TInventoryFilterParams>,
+ filter: TSyncEligibilityFilterParams & { projectId: string },
options?: { limit?: number; offset?: number },
permissionFilters?: ProcessedPermissionRules
- ): Promise<(TCertificates & { hasPrivateKey: boolean })[]> => {
+ ): Promise<(TCertificates & { hasPrivateKey: boolean; profileName?: string | null })[]> => {
try {
+ const { projectId, ...inventoryFilters } = filter;
+
let query = db
.replicaNode()(TableName.Certificate)
.leftJoin(TableName.CertificateSecret, `${TableName.Certificate}.id`, `${TableName.CertificateSecret}.certId`)
+ .leftJoin(
+ TableName.PkiCertificateProfile,
+ `${TableName.Certificate}.profileId`,
+ `${TableName.PkiCertificateProfile}.id`
+ )
.select(selectAllTableCols(TableName.Certificate))
.select(db.ref(`${TableName.CertificateSecret}.certId`).as("privateKeyRef"))
- .where({ status: CertStatus.ACTIVE })
- .where("notAfter", ">", new Date())
- .whereNull("renewedByCertificateId");
+ .select(db.ref("slug").withSchema(TableName.PkiCertificateProfile).as("profileName"))
+ .andWhere(`${TableName.Certificate}.projectId`, projectId);
- Object.entries(filter).forEach(([key, value]) => {
- if (value === undefined || value === null) return;
- if (key === "applicationIds") {
- if (Array.isArray(value) && value.length > 0) {
- query = query.whereIn(`${TableName.Certificate}.applicationId`, value as string[]);
- }
- return;
- }
- if (key === "friendlyName" || key === "commonName") {
- const sanitizedValue = sanitizeSqlLikeString(String(value));
- query = query.andWhere(`${TableName.Certificate}.${key}`, "like", `%${sanitizedValue}%`);
- } else {
- query = query.andWhere(`${TableName.Certificate}.${key}`, value);
- }
- });
+ query = $applyActiveForSyncEligibility(query) as typeof query;
+
+ query = applyInventoryFilters(query, inventoryFilters, false) as typeof query;
if (permissionFilters) {
query = applyProcessedPermissionRulesToQuery(query, TableName.Certificate, permissionFilters) as typeof query;
@@ -499,48 +516,78 @@ export const certificateDALFactory = (db: TDbClient) => {
}
};
- const countActiveCertificatesForSync = async ({
- projectId,
- friendlyName,
- commonName,
- applicationId,
- applicationIds
- }: {
- projectId: string;
- friendlyName?: string;
- commonName?: string;
- applicationId?: string;
- applicationIds?: string[];
- }) => {
+ const findCertificatesMatchingSyncFilters = async (
+ filters: TPkiSyncMatchFilters | null | undefined,
+ scope: { projectId: string; applicationId: string; certificateId?: string },
+ options?: { limit?: number }
+ ): Promise<TMatchedSyncCertificate[]> => {
try {
- interface CountResult {
- count: string;
+ 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);
}
- let query = db
- .replicaNode()(TableName.Certificate)
- .join(TableName.CertificateAuthority, `${TableName.Certificate}.caId`, `${TableName.CertificateAuthority}.id`)
- .join(TableName.Project, `${TableName.CertificateAuthority}.projectId`, `${TableName.Project}.id`)
- .where(`${TableName.Project}.id`, projectId)
- .where(`${TableName.Certificate}.status`, CertStatus.ACTIVE)
- .where(`${TableName.Certificate}.notAfter`, ">", new Date())
- .whereNull(`${TableName.Certificate}.renewedByCertificateId`);
+ if (filters?.certificateOrderIds) {
+ query = query.whereIn(`${TableName.Certificate}.orderId`, filters.certificateOrderIds);
+ }
- if (friendlyName) {
- const sanitizedValue = sanitizeSqlLikeString(friendlyName);
- query = query.andWhere(`${TableName.Certificate}.friendlyName`, "like", `%${sanitizedValue}%`);
+ if (filters?.profileIds) {
+ query = query.whereIn(`${TableName.Certificate}.profileId`, filters.profileIds);
}
- if (commonName) {
- const sanitizedValue = sanitizeSqlLikeString(commonName);
- query = query.andWhere(`${TableName.Certificate}.commonName`, "like", `%${sanitizedValue}%`);
+ if (filters?.metadata) {
+ query = filters.metadata.length
+ ? applyMetadataFilter(query, filters.metadata, "certificateId", TableName.Certificate)
+ : query.whereRaw("1 = 0");
+ }
+
+ if (options?.limit) {
+ query = query.limit(options.limit);
}
- if (applicationId) {
- query = query.andWhere(`${TableName.Certificate}.applicationId`, applicationId);
+ return (await query
+ .orderBy(`${TableName.Certificate}.commonName`, "asc")
+ .select(
+ `${TableName.Certificate}.id`,
+ `${TableName.Certificate}.commonName`,
+ `${TableName.Certificate}.serialNumber`,
+ `${TableName.Certificate}.notAfter`,
+ `${TableName.Certificate}.orderId`,
+ db.ref("slug").withSchema(TableName.PkiCertificateProfile).as("profileName")
+ )) as TMatchedSyncCertificate[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find certificates matching sync filters" });
+ }
+ };
+
+ const countActiveCertificatesForSync = async (
+ filter: TSyncEligibilityFilterParams & { projectId: string },
+ permissionFilters?: ProcessedPermissionRules
+ ) => {
+ try {
+ interface CountResult {
+ count: string;
}
- if (applicationIds && applicationIds.length > 0) {
- query = query.whereIn(`${TableName.Certificate}.applicationId`, applicationIds);
+
+ const { projectId, ...inventoryFilters } = filter;
+
+ let query = db.replicaNode()(TableName.Certificate).where(`${TableName.Certificate}.projectId`, projectId);
+
+ query = $applyActiveForSyncEligibility(query) as typeof query;
+ query = applyInventoryFilters(query, inventoryFilters, false) as typeof query;
+
+ if (permissionFilters) {
+ query = applyProcessedPermissionRulesToQuery(query, TableName.Certificate, permissionFilters) as typeof query;
}
const count = await query.count("*").first();
@@ -1255,7 +1302,10 @@ export const certificateDALFactory = (db: TDbClient) => {
}
};
+ const primaryNode = () => db.primaryNode();
+
return {
+ primaryNode,
...certificateOrm,
create,
countCertificatesInProject,
@@ -1268,6 +1318,7 @@ export const certificateDALFactory = (db: TDbClient) => {
findByThumbprintInOrg,
findActiveCertificatesByIds,
findActiveCertificatesForSync,
+ findCertificatesMatchingSyncFilters,
findCertificatesEligibleForRenewal,
getRequestEnrollmentTypeByCertId,
getOriginatingRequestByCertId,
diff --git a/backend/src/services/certificate/certificate-schemas.ts b/backend/src/services/certificate/certificate-schemas.ts
index 578d0c5d76..95fd84f549 100644
--- a/backend/src/services/certificate/certificate-schemas.ts
+++ b/backend/src/services/certificate/certificate-schemas.ts
@@ -1,10 +1,9 @@
import { CertificatesSchema } from "@app/db/schemas";
-// The certificates table carries bookkeeping columns the API does not expose: orderId groups a
-// renewal chain, and quotaKey / hasWildcard exist so the licence quota can be counted from an index.
-// Responses build on this rather than omitting them per route, so a new endpoint cannot leak them.
+// The certificates table carries bookkeeping columns the API does not expose: quotaKey and
+// hasWildcard exist so the licence quota can be counted from an index. Responses build on this
+// rather than omitting them per route, so a new endpoint cannot leak them.
export const SanitizedCertificateSchema = CertificatesSchema.omit({
- orderId: true,
quotaKey: true,
hasWildcard: true
});
diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.ts
index f6352e71a3..9e92aec52c 100644
--- a/backend/src/services/certificate/certificate-service.ts
+++ b/backend/src/services/certificate/certificate-service.ts
@@ -3,6 +3,7 @@ import { ForbiddenError, subject } from "@casl/ability";
import * as x509 from "@peculiar/x509";
import { ActionProjectType, ProjectMembershipRole, ResourceType } from "@app/db/schemas";
+import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TCertificateAuthorityCrlDALFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-dal";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
@@ -56,7 +57,12 @@ import { TPkiCollectionDALFactory } from "@app/services/pki-collection/pki-colle
import { TPkiCollectionItemDALFactory } from "@app/services/pki-collection/pki-collection-item-dal";
import { TPkiSyncDALFactory } from "@app/services/pki-sync/pki-sync-dal";
import { TPkiSyncQueueFactory } from "@app/services/pki-sync/pki-sync-queue";
-import { triggerAutoSyncForCertificate } from "@app/services/pki-sync/pki-sync-utils";
+import {
+ findPkiSyncIdsHoldingCertificate,
+ queueCertificateFilterReconcile,
+ triggerAutoSyncForCertificate,
+ triggerSyncsForDeletedCertificate
+} from "@app/services/pki-sync/pki-sync-utils";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
import { TResourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";
@@ -138,9 +144,10 @@ type TCertificateServiceFactoryDep = {
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "findById" | "transaction" | "findProjectBySlug">;
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
- certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findPkiSyncIdsByCertificateId">;
+ certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findPkiSyncIdsByCertificateId" | "primaryNode">;
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;
- pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;
+ pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById" | "queuePkiSyncLinkMatchingCertificates">;
certificateAuthorityService: Pick<TCertificateAuthorityServiceFactory, "revokeCertificate">;
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find">;
pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;
@@ -170,6 +177,7 @@ export const certificateServiceFactory = ({
kmsService,
permissionService,
certificateSyncDAL,
+ auditLogService,
pkiSyncDAL,
pkiSyncQueue,
certificateAuthorityService,
@@ -426,8 +434,23 @@ export const certificateServiceFactory = ({
/**
* Delete certificate with serial number [serialNumber]
*/
- const deleteCert = async ({ id, serialNumber, actorId, actorAuthMethod, actor, actorOrgId }: TDeleteCertDTO) => {
+ const deleteCert = async ({
+ id,
+ serialNumber,
+ actorId,
+ actorAuthMethod,
+ actor,
+ actorOrgId,
+ auditLogInfo
+ }: TDeleteCertDTO) => {
const cert = id ? await certificateDAL.findById(id) : await certificateDAL.findOne({ serialNumber });
+ if (!cert) {
+ throw new NotFoundError({
+ message: id
+ ? `Certificate with id '${id}' not found`
+ : `Certificate with serial number '${serialNumber}' not found`
+ });
+ }
const metadataRows = await resourceMetadataDAL.find({ certificateId: cert.id });
const certMetadata = metadataRows.map(({ key, value }) => ({ key, value: value || "" }));
@@ -467,6 +490,8 @@ export const certificateServiceFactory = ({
);
}
+ const pkiSyncIdsHoldingCertificate = await findPkiSyncIdsHoldingCertificate(cert.id, { certificateSyncDAL });
+
let deletedCert;
try {
deletedCert = await certificateDAL.transaction(async (tx) => {
@@ -503,12 +528,13 @@ export const certificateServiceFactory = ({
throw err;
}
- // Trigger auto sync for PKI syncs connected to this certificate
- await triggerAutoSyncForCertificate(cert.id, {
- certificateSyncDAL,
- pkiSyncDAL,
- pkiSyncQueue
- });
+ await triggerSyncsForDeletedCertificate(
+ cert.id,
+ pkiSyncIdsHoldingCertificate,
+ { pkiSyncDAL, pkiSyncQueue, auditLogService },
+ { commonName: cert.commonName, projectId: cert.projectId, applicationId: cert.applicationId },
+ auditLogInfo
+ );
usageMeteringService.emitForProject(cert.projectId, ActiveCerts.key);
usageMeteringService.emitForProject(cert.projectId, WildcardCerts.key);
@@ -544,11 +570,6 @@ export const certificateServiceFactory = ({
}
};
- /**
- * Revoke certificate with serial number [serialNumber].
- * Note: Revoking a certificate adds it to the certificate revocation list (CRL)
- * of its issuing CA
- */
const revokeCert = async ({
id,
serialNumber,
@@ -709,6 +730,10 @@ export const certificateServiceFactory = ({
pkiSyncQueue
});
+ if (cert.applicationId) {
+ await queueCertificateFilterReconcile(cert.id, cert.applicationId, pkiSyncQueue);
+ }
+
// rebuild CRL (TODO: move to interval-based cron job)
// Only rebuild CRL for internal CAs - external CAs manage their own CRLs
if (!ca.externalCa?.id) {
@@ -1369,6 +1394,10 @@ export const certificateServiceFactory = ({
usageMeteringService.emitForProject(projectId, ActiveCerts.key);
usageMeteringService.emitForProject(projectId, WildcardCerts.key);
+ if (cert.id && cert.applicationId) {
+ await queueCertificateFilterReconcile(cert.id, cert.applicationId, pkiSyncQueue);
+ }
+
return {
certificate: certificatePem,
certificateChain: chainPem,
@@ -1642,6 +1671,9 @@ export const certificateServiceFactory = ({
}
const [updatedCert] = await certificateDAL.update({ id: cert.id }, { applicationId });
+
+ await queueCertificateFilterReconcile(cert.id, applicationId, pkiSyncQueue);
+
return { certificate: updatedCert, application };
};
diff --git a/backend/src/services/certificate/certificate-types.ts b/backend/src/services/certificate/certificate-types.ts
index a44aa7e983..a0020dd50f 100644
--- a/backend/src/services/certificate/certificate-types.ts
+++ b/backend/src/services/certificate/certificate-types.ts
@@ -1,3 +1,4 @@
+import { AuditLogInfo } from "@app/ee/services/audit-log/audit-log-types";
import { TProjectPermission } from "@app/lib/types";
import {
CERT_EXTENDED_KEY_USAGES,
@@ -122,6 +123,7 @@ export type TGetCertDTO = {
export type TDeleteCertDTO = {
id?: string;
serialNumber?: string;
+ auditLogInfo?: AuditLogInfo;
} & Omit<TProjectPermission, "projectId">;
export type TRevokeCertDTO = {
diff --git a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-fns.ts b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-fns.ts
index b458a35648..d471354d39 100644
--- a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-fns.ts
@@ -49,6 +49,7 @@ import {
} from "./aws-certificate-manager-pki-sync-types";
const INFISICAL_CERTIFICATE_TAG = "InfisicalCertificate";
+const INFISICAL_PKI_SYNC_TAG = "InfisicalPkiSyncId";
const AWS_CERTIFICATE_ARN_PATTERN = new RE2("^arn:aws:acm:[a-z0-9-]+:\\d{12}:certificate/[a-f0-9-]{36}$");
type TAwsAssumeRoleCredentials = z.infer<typeof AwsConnectionAssumeRoleCredentialsSchema>;
@@ -475,11 +476,18 @@ export const awsCertificateManagerPkiSyncFactory = ({
if (currentSyncRecord?.externalIdentifier) {
const existingAcmCert = acmCertificatesByArn.get(currentSyncRecord.externalIdentifier);
+ const alreadyDelivered =
+ currentSyncRecord.syncStatus === CertificateSyncStatus.Succeeded &&
+ Boolean(currentSyncRecord.lastSyncedAt);
if (existingAcmCert) {
- if (!preserveArn && oldSyncRecord?.externalIdentifier === currentSyncRecord.externalIdentifier) {
+ if (alreadyDelivered) {
+ targetArn = currentSyncRecord.externalIdentifier;
+ activeExternalIdentifiers.add(targetArn);
+ shouldCreateNew = false;
+ } else if (!preserveArn) {
shouldCreateNew = true;
- } else if (preserveArn && oldSyncRecord?.externalIdentifier === currentSyncRecord.externalIdentifier) {
+ } else {
targetArn = currentSyncRecord.externalIdentifier;
shouldCreateNew = true;
activeExternalIdentifiers.add(targetArn);
@@ -487,10 +495,6 @@ export const awsCertificateManagerPkiSyncFactory = ({
if (oldCertificateId && oldSyncRecord) {
await certificateSyncDAL.removeCertificates(pkiSync.id, [oldCertificateId]);
}
- } else {
- targetArn = currentSyncRecord.externalIdentifier;
- activeExternalIdentifiers.add(targetArn);
- shouldCreateNew = false;
}
} else {
shouldCreateNew = true;
@@ -559,9 +563,11 @@ export const awsCertificateManagerPkiSyncFactory = ({
Object.values(acmCertificates).forEach((acmCert) => {
if (acmCert.arn && acmCert.Tags) {
- const hasInfisicalTag = acmCert.Tags.some((tag) => tag.Key === INFISICAL_CERTIFICATE_TAG && tag.Value);
+ const belongsToThisSync = acmCert.Tags.some(
+ (tag) => tag.Key === INFISICAL_PKI_SYNC_TAG && tag.Value === pkiSync.id
+ );
- if (hasInfisicalTag) {
+ if (belongsToThisSync) {
const isTrackedInSyncRecords = existingSyncRecords.some(
(record) => record.externalIdentifier === acmCert.arn
);
@@ -588,6 +594,10 @@ export const awsCertificateManagerPkiSyncFactory = ({
{
Key: INFISICAL_CERTIFICATE_TAG,
Value: key
+ },
+ {
+ Key: INFISICAL_PKI_SYNC_TAG,
+ Value: pkiSync.id
}
];
}
@@ -620,6 +630,10 @@ export const awsCertificateManagerPkiSyncFactory = ({
{
Key: INFISICAL_CERTIFICATE_TAG,
Value: key
+ },
+ {
+ Key: INFISICAL_PKI_SYNC_TAG,
+ Value: pkiSync.id
}
]
})
diff --git a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts
index 6806da8ec2..2087e1f457 100644
--- a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts
@@ -5,7 +5,12 @@ import { AppConnection, AWSRegion } from "@app/services/app-connection/app-conne
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-import { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import {
+ HostCommandSchema,
+ PkiSyncFiltersField,
+ PkiSyncSchema,
+ UpdatePkiSyncFiltersField
+} from "@app/services/pki-sync/pki-sync-schemas";
import { AWS_CERTIFICATE_MANAGER_CERTIFICATE_NAMING } from "./aws-certificate-manager-pki-sync-constants";
@@ -67,7 +72,8 @@ export const CreateAwsCertificateManagerPkiSyncSchema = z.object({
connectionId: z.string(),
projectId: z.string().trim().min(1).optional().describe(openApiHidden()),
applicationId: z.string().uuid().optional(),
- certificateIds: z.array(z.string().uuid()).optional()
+ certificateIds: z.array(z.string().uuid()).optional(),
+ filters: PkiSyncFiltersField
});
export const UpdateAwsCertificateManagerPkiSyncSchema = z.object({
@@ -77,7 +83,8 @@ export const UpdateAwsCertificateManagerPkiSyncSchema = z.object({
destinationConfig: AwsCertificateManagerPkiSyncConfigSchema.optional(),
syncOptions: AwsCertificateManagerPkiSyncOptionsSchema.optional(),
subscriberId: z.string().nullish(),
- connectionId: z.string().optional()
+ connectionId: z.string().optional(),
+ filters: UpdatePkiSyncFiltersField
});
export const AwsCertificateManagerPkiSyncListItemSchema = z.object({
diff --git a/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-schemas.ts b/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-schemas.ts
index 50b4e3cd95..372629d9b0 100644
--- a/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-schemas.ts
@@ -4,7 +4,12 @@ import { openApiHidden } from "@app/server/lib/schemas";
import { AppConnection, AWSRegion } from "@app/services/app-connection/app-connection-enums";
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-import { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import {
+ HostCommandSchema,
+ PkiSyncFiltersField,
+ PkiSyncSchema,
+ UpdatePkiSyncFiltersField
+} from "@app/services/pki-sync/pki-sync-schemas";
export const AwsElasticLoadBalancerListenerSchema = z.object({
listenerArn: z.string().min(1, "Listener ARN is required"),
@@ -47,7 +52,8 @@ export const CreateAwsElasticLoadBalancerPkiSyncSchema = z.object({
connectionId: z.string(),
projectId: z.string().trim().min(1).optional().describe(openApiHidden()),
applicationId: z.string().uuid().optional(),
- certificateIds: z.array(z.string().uuid()).optional()
+ certificateIds: z.array(z.string().uuid()).optional(),
+ filters: PkiSyncFiltersField
});
export const UpdateAwsElasticLoadBalancerPkiSyncSchema = z.object({
@@ -57,7 +63,8 @@ export const UpdateAwsElasticLoadBalancerPkiSyncSchema = z.object({
destinationConfig: AwsElasticLoadBalancerPkiSyncConfigSchema.optional(),
syncOptions: AwsElasticLoadBalancerPkiSyncOptionsSchema.optional(),
subscriberId: z.string().nullish(),
- connectionId: z.string().optional()
+ connectionId: z.string().optional(),
+ filters: UpdatePkiSyncFiltersField
});
export const AwsElasticLoadBalancerPkiSyncListItemSchema = z.object({
diff --git a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.ts b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.ts
index ac88ed4205..f1370d282d 100644
--- a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.ts
@@ -5,7 +5,12 @@ import { AppConnection, AWSRegion } from "@app/services/app-connection/app-conne
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-import { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import {
+ HostCommandSchema,
+ PkiSyncFiltersField,
+ PkiSyncSchema,
+ UpdatePkiSyncFiltersField
+} from "@app/services/pki-sync/pki-sync-schemas";
import { AWS_SECRETS_MANAGER_PKI_SYNC_CERTIFICATE_NAMING } from "./aws-secrets-manager-pki-sync-constants";
@@ -81,7 +86,8 @@ export const CreateAwsSecretsManagerPkiSyncSchema = z.object({
connectionId: z.string(),
projectId: z.string().trim().min(1).optional().describe(openApiHidden()),
applicationId: z.string().uuid().optional(),
- certificateIds: z.array(z.string().uuid()).optional()
+ certificateIds: z.array(z.string().uuid()).optional(),
+ filters: PkiSyncFiltersField
});
export const UpdateAwsSecretsManagerPkiSyncSchema = z.object({
@@ -91,7 +97,8 @@ export const UpdateAwsSecretsManagerPkiSyncSchema = z.object({
destinationConfig: AwsSecretsManagerPkiSyncConfigSchema.optional(),
syncOptions: AwsSecretsManagerPkiSyncOptionsSchema.optional(),
subscriberId: z.string().nullish(),
- connectionId: z.string().optional()
+ connectionId: z.string().optional(),
+ filters: UpdatePkiSyncFiltersField
});
export const AwsSecretsManagerPkiSyncListItemSchema = z.object({
diff --git a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts
index a9df266aaa..79817e068b 100644
--- a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts
@@ -6,7 +6,12 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enums
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-import { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import {
+ HostCommandSchema,
+ PkiSyncFiltersField,
+ PkiSyncSchema,
+ UpdatePkiSyncFiltersField
+} from "@app/services/pki-sync/pki-sync-schemas";
import { AZURE_KEY_VAULT_CERTIFICATE_NAMING } from "./azure-key-vault-pki-sync-constants";
@@ -64,7 +69,8 @@ export const CreateAzureKeyVaultPkiSyncSchema = z.object({
connectionId: z.string(),
projectId: z.string().trim().min(1).optional().describe(openApiHidden()),
applicationId: z.string().uuid().optional(),
- certificateIds: z.array(z.string().uuid()).optional()
+ certificateIds: z.array(z.string().uuid()).optional(),
+ filters: PkiSyncFiltersField
});
export const UpdateAzureKeyVaultPkiSyncSchema = z.object({
@@ -74,7 +80,8 @@ export const UpdateAzureKeyVaultPkiSyncSchema = z.object({
destinationConfig: AzureKeyVaultPkiSyncConfigSchema.optional(),
syncOptions: AzureKeyVaultPkiSyncOptionsSchema.optional(),
subscriberId: z.string().nullish(),
- connectionId: z.string().optional()
+ connectionId: z.string().optional(),
+ filters: UpdatePkiSyncFiltersField
});
export const AzureKeyVaultPkiSyncListItemSchema = z.object({
diff --git a/backend/src/services/pki-sync/chef/chef-pki-sync-schemas.ts b/backend/src/services/pki-sync/chef/chef-pki-sync-schemas.ts
index 006688588b..7654efbaf3 100644
--- a/backend/src/services/pki-sync/chef/chef-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/chef/chef-pki-sync-schemas.ts
@@ -5,7 +5,12 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enums
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-import { BasePkiSyncOptionsSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import {
+ BasePkiSyncOptionsSchema,
+ PkiSyncFiltersField,
+ PkiSyncSchema,
+ UpdatePkiSyncFiltersField
+} from "@app/services/pki-sync/pki-sync-schemas";
import { CHEF_PKI_SYNC_CERTIFICATE_NAMING, CHEF_PKI_SYNC_DATA_BAG_NAMING } from "./chef-pki-sync-constants";
@@ -83,7 +88,8 @@ export const CreateChefPkiSyncSchema = z.object({
connectionId: z.string(),
projectId: z.string().trim().min(1).optional().describe(openApiHidden()),
applicationId: z.string().uuid().optional(),
- certificateIds: z.array(z.string().uuid()).optional()
+ certificateIds: z.array(z.string().uuid()).optional(),
+ filters: PkiSyncFiltersField
});
export const UpdateChefPkiSyncSchema = z.object({
@@ -93,7 +99,8 @@ export const UpdateChefPkiSyncSchema = z.object({
destinationConfig: ChefPkiSyncConfigSchema.optional(),
syncOptions: ChefPkiSyncOptionsSchema.optional(),
subscriberId: z.string().nullish(),
- connectionId: z.string().optional()
+ connectionId: z.string().optional(),
+ filters: UpdatePkiSyncFiltersField
});
export const ChefPkiSyncListItemSchema = z.object({
diff --git a/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.ts b/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.ts
index 53296150e0..8b842e03e4 100644
--- a/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.ts
@@ -5,7 +5,12 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enums
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-import { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import {
+ HostCommandSchema,
+ PkiSyncFiltersField,
+ PkiSyncSchema,
+ UpdatePkiSyncFiltersField
+} from "@app/services/pki-sync/pki-sync-schemas";
import { CLOUDFLARE_CUSTOM_CERTIFICATE_NAMING } from "./cloudflare-custom-certificate-pki-sync-constants";
@@ -59,7 +64,8 @@ export const CreateCloudflareCustomCertificatePkiSyncSchema = z.object({
connectionId: z.string(),
projectId: z.string().trim().min(1).optional().describe(openApiHidden()),
applicationId: z.string().uuid().optional(),
- certificateIds: z.array(z.string().uuid()).optional()
+ certificateIds: z.array(z.string().uuid()).optional(),
+ filters: PkiSyncFiltersField
});
export const UpdateCloudflareCustomCertificatePkiSyncSchema = z.object({
@@ -69,7 +75,8 @@ export const UpdateCloudflareCustomCertificatePkiSyncSchema = z.object({
destinationConfig: CloudflareCustomCertificatePkiSyncConfigSchema.optional(),
syncOptions: CloudflareCustomCertificatePkiSyncOptionsSchema.optional(),
subscriberId: z.string().nullish(),
- connectionId: z.string().optional()
+ connectionId: z.string().optional(),
+ filters: UpdatePkiSyncFiltersField
});
export const CloudflareCustomCertificatePkiSyncListItemSchema = z.object({
diff --git a/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-schemas.ts b/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-schemas.ts
index 271b4d76f8..2e89cba3f1 100644
--- a/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-schemas.ts
@@ -7,7 +7,9 @@ import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
import {
BasePkiSyncOptionsSchema,
buildDestinationCertificateNameSchema,
- PkiSyncSchema
+ PkiSyncFiltersField,
+ PkiSyncSchema,
+ UpdatePkiSyncFiltersField
} from "@app/services/pki-sync/pki-sync-schemas";
import { F5_BIG_IP_NAMING, F5BigIpProfileType } from "./f5-big-ip-pki-sync-constants";
@@ -81,7 +83,8 @@ export const CreateF5BigIpPkiSyncSchema = z.object({
connectionId: z.string(),
projectId: z.string().trim().min(1).optional().describe(openApiHidden()),
applicationId: z.string().uuid().optional(),
- certificateIds: z.array(z.string().uuid()).optional()
+ certificateIds: z.array(z.string().uuid()).optional(),
+ filters: PkiSyncFiltersField
});
export const UpdateF5BigIpPkiSyncSchema = z.object({
@@ -91,7 +94,8 @@ export const UpdateF5BigIpPkiSyncSchema = z.object({
destinationConfig: F5BigIpPkiSyncConfigSchema.optional(),
syncOptions: F5BigIpPkiSyncOptionsSchema.optional(),
subscriberId: z.string().nullish(),
- connectionId: z.string().optional()
+ connectionId: z.string().optional(),
+ filters: UpdatePkiSyncFiltersField
});
export const F5BigIpPkiSyncListItemSchema = z.object({
diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-schemas.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-schemas.ts
index e03ef63183..ccf0c1f67a 100644
--- a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-schemas.ts
@@ -8,7 +8,9 @@ import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
import {
BasePkiSyncOptionsSchema,
buildDestinationCertificateNameSchema,
- PkiSyncSchema
+ PkiSyncFiltersField,
+ PkiSyncSchema,
+ UpdatePkiSyncFiltersField
} from "@app/services/pki-sync/pki-sync-schemas";
import {
@@ -182,12 +184,18 @@ export const CreateGcpCertificateManagerPkiSyncSchema = z
connectionId: z.string().uuid(),
projectId: z.string().trim().min(1).optional().describe(openApiHidden()),
applicationId: z.string().uuid().optional(),
- certificateIds: z.array(z.string().uuid()).optional()
+ certificateIds: z.array(z.string().uuid()).optional(),
+ filters: PkiSyncFiltersField
})
.superRefine((value, ctx) => {
+ const requestedCertificateCount = Math.max(
+ value.certificateIds?.length ?? 0,
+ value.filters?.certificateOrderIds?.length ?? 0
+ );
+
if (
value.destinationConfig.certificateMapBinding &&
- (value.certificateIds?.length ?? 0) > GCP_MAX_CERTIFICATES_PER_MAP_ENTRY
+ requestedCertificateCount > GCP_MAX_CERTIFICATES_PER_MAP_ENTRY
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
@@ -204,7 +212,8 @@ export const UpdateGcpCertificateManagerPkiSyncSchema = z.object({
destinationConfig: GcpCertificateManagerPkiSyncConfigUpdateSchema.optional(),
syncOptions: GcpCertificateManagerPkiSyncOptionsSchema.optional(),
subscriberId: z.string().nullish(),
- connectionId: z.string().uuid().optional()
+ connectionId: z.string().uuid().optional(),
+ filters: UpdatePkiSyncFiltersField
});
export const GcpCertificateManagerPkiSyncListItemSchema = z.object({
diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-update-fns.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-update-fns.ts
index 9b2e74281c..7df220cb40 100644
--- a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-update-fns.ts
+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-update-fns.ts
@@ -41,17 +41,3 @@ export const resolveGcpCertificateManagerConfigUpdate = (
export const buildGcpTooManyCertificatesMessage = (certificateMap: string, certificateCount: number) =>
`This sync attaches its certificates to the GCP certificate map "${certificateMap}", and GCP allows at most ${GCP_MAX_CERTIFICATES_PER_MAP_ENTRY} certificates in one certificate map entry. Turn off the certificate map binding to sync ${certificateCount} certificates, or link at most ${GCP_MAX_CERTIFICATES_PER_MAP_ENTRY}.`;
-
-export const assertGcpCertificateManagerCertificateCount = (
- destinationConfig: TGcpCertificateManagerPkiSyncConfig | undefined,
- resultingCertificateCount: number
-) => {
- if (resultingCertificateCount <= GCP_MAX_CERTIFICATES_PER_MAP_ENTRY) return;
-
- const certificateMapBinding = destinationConfig?.certificateMapBinding;
- if (!certificateMapBinding) return;
-
- throw new BadRequestError({
- message: buildGcpTooManyCertificatesMessage(certificateMapBinding.certificateMap, resultingCertificateCount)
- });
-};
diff --git a/backend/src/services/pki-sync/kemp-loadmaster/kemp-loadmaster-pki-sync-schemas.ts b/backend/src/services/pki-sync/kemp-loadmaster/kemp-loadmaster-pki-sync-schemas.ts
index d2d83aeba7..e0593e2e22 100644
--- a/backend/src/services/pki-sync/kemp-loadmaster/kemp-loadmaster-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/kemp-loadmaster/kemp-loadmaster-pki-sync-schemas.ts
@@ -8,7 +8,9 @@ import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
import {
BasePkiSyncOptionsSchema,
buildDestinationCertificateNameSchema,
- PkiSyncSchema
+ PkiSyncFiltersField,
+ PkiSyncSchema,
+ UpdatePkiSyncFiltersField
} from "@app/services/pki-sync/pki-sync-schemas";
import { KEMP_LOADMASTER_DEFAULT_CA_NAME_SCHEMA, KEMP_LOADMASTER_NAMING } from "./kemp-loadmaster-pki-sync-constants";
@@ -70,7 +72,8 @@ export const CreateKempLoadMasterPkiSyncSchema = z.object({
connectionId: z.string(),
projectId: z.string().trim().min(1).optional().describe(openApiHidden()),
applicationId: z.string().uuid().optional(),
- certificateIds: z.array(z.string().uuid()).optional()
+ certificateIds: z.array(z.string().uuid()).optional(),
+ filters: PkiSyncFiltersField
});
export const UpdateKempLoadMasterPkiSyncSchema = z.object({
@@ -80,7 +83,8 @@ export const UpdateKempLoadMasterPkiSyncSchema = z.object({
destinationConfig: KempLoadMasterPkiSyncConfigSchema.optional(),
syncOptions: KempLoadMasterPkiSyncOptionsSchema.optional(),
subscriberId: z.string().nullish(),
- connectionId: z.string().optional()
+ connectionId: z.string().optional(),
+ filters: UpdatePkiSyncFiltersField
});
export const KempLoadMasterPkiSyncListItemSchema = z.object({
diff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts
index cd7cdfa759..fc5b7834b0 100644
--- a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts
@@ -21,6 +21,7 @@ import {
withSshConnection
} from "@app/services/app-connection/ssh/ssh-connection-fns";
import { TSshConnectionConfig } from "@app/services/app-connection/ssh/ssh-connection-types";
+import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";
import { TSyncMetadata } from "@app/services/certificate-sync/certificate-sync-schemas";
@@ -51,6 +52,7 @@ type TLinuxServerPkiSyncFactoryDeps = {
TCertificateSyncDALFactory,
"findByPkiSyncId" | "findByPkiSyncAndCertificate" | "updateById" | "addCertificates" | "removeCertificates"
>;
+ certificateDAL: Pick<TCertificateDALFactory, "findActiveCertificatesByIds">;
gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId" | "getGatewayById">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
@@ -262,8 +264,9 @@ const reconcileLinuxServerRemovals = async (args: {
certificateMap: TCertificateMap;
deliveredPaths: Set<string>;
certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findByPkiSyncId" | "removeCertificates">;
+ certificateDAL: Pick<TCertificateDALFactory, "findActiveCertificatesByIds">;
}): Promise<{ removed: number; failedRemovals: Array<{ name: string; error: string }> }> => {
- const { sftp, pkiSync, certificateMap, deliveredPaths, certificateSyncDAL } = args;
+ const { sftp, pkiSync, certificateMap, deliveredPaths, certificateSyncDAL, certificateDAL } = args;
const failedRemovals: Array<{ name: string; error: string }> = [];
let removed = 0;
@@ -274,8 +277,19 @@ const reconcileLinuxServerRemovals = async (args: {
);
const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id);
+ const untrackCandidateIds = existingSyncRecords
+ .map((record) => record.certificateId)
+ .filter((id): id is string => Boolean(id) && !activeCertificateIds.has(id));
+ const stillActiveIds = new Set(
+ (await certificateDAL.findActiveCertificatesByIds(untrackCandidateIds)).map((cert) => cert.id)
+ );
+
for (const record of existingSyncRecords) {
- if (!record.certificateId || activeCertificateIds.has(record.certificateId)) {
+ if (
+ !record.certificateId ||
+ activeCertificateIds.has(record.certificateId) ||
+ stillActiveIds.has(record.certificateId)
+ ) {
// eslint-disable-next-line no-continue
continue;
}
@@ -393,6 +407,7 @@ const runLinuxServerPostSyncCommand = ({
export const linuxServerPkiSyncFactory = ({
certificateSyncDAL,
+ certificateDAL,
gatewayV2Service,
gatewayPoolService,
keyStore
@@ -539,7 +554,8 @@ export const linuxServerPkiSyncFactory = ({
pkiSync,
certificateMap,
deliveredPaths,
- certificateSyncDAL
+ certificateSyncDAL,
+ certificateDAL
});
removed += reconciliation.removed;
failedRemovals.push(...reconciliation.failedRemovals);
diff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts
index 57f8172c36..784b06e695 100644
--- a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts
@@ -13,9 +13,11 @@ import { PemCertificateExtension, PkiSyncExportFormat } from "@app/services/pki-
import {
BaseHealthCheckTestSchema,
HostCommandSchema,
+ PkiSyncFiltersField,
PkiSyncSchema,
PkiSyncTargetHostSchema,
- PkiSyncTargetPortSchema
+ PkiSyncTargetPortSchema,
+ UpdatePkiSyncFiltersField
} from "@app/services/pki-sync/pki-sync-schemas";
import { LINUX_SERVER_NAMING } from "./linux-server-pki-sync-constants";
@@ -129,7 +131,8 @@ export const CreateLinuxServerPkiSyncSchema = z
subscriberId: z.string().nullish(),
connectionId: z.string(),
applicationId: z.string().uuid().optional(),
- certificateIds: z.array(z.string().uuid()).optional()
+ certificateIds: z.array(z.string().uuid()).optional(),
+ filters: PkiSyncFiltersField
})
.superRefine((data, ctx) => {
if (data.syncOptions.exportFormat === PkiSyncExportFormat.Pkcs12 && !data.credentials?.exportPassword) {
@@ -149,7 +152,8 @@ export const UpdateLinuxServerPkiSyncSchema = z.object({
syncOptions: LinuxServerPkiSyncOptionsSchema.optional(),
credentials: LinuxServerPkiSyncCredentialsSchema.optional(),
subscriberId: z.string().nullish(),
- connectionId: z.string().optional()
+ connectionId: z.string().optional(),
+ filters: UpdatePkiSyncFiltersField
});
export const LinuxServerPkiSyncListItemSchema = z.object({
diff --git a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.ts b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.ts
index 37a90cf3ba..db3b2b89d8 100644
--- a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.ts
@@ -7,7 +7,9 @@ import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
import {
BasePkiSyncOptionsSchema,
buildDestinationCertificateNameSchema,
- PkiSyncSchema
+ PkiSyncFiltersField,
+ PkiSyncSchema,
+ UpdatePkiSyncFiltersField
} from "@app/services/pki-sync/pki-sync-schemas";
import { NETSCALER_NAMING } from "./netscaler-pki-sync-constants";
@@ -40,7 +42,8 @@ export const CreateNetScalerPkiSyncSchema = z.object({
connectionId: z.string(),
projectId: z.string().trim().min(1).optional().describe(openApiHidden()),
applicationId: z.string().uuid().optional(),
- certificateIds: z.array(z.string().uuid()).optional()
+ certificateIds: z.array(z.string().uuid()).optional(),
+ filters: PkiSyncFiltersField
});
export const UpdateNetScalerPkiSyncSchema = z.object({
@@ -50,7 +53,8 @@ export const UpdateNetScalerPkiSyncSchema = z.object({
destinationConfig: NetScalerPkiSyncConfigSchema.optional(),
syncOptions: NetScalerPkiSyncOptionsSchema.optional(),
subscriberId: z.string().nullish(),
- connectionId: z.string().optional()
+ connectionId: z.string().optional(),
+ filters: UpdatePkiSyncFiltersField
});
export const NetScalerPkiSyncListItemSchema = z.object({
diff --git a/backend/src/services/pki-sync/nutanix-prism-central/nutanix-prism-central-pki-sync-schemas.ts b/backend/src/services/pki-sync/nutanix-prism-central/nutanix-prism-central-pki-sync-schemas.ts
index c012b10bce..e47d696bb2 100644
--- a/backend/src/services/pki-sync/nutanix-prism-central/nutanix-prism-central-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/nutanix-prism-central/nutanix-prism-central-pki-sync-schemas.ts
@@ -4,7 +4,12 @@ import { openApiHidden } from "@app/server/lib/schemas";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-import { HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import {
+ HostCommandSchema,
+ PkiSyncFiltersField,
+ PkiSyncSchema,
+ UpdatePkiSyncFiltersField
+} from "@app/services/pki-sync/pki-sync-schemas";
export const NutanixPrismCentralPkiSyncConfigSchema = z.object({
clusterId: z.string().min(1, "Cluster ID is required"),
@@ -37,7 +42,8 @@ export const CreateNutanixPrismCentralPkiSyncSchema = z.object({
connectionId: z.string(),
projectId: z.string().trim().min(1).optional().describe(openApiHidden()),
applicationId: z.string().uuid().optional(),
- certificateIds: z.array(z.string().uuid()).optional()
+ certificateIds: z.array(z.string().uuid()).optional(),
+ filters: PkiSyncFiltersField
});
export const UpdateNutanixPrismCentralPkiSyncSchema = z.object({
@@ -47,7 +53,8 @@ export const UpdateNutanixPrismCentralPkiSyncSchema = z.object({
destinationConfig: NutanixPrismCentralPkiSyncConfigSchema.optional(),
syncOptions: NutanixPrismCentralPkiSyncOptionsSchema.optional(),
subscriberId: z.string().nullish(),
- connectionId: z.string().optional()
+ connectionId: z.string().optional(),
+ filters: UpdatePkiSyncFiltersField
});
export const NutanixPrismCentralPkiSyncListItemSchema = z.object({
diff --git a/backend/src/services/pki-sync/pki-sync-cleanup-queue.ts b/backend/src/services/pki-sync/pki-sync-cleanup-queue.ts
index abbb34f24f..8ad17d1ef2 100644
--- a/backend/src/services/pki-sync/pki-sync-cleanup-queue.ts
+++ b/backend/src/services/pki-sync/pki-sync-cleanup-queue.ts
@@ -2,13 +2,17 @@ import { getConfig } from "@app/lib/config/env";
import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
+import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";
import { TPkiSyncDALFactory } from "./pki-sync-dal";
import { TPkiSyncQueueFactory } from "./pki-sync-queue";
+const INELIGIBLE_LINK_BATCH = 500;
+
type TPkiSyncCleanupQueueServiceFactoryDep = {
cronJob: TCronJobFactory;
pkiSyncDAL: Pick<TPkiSyncDALFactory, "findPkiSyncsWithExpiredCertificates">;
- pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;
+ certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findIneligibleFilteredLinks">;
+ pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById" | "queuePkiSyncLinkMatchingCertificates">;
};
export type TPkiSyncCleanupQueueServiceFactory = ReturnType<typeof pkiSyncCleanupQueueServiceFactory>;
@@ -16,6 +20,7 @@ export type TPkiSyncCleanupQueueServiceFactory = ReturnType<typeof pkiSyncCleanu
export const pkiSyncCleanupQueueServiceFactory = ({
cronJob,
pkiSyncDAL,
+ certificateSyncDAL,
pkiSyncQueue
}: TPkiSyncCleanupQueueServiceFactoryDep) => {
const appCfg = getConfig();
@@ -53,6 +58,27 @@ export const pkiSyncCleanupQueueServiceFactory = ({
}
};
+ const reconcileIneligibleFilteredLinks = async () => {
+ try {
+ const stale = await certificateSyncDAL.findIneligibleFilteredLinks(INELIGIBLE_LINK_BATCH);
+
+ if (stale.length === 0) return;
+
+ logger.info(`cron[pki-sync-cleanup]: re-evaluating ${stale.length} certificate(s) held by a filtered sync`);
+
+ for (const { certificateId, applicationId } of stale) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ await pkiSyncQueue.queuePkiSyncLinkMatchingCertificates({ certificateId, applicationId });
+ } catch (error) {
+ logger.error(error, `Failed to queue a filter reconcile [certificateId=${certificateId}]`);
+ }
+ }
+ } catch (error) {
+ logger.error(error, "Failed to re-evaluate certificates held by a filtered sync");
+ }
+ };
+
const init = () => {
cronJob.register({
name: CronJobName.PkiSyncCleanup,
@@ -61,13 +87,20 @@ export const pkiSyncCleanupQueueServiceFactory = ({
enabled: !appCfg.isSecondaryInstance,
handler: async () => {
logger.info("cron[pki-sync-cleanup]: task started");
- await syncExpiredCertificatesForPkiSyncs();
+
+ const [expiredCertificateSweep] = await Promise.allSettled([
+ syncExpiredCertificatesForPkiSyncs(),
+ reconcileIneligibleFilteredLinks()
+ ]);
+
+ if (expiredCertificateSweep.status === "rejected") throw expiredCertificateSweep.reason;
}
});
};
return {
init,
- syncExpiredCertificatesForPkiSyncs
+ syncExpiredCertificatesForPkiSyncs,
+ reconcileIneligibleFilteredLinks
};
};
diff --git a/backend/src/services/pki-sync/pki-sync-dal.ts b/backend/src/services/pki-sync/pki-sync-dal.ts
index 1f1aa0f31e..0f920b9368 100644
--- a/backend/src/services/pki-sync/pki-sync-dal.ts
+++ b/backend/src/services/pki-sync/pki-sync-dal.ts
@@ -293,11 +293,13 @@ export const pkiSyncDALFactory = (db: TDbClient) => {
return expandPkiSync(pkiSync);
};
- const updateById = async (syncId: string, data: Parameters<(typeof pkiSyncOrm)["updateById"]>[1]) => {
- const pkiSync = (await pkiSyncOrm.transaction(async (tx) => {
+ const updateById = async (syncId: string, data: Parameters<(typeof pkiSyncOrm)["updateById"]>[1], outerTx?: Knex) => {
+ const run = async (tx: Knex) => {
const sync = await pkiSyncOrm.updateById(syncId, data, tx);
return basePkiSyncQuery({ filter: { id: sync.id }, db, tx }).first();
- }))!;
+ };
+
+ const pkiSync = (outerTx ? await run(outerTx) : await pkiSyncOrm.transaction(run))!;
return expandPkiSync(pkiSync);
};
@@ -418,7 +420,10 @@ export const pkiSyncDALFactory = (db: TDbClient) => {
}
};
+ const primaryNode = () => db.primaryNode();
+
return {
+ primaryNode,
...pkiSyncOrm,
recordHealthCheckOutcome,
findFailureNotificationRecipients,
diff --git a/backend/src/services/pki-sync/pki-sync-filter-fns.ts b/backend/src/services/pki-sync/pki-sync-filter-fns.ts
new file mode 100644
index 0000000000..bf376e2a64
--- /dev/null
+++ b/backend/src/services/pki-sync/pki-sync-filter-fns.ts
@@ -0,0 +1,10 @@
+import { TPkiSyncFilters } from "./pki-sync-types";
+
+export const PKI_SYNC_MAX_LINKED_CERTIFICATES = 500;
+
+export const PKI_SYNC_FILTER_KINDS = ["profileIds", "certificateOrderIds", "metadata"] as const;
+
+export const hasAnyPkiSyncFilter = (filters: TPkiSyncFilters | null | undefined): boolean =>
+ Boolean(filters && PKI_SYNC_FILTER_KINDS.some((kind) => filters[kind] !== undefined));
+
+export type TPkiSyncFilterKind = (typeof PKI_SYNC_FILTER_KINDS)[number];
diff --git a/backend/src/services/pki-sync/pki-sync-filter-reconcile-fns.ts b/backend/src/services/pki-sync/pki-sync-filter-reconcile-fns.ts
new file mode 100644
index 0000000000..ebde7bd943
--- /dev/null
+++ b/backend/src/services/pki-sync/pki-sync-filter-reconcile-fns.ts
@@ -0,0 +1,232 @@
+import { Knex } from "knex";
+
+import { AuditLogInfo, EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
+import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { ActorType } from "@app/services/auth/auth-type";
+
+import { TCertificateDALFactory } from "../certificate/certificate-dal";
+import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";
+import { PkiSync } from "./pki-sync-enums";
+import { hasAnyPkiSyncFilter } from "./pki-sync-filter-fns";
+import { assertPkiSyncCanHoldCertificateCount } from "./pki-sync-fns";
+import {
+ TPkiSyncCertificateDiff,
+ TPkiSyncCertificateRef,
+ TPkiSyncFilters,
+ TQueuePkiSyncRemoveCertificatesByIdDTO,
+ TQueuePkiSyncSyncCertificatesByIdDTO
+} from "./pki-sync-types";
+
+export type TPkiSyncReconcileTarget = {
+ id: string;
+ name: string;
+ projectId: string;
+ applicationId?: string | null;
+ destination: string;
+ destinationConfig: Record<string, unknown>;
+ syncOptions: unknown;
+ isAutoSyncEnabled: boolean;
+};
+
+type TPkiSyncFilterReconcileDeps = {
+ certificateDAL: Pick<TCertificateDALFactory, "findCertificatesMatchingSyncFilters" | "find">;
+ certificateSyncDAL: Pick<
+ TCertificateSyncDALFactory,
+ | "findCertificateIdsByPkiSyncId"
+ | "findByPkiSyncId"
+ | "addCertificates"
+ | "removeCertificates"
+ | "transaction"
+ | "primaryNode"
+ >;
+ pkiSyncQueue: {
+ queuePkiSyncSyncCertificatesById: (payload: TQueuePkiSyncSyncCertificatesByIdDTO) => Promise<unknown>;
+ queuePkiSyncRemoveCertificatesById: (payload: TQueuePkiSyncRemoveCertificatesByIdDTO) => Promise<unknown>;
+ };
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
+};
+
+const PKI_SYNC_FILTER_LOCK_TTL_MS = 60 * 1000;
+
+export const withPkiSyncFilterLock = async <T>(
+ keyStore: Pick<TKeyStoreFactory, "acquireLock">,
+ syncId: string,
+ run: () => Promise<T>
+): Promise<T> => {
+ let lock: Awaited<ReturnType<TKeyStoreFactory["acquireLock"]>>;
+
+ try {
+ lock = await keyStore.acquireLock([KeyStorePrefixes.PkiSyncFilterLock(syncId)], PKI_SYNC_FILTER_LOCK_TTL_MS, {
+ retryCount: 20,
+ retryDelay: 500
+ });
+ } catch (error) {
+ logger.error(error, `Failed to acquire the PKI sync filter lock [pkiSyncId=${syncId}]`);
+ throw new BadRequestError({
+ message: "Another change to this PKI sync's certificates is still being applied. Try again in a moment."
+ });
+ }
+
+ try {
+ return await run();
+ } finally {
+ await lock.release();
+ }
+};
+
+const getPkiSyncLinkDestinationTargets = (record: {
+ externalIdentifier?: string | null;
+ syncMetadata?: unknown;
+}): string[] => {
+ const files = (record.syncMetadata as { files?: string[] } | null)?.files ?? [];
+ return [...(record.externalIdentifier ? [record.externalIdentifier] : []), ...files];
+};
+
+export const computePkiSyncCertificateDiff = async (
+ pkiSync: TPkiSyncReconcileTarget,
+ filters: TPkiSyncFilters | null | undefined,
+ { certificateDAL, certificateSyncDAL }: Pick<TPkiSyncFilterReconcileDeps, "certificateDAL" | "certificateSyncDAL">
+): Promise<TPkiSyncCertificateDiff> => {
+ if (!pkiSync.applicationId) return { matched: [], toLink: [], toUnlink: [] };
+
+ const matched = hasAnyPkiSyncFilter(filters)
+ ? await certificateDAL.findCertificatesMatchingSyncFilters(filters, {
+ projectId: pkiSync.projectId,
+ applicationId: pkiSync.applicationId
+ })
+ : [];
+
+ const linkedIds = await certificateSyncDAL.findCertificateIdsByPkiSyncId(
+ pkiSync.id,
+ certificateSyncDAL.primaryNode()
+ );
+ const linkedIdSet = new Set(linkedIds);
+ const matchedIdSet = new Set(matched.map((certificate) => certificate.id));
+
+ const toLink = matched.filter((certificate) => !linkedIdSet.has(certificate.id));
+ const unlinkIds = linkedIds.filter((id) => !matchedIdSet.has(id));
+
+ const toUnlink: TPkiSyncCertificateRef[] = unlinkIds.length
+ ? (await certificateDAL.find({ projectId: pkiSync.projectId, $in: { id: unlinkIds } })).map(
+ ({ id, commonName }) => ({ id, commonName })
+ )
+ : [];
+
+ return { matched, toLink, toUnlink };
+};
+
+export const assertPkiSyncCanHoldMatchedCertificates = (pkiSync: TPkiSyncReconcileTarget, matchedCount: number) =>
+ assertPkiSyncCanHoldCertificateCount(
+ pkiSync.destination as PkiSync,
+ pkiSync.syncOptions as Record<string, unknown> | undefined,
+ pkiSync.destinationConfig,
+ matchedCount
+ );
+
+export const applyPkiSyncCertificateDiff = async (
+ pkiSync: TPkiSyncReconcileTarget,
+ diff: TPkiSyncCertificateDiff,
+ deps: TPkiSyncFilterReconcileDeps,
+ auditLogInfo?: AuditLogInfo,
+ writeFilters?: (tx: Knex) => Promise<void>
+): Promise<{ linked: TPkiSyncCertificateRef[]; unlinked: TPkiSyncCertificateRef[] }> => {
+ const { certificateSyncDAL, pkiSyncQueue, auditLogService } = deps;
+ const { toLink, toUnlink } = diff;
+
+ const unlinkIds = new Set(toUnlink.map((certificate) => certificate.id));
+ const canRemoveCertificates = Boolean(
+ (pkiSync.syncOptions as { canRemoveCertificates?: boolean } | undefined)?.canRemoveCertificates
+ );
+
+ const linkRecords =
+ canRemoveCertificates && unlinkIds.size
+ ? await certificateSyncDAL.findByPkiSyncId(pkiSync.id, certificateSyncDAL.primaryNode())
+ : [];
+
+ const destinationTargetsStillHeld = new Set(
+ linkRecords
+ .filter((record) => record.certificateId && !unlinkIds.has(record.certificateId))
+ .flatMap((record) => getPkiSyncLinkDestinationTargets(record))
+ );
+
+ const idsAtDestination = linkRecords
+ .filter((record) => {
+ if (!record.certificateId || !unlinkIds.has(record.certificateId)) return false;
+
+ const targets = getPkiSyncLinkDestinationTargets(record);
+ return targets.length > 0 && targets.every((target) => !destinationTargetsStillHeld.has(target));
+ })
+ .map((record) => record.certificateId);
+
+ const idsOnlyLinked = [...unlinkIds].filter((id) => !idsAtDestination.includes(id));
+
+ await certificateSyncDAL.transaction(async (tx) => {
+ if (writeFilters) await writeFilters(tx);
+
+ if (toLink.length > 0) {
+ await certificateSyncDAL.addCertificates(
+ pkiSync.id,
+ toLink.map((certificate) => ({ certificateId: certificate.id })),
+ tx
+ );
+ }
+
+ if (idsOnlyLinked.length > 0) {
+ await certificateSyncDAL.removeCertificates(pkiSync.id, idsOnlyLinked, tx);
+ }
+ });
+
+ if (toLink.length === 0 && toUnlink.length === 0) return { linked: [], unlinked: [] };
+
+ const auditActor: AuditLogInfo = auditLogInfo ?? { actor: { type: ActorType.PLATFORM, metadata: {} } };
+
+ if (toLink.length > 0) {
+ await auditLogService.createAuditLog({
+ ...auditActor,
+ projectId: pkiSync.projectId,
+ event: {
+ type: EventType.PKI_SYNC_LINK_CERTIFICATES,
+ metadata: {
+ pkiSyncId: pkiSync.id,
+ name: pkiSync.name,
+ count: toLink.length,
+ certificates: toLink.map(({ id, commonName }) => ({ id, commonName })),
+ ...(pkiSync.applicationId ? { applicationId: pkiSync.applicationId } : {})
+ }
+ }
+ });
+ }
+
+ if (toUnlink.length > 0) {
+ if (idsAtDestination.length > 0) {
+ await pkiSyncQueue.queuePkiSyncRemoveCertificatesById({
+ syncId: pkiSync.id,
+ certificateIds: idsAtDestination
+ });
+ }
+
+ await auditLogService.createAuditLog({
+ ...auditActor,
+ projectId: pkiSync.projectId,
+ event: {
+ type: EventType.PKI_SYNC_UNLINK_CERTIFICATES,
+ metadata: {
+ pkiSyncId: pkiSync.id,
+ name: pkiSync.name,
+ count: toUnlink.length,
+ certificates: toUnlink,
+ removedFromDestination: idsAtDestination.length > 0,
+ ...(pkiSync.applicationId ? { applicationId: pkiSync.applicationId } : {})
+ }
+ }
+ });
+ }
+
+ if (toLink.length > 0 && pkiSync.isAutoSyncEnabled) {
+ await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: pkiSync.id });
+ }
+
+ return { linked: toLink, unlinked: toUnlink };
+};
diff --git a/backend/src/services/pki-sync/pki-sync-fns.test.ts b/backend/src/services/pki-sync/pki-sync-fns.test.ts
index b8a25af106..ec2a30bca3 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,13 @@
import { PkiSync } from "./pki-sync-enums";
-import { getPkiSyncProviderCapabilities, matchesCertificateNameSchema, parsePkiSyncErrorMessage } from "./pki-sync-fns";
+import { hasAnyPkiSyncFilter, PKI_SYNC_MAX_LINKED_CERTIFICATES } from "./pki-sync-filter-fns";
+import {
+ assertFiltersCannotExceedCertificateCap,
+ assertPkiSyncCanHoldCertificateCount,
+ getPkiSyncCertificateCap,
+ getPkiSyncProviderCapabilities,
+ matchesCertificateNameSchema,
+ parsePkiSyncErrorMessage
+} from "./pki-sync-fns";
// A dash-stripped UUID (what {{certificateId}}, {{profileId}}, {{applicationId}} resolve to).
const HEX = "550e8400e29b41d4a716446655440000";
@@ -146,3 +154,252 @@ describe("parsePkiSyncErrorMessage", () => {
expect(parsePkiSyncErrorMessage({ weird: true })).toBe("An unknown error occurred during PKI sync operation");
});
});
+
+describe("assertPkiSyncCanHoldCertificateCount", () => {
+ const multiCertSchema = { certificateNameSchema: "Infisical-{{certificateId}}" };
+
+ test("allows a count within both the global cap and the destination cap", () => {
+ expect(() =>
+ assertPkiSyncCanHoldCertificateCount(PkiSync.AwsCertificateManager, multiCertSchema, undefined, 499)
+ ).not.toThrow();
+ expect(() =>
+ assertPkiSyncCanHoldCertificateCount(
+ PkiSync.AwsCertificateManager,
+ multiCertSchema,
+ undefined,
+ PKI_SYNC_MAX_LINKED_CERTIFICATES
+ )
+ ).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)
+ ).not.toThrow();
+ expect(() =>
+ assertPkiSyncCanHoldCertificateCount(PkiSync.NutanixPrismCentral, multiCertSchema, undefined, 2)
+ ).toThrow(/at most 1 certificate/);
+ });
+
+ test("does not constrain a sync that holds one certificate", () => {
+ expect(() =>
+ assertPkiSyncCanHoldCertificateCount(PkiSync.LinuxServer, { certificateNameSchema: "static" }, undefined, 1)
+ ).not.toThrow();
+ });
+
+ test("rejects a name schema with no placeholder once more than one certificate is held", () => {
+ expect(() =>
+ assertPkiSyncCanHoldCertificateCount(PkiSync.LinuxServer, { certificateNameSchema: "static" }, undefined, 2)
+ ).toThrow(/no placeholder/);
+ });
+
+ test("rejects a sync with no name schema at all once more than one certificate is held", () => {
+ expect(() => assertPkiSyncCanHoldCertificateCount(PkiSync.LinuxServer, undefined, undefined, 2)).toThrow(
+ /no placeholder/
+ );
+ });
+
+ test("accepts a name schema with a placeholder", () => {
+ expect(() =>
+ assertPkiSyncCanHoldCertificateCount(PkiSync.LinuxServer, multiCertSchema, undefined, 2)
+ ).not.toThrow();
+ });
+
+ test("rejects a post-sync command that names a single certificate", () => {
+ expect(() =>
+ assertPkiSyncCanHoldCertificateCount(
+ PkiSync.LinuxServer,
+ { ...multiCertSchema, postSyncCommand: "cat {{certificatePath}}" },
+ undefined,
+ 2
+ )
+ ).toThrow(/certificatePath/);
+ });
+
+ test("rejects a health-check command that names a single certificate", () => {
+ expect(() =>
+ assertPkiSyncCanHoldCertificateCount(
+ PkiSync.LinuxServer,
+ { ...multiCertSchema, healthCheckCommand: "openssl x509 -in {{certificatePath}}" },
+ undefined,
+ 2
+ )
+ ).toThrow(/certificatePath/);
+ });
+
+ test("accepts a command that covers every certificate in the run", () => {
+ expect(() =>
+ assertPkiSyncCanHoldCertificateCount(
+ PkiSync.LinuxServer,
+ { ...multiCertSchema, postSyncCommand: "ls {{certificateDirectory}}" },
+ undefined,
+ 2
+ )
+ ).not.toThrow();
+ });
+
+ test("ignores destinations without a config-derived cap", () => {
+ expect(() =>
+ assertPkiSyncCanHoldCertificateCount(PkiSync.AwsCertificateManager, multiCertSchema, { region: "us-east-2" }, 500)
+ ).not.toThrow();
+ });
+
+ test("applies the GCP certificate map entry cap", () => {
+ const gcp = { certificateMapBinding: { certificateMap: "my-map" } };
+ expect(() =>
+ assertPkiSyncCanHoldCertificateCount(PkiSync.GcpCertificateManager, multiCertSchema, gcp, 4)
+ ).not.toThrow();
+ expect(() => assertPkiSyncCanHoldCertificateCount(PkiSync.GcpCertificateManager, multiCertSchema, gcp, 5)).toThrow(
+ /at most 4 certificates/
+ );
+ });
+});
+
+describe("hasAnyPkiSyncFilter", () => {
+ test("is false when no filters are stored, which means the sync holds nothing", () => {
+ expect(hasAnyPkiSyncFilter(null)).toBe(false);
+ expect(hasAnyPkiSyncFilter(undefined)).toBe(false);
+ expect(hasAnyPkiSyncFilter({})).toBe(false);
+ });
+
+ test("is true for a present filter, empty or not", () => {
+ expect(hasAnyPkiSyncFilter({ profileIds: [] })).toBe(true);
+ expect(hasAnyPkiSyncFilter({ certificateOrderIds: [] })).toBe(true);
+ expect(hasAnyPkiSyncFilter({ metadata: [] })).toBe(true);
+ expect(hasAnyPkiSyncFilter({ profileIds: ["p1"] })).toBe(true);
+ });
+});
+
+describe("getPkiSyncCertificateCap", () => {
+ const multiCertSchema = { certificateNameSchema: "{{certificateId}}" };
+
+ test("no cap when the destination and options both allow many", () => {
+ expect(getPkiSyncCertificateCap(PkiSync.AwsCertificateManager, multiCertSchema, {})).toBeUndefined();
+ });
+
+ test("caps at 1 for a destination that holds one certificate", () => {
+ expect(getPkiSyncCertificateCap(PkiSync.NutanixPrismCentral, multiCertSchema, {})).toBe(1);
+ });
+
+ test("caps at 1 when the name schema has no placeholder", () => {
+ expect(getPkiSyncCertificateCap(PkiSync.LinuxServer, { certificateNameSchema: "static" }, {})).toBe(1);
+ });
+
+ test("caps at 1 when a host command names a single certificate", () => {
+ expect(
+ getPkiSyncCertificateCap(
+ PkiSync.LinuxServer,
+ { ...multiCertSchema, postSyncCommand: "cat {{certificatePath}}" },
+ {}
+ )
+ ).toBe(1);
+ });
+
+ test("caps at the GCP map-entry limit when a certificate map is bound", () => {
+ expect(
+ getPkiSyncCertificateCap(PkiSync.GcpCertificateManager, multiCertSchema, {
+ certificateMapBinding: { certificateMap: "my-map" }
+ })
+ ).toBe(4);
+ });
+
+ test("takes the smallest applicable cap", () => {
+ expect(
+ getPkiSyncCertificateCap(
+ PkiSync.GcpCertificateManager,
+ { certificateNameSchema: "static" },
+ {
+ certificateMapBinding: { certificateMap: "my-map" }
+ }
+ )
+ ).toBe(1);
+ });
+});
+
+describe("assertFiltersCannotExceedCertificateCap", () => {
+ const single = { certificateNameSchema: "static" };
+ const many = { certificateNameSchema: "{{certificateId}}" };
+ const assertSingle = (filters: Parameters<typeof assertFiltersCannotExceedCertificateCap>[3]) => () =>
+ assertFiltersCannotExceedCertificateCap(PkiSync.LinuxServer, single, {}, filters);
+
+ test("an uncapped sync accepts any filter", () => {
+ expect(() =>
+ assertFiltersCannotExceedCertificateCap(PkiSync.LinuxServer, many, {}, { profileIds: ["p"] })
+ ).not.toThrow();
+ expect(() => assertFiltersCannotExceedCertificateCap(PkiSync.LinuxServer, many, {}, null)).not.toThrow();
+ });
+
+ test("a single certificate order is accepted", () => {
+ expect(assertSingle({ certificateOrderIds: ["o"] })).not.toThrow();
+ });
+
+ test("an empty list is accepted, since it matches nothing", () => {
+ expect(assertSingle({ certificateOrderIds: [] })).not.toThrow();
+ });
+
+ test("a certificate order combined with a growable filter is rejected", () => {
+ expect(assertSingle({ certificateOrderIds: ["o"], profileIds: ["p"] })).toThrow(
+ /only accepts a certificate order filter.*certificate profile/s
+ );
+ expect(assertSingle({ certificateOrderIds: ["o"], metadata: [{ key: "tier" }] })).toThrow(
+ /only accepts a certificate order filter.*metadata/s
+ );
+ expect(assertSingle({ certificateOrderIds: ["o"], profileIds: ["p"], metadata: [{ key: "tier" }] })).toThrow(
+ /certificate profile and metadata/
+ );
+ });
+
+ test("two certificate orders are rejected", () => {
+ expect(assertSingle({ certificateOrderIds: ["o1", "o2"] })).toThrow(/can name at most 1 certificate order/);
+ });
+
+ test("a profile filter on its own is rejected, because it grows as certificates are issued", () => {
+ expect(assertSingle({ profileIds: ["p"] })).toThrow(/only accepts a certificate order filter/);
+ });
+
+ test("a metadata filter on its own is rejected", () => {
+ expect(assertSingle({ metadata: [{ key: "tier", value: "prod" }] })).toThrow(
+ /only accepts a certificate order filter/
+ );
+ });
+
+ test("a capped sync rejects a growable filter whatever its own cap is", () => {
+ const gcp = { certificateMapBinding: { certificateMap: "my-map" } };
+ expect(() =>
+ assertFiltersCannotExceedCertificateCap(PkiSync.GcpCertificateManager, many, gcp, {
+ certificateOrderIds: ["o1"],
+ profileIds: ["p"]
+ })
+ ).toThrow(/holds at most 4 certificates, so it only accepts a certificate order filter/);
+ });
+
+ test("no filters at all is accepted, since a sync with no filters holds nothing", () => {
+ expect(assertSingle(null)).not.toThrow();
+ expect(assertSingle(undefined)).not.toThrow();
+ expect(assertSingle({})).not.toThrow();
+ });
+
+ test("four certificate orders are accepted under the GCP map-entry cap but five are not", () => {
+ const gcp = { certificateMapBinding: { certificateMap: "my-map" } };
+ const four = ["o1", "o2", "o3", "o4"];
+ expect(() =>
+ assertFiltersCannotExceedCertificateCap(PkiSync.GcpCertificateManager, many, gcp, { certificateOrderIds: four })
+ ).not.toThrow();
+ expect(() =>
+ assertFiltersCannotExceedCertificateCap(PkiSync.GcpCertificateManager, many, gcp, {
+ certificateOrderIds: [...four, "e"]
+ })
+ ).toThrow(/can name at most 4 certificate orders/);
+ });
+});
diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.ts
index 6b6d41ea9b..e67cc37fc7 100644
--- a/backend/src/services/pki-sync/pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-fns.ts
@@ -25,14 +25,17 @@ import { CLOUDFLARE_CUSTOM_CERTIFICATE_PKI_SYNC_LIST_OPTION } from "./cloudflare
import { cloudflareCustomCertificatePkiSyncFactory } from "./cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-fns";
import { F5_BIG_IP_PKI_SYNC_LIST_OPTION } from "./f5-big-ip/f5-big-ip-pki-sync-constants";
import { f5BigIpPkiSyncFactory } from "./f5-big-ip/f5-big-ip-pki-sync-fns";
-import { GCP_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION } from "./gcp-certificate-manager/gcp-certificate-manager-pki-sync-constants";
+import {
+ GCP_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION,
+ GCP_MAX_CERTIFICATES_PER_MAP_ENTRY
+} from "./gcp-certificate-manager/gcp-certificate-manager-pki-sync-constants";
import { gcpCertificateManagerPkiSyncFactory } from "./gcp-certificate-manager/gcp-certificate-manager-pki-sync-fns";
import {
TGcpCertificateManagerPkiSyncConfig,
TGcpCertificateManagerPkiSyncConfigUpdate
} from "./gcp-certificate-manager/gcp-certificate-manager-pki-sync-types";
import {
- assertGcpCertificateManagerCertificateCount,
+ buildGcpTooManyCertificatesMessage,
resolveGcpCertificateManagerConfigUpdate
} from "./gcp-certificate-manager/gcp-certificate-manager-pki-sync-update-fns";
import { KEMP_LOADMASTER_PKI_SYNC_LIST_OPTION } from "./kemp-loadmaster/kemp-loadmaster-pki-sync-constants";
@@ -45,14 +48,34 @@ import { NUTANIX_PRISM_CENTRAL_PKI_SYNC_LIST_OPTION } from "./nutanix-prism-cent
import { nutanixPrismCentralPkiSyncFactory } from "./nutanix-prism-central/nutanix-prism-central-pki-sync-fns";
import {
buildManagedCertificateNameRegexSource,
+ certificateNameSchemaAllowsMultipleCertificates,
SHORT_UUID_NAME_REGEX_FRAGMENT,
UUID_NAME_REGEX_FRAGMENT
} from "./pki-sync-certificate-name-fns";
import { PkiSync } from "./pki-sync-enums";
import { PkiSyncError } from "./pki-sync-errors";
-import { THostCommandResult } from "./pki-sync-host-command-fns";
-import { getPkiSyncConnectionApps } from "./pki-sync-maps";
-import { TCertificateMap, THealthCheckTarget, TPkiSyncSyncResult, TPkiSyncWithCredentials } from "./pki-sync-types";
+import {
+ hasAnyPkiSyncFilter,
+ PKI_SYNC_FILTER_KINDS,
+ PKI_SYNC_MAX_LINKED_CERTIFICATES,
+ TPkiSyncFilterKind
+} from "./pki-sync-filter-fns";
+import { getHealthCheckCommand } from "./pki-sync-health-check-command-fns";
+import {
+ findSingleCertificateHostCommandVariables,
+ formatHostCommandVariables,
+ HostCommandKind,
+ THostCommandResult
+} from "./pki-sync-host-command-fns";
+import { getPkiSyncConnectionApps, PKI_SYNC_NAME_MAP } from "./pki-sync-maps";
+import { getPostSyncCommand } from "./pki-sync-post-sync-command-fns";
+import {
+ TCertificateMap,
+ THealthCheckTarget,
+ TPkiSyncFilters,
+ TPkiSyncSyncResult,
+ TPkiSyncWithCredentials
+} from "./pki-sync-types";
import { WINDOWS_SERVER_PKI_SYNC_LIST_OPTION } from "./windows-server/windows-server-pki-sync-constants";
import { windowsServerPkiSyncFactory } from "./windows-server/windows-server-pki-sync-fns";
@@ -112,7 +135,7 @@ export const getPkiSyncProviderCapabilities = (destination: PkiSync) => {
};
};
-export const getPkiSyncMaxCertificates = (destination: PkiSync): number | undefined => {
+const getPkiSyncMaxCertificates = (destination: PkiSync): number | undefined => {
const providerOption = PKI_SYNC_LIST_OPTIONS[destination];
if (providerOption && "maxCertificates" in providerOption) {
return providerOption.maxCertificates;
@@ -135,19 +158,6 @@ export const resolvePkiSyncDestinationConfigUpdate = (
return nextConfig;
};
-export const assertPkiSyncDestinationConfigAllowsCertificateCount = (
- destination: PkiSync,
- destinationConfig: Record<string, unknown> | undefined,
- resultingCertificateCount: number
-) => {
- if (destination === PkiSync.GcpCertificateManager) {
- assertGcpCertificateManagerCertificateCount(
- destinationConfig as TGcpCertificateManagerPkiSyncConfig | undefined,
- resultingCertificateCount
- );
- }
-};
-
export const matchesSchema = <T extends ZodSchema>(schema: T, data: unknown): data is z.infer<T> => {
return schema.safeParse(data).success;
};
@@ -365,6 +375,7 @@ export const PkiSyncFns = {
checkPkiSyncDestination(pkiSync, PkiSync.LinuxServer as PkiSync);
const linuxServerPkiSync = linuxServerPkiSyncFactory({
certificateSyncDAL: dependencies.certificateSyncDAL,
+ certificateDAL: dependencies.certificateDAL,
gatewayV2Service: dependencies.gatewayV2Service,
gatewayPoolService: dependencies.gatewayPoolService,
keyStore: dependencies.keyStore
@@ -378,6 +389,7 @@ export const PkiSyncFns = {
}
const windowsServerPkiSync = windowsServerPkiSyncFactory({
certificateSyncDAL: dependencies.certificateSyncDAL,
+ certificateDAL: dependencies.certificateDAL,
gatewayV2Service: dependencies.gatewayV2Service,
gatewayPoolService: dependencies.gatewayPoolService,
keyStore: dependencies.keyStore
@@ -412,6 +424,7 @@ export const PkiSyncFns = {
certificateMap: TCertificateMap,
dependencies: {
certificateSyncDAL: TCertificateSyncDALFactory;
+ certificateDAL: Pick<TCertificateDALFactory, "findActiveCertificatesByIds">;
gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId" | "getGatewayById">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
@@ -421,6 +434,7 @@ export const PkiSyncFns = {
case PkiSync.LinuxServer: {
const linuxServerPkiSync = linuxServerPkiSyncFactory({
certificateSyncDAL: dependencies.certificateSyncDAL,
+ certificateDAL: dependencies.certificateDAL,
gatewayV2Service: dependencies.gatewayV2Service,
gatewayPoolService: dependencies.gatewayPoolService,
keyStore: dependencies.keyStore
@@ -436,6 +450,7 @@ export const PkiSyncFns = {
}
const windowsServerPkiSync = windowsServerPkiSyncFactory({
certificateSyncDAL: dependencies.certificateSyncDAL,
+ certificateDAL: dependencies.certificateDAL,
gatewayV2Service: dependencies.gatewayV2Service,
gatewayPoolService: dependencies.gatewayPoolService,
keyStore: dependencies.keyStore
@@ -451,6 +466,7 @@ export const PkiSyncFns = {
pkiSync: THealthCheckTarget,
dependencies: {
certificateSyncDAL: TCertificateSyncDALFactory;
+ certificateDAL: Pick<TCertificateDALFactory, "findActiveCertificatesByIds">;
gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId" | "getGatewayById">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
@@ -459,6 +475,7 @@ export const PkiSyncFns = {
if (pkiSync.destination === PkiSync.LinuxServer) {
const linuxServerPkiSync = linuxServerPkiSyncFactory({
certificateSyncDAL: dependencies.certificateSyncDAL,
+ certificateDAL: dependencies.certificateDAL,
gatewayV2Service: dependencies.gatewayV2Service,
gatewayPoolService: dependencies.gatewayPoolService,
keyStore: dependencies.keyStore
@@ -476,6 +493,7 @@ export const PkiSyncFns = {
}
const windowsServerPkiSync = windowsServerPkiSyncFactory({
certificateSyncDAL: dependencies.certificateSyncDAL,
+ certificateDAL: dependencies.certificateDAL,
gatewayV2Service: dependencies.gatewayV2Service,
gatewayPoolService: dependencies.gatewayPoolService,
keyStore: dependencies.keyStore
@@ -622,6 +640,7 @@ export const PkiSyncFns = {
checkPkiSyncDestination(pkiSync, PkiSync.LinuxServer as PkiSync);
const linuxServerPkiSync = linuxServerPkiSyncFactory({
certificateSyncDAL: dependencies.certificateSyncDAL,
+ certificateDAL: dependencies.certificateDAL,
gatewayV2Service: dependencies.gatewayV2Service,
gatewayPoolService: dependencies.gatewayPoolService,
keyStore: dependencies.keyStore
@@ -639,6 +658,7 @@ export const PkiSyncFns = {
}
const windowsServerPkiSync = windowsServerPkiSyncFactory({
certificateSyncDAL: dependencies.certificateSyncDAL,
+ certificateDAL: dependencies.certificateDAL,
gatewayV2Service: dependencies.gatewayV2Service,
gatewayPoolService: dependencies.gatewayPoolService,
keyStore: dependencies.keyStore
@@ -671,3 +691,130 @@ export const PkiSyncFns = {
}
}
};
+
+type TPkiSyncCertificateCap = { cap: number; reason: (resultingCertificateCount: number) => string };
+
+const getPkiSyncCertificateCaps = (
+ destination: PkiSync,
+ syncOptions: Record<string, unknown> | undefined,
+ destinationConfig: Record<string, unknown> | undefined
+): TPkiSyncCertificateCap[] => {
+ const caps: TPkiSyncCertificateCap[] = [];
+
+ const destinationMax = getPkiSyncMaxCertificates(destination);
+ if (destinationMax !== undefined) {
+ caps.push({
+ cap: destinationMax,
+ reason: () =>
+ `${PKI_SYNC_NAME_MAP[destination]} PKI sync supports at most ${destinationMax} certificate${
+ destinationMax === 1 ? "" : "s"
+ }`
+ });
+ }
+
+ if (!certificateNameSchemaAllowsMultipleCertificates(syncOptions?.certificateNameSchema as string | undefined)) {
+ caps.push({
+ cap: 1,
+ reason: () =>
+ "This PKI sync's certificate name schema has no placeholder, so it holds only one certificate. Add {{certificateId}} or {{commonName}} to hold more."
+ });
+ }
+
+ [
+ { kind: HostCommandKind.HealthCheck, command: getHealthCheckCommand(syncOptions) },
+ { kind: HostCommandKind.PostSync, command: getPostSyncCommand(syncOptions) }
+ ].forEach(({ kind, command }) => {
+ const singleCertificateVariables = findSingleCertificateHostCommandVariables(command);
+
+ if (singleCertificateVariables.length > 0) {
+ caps.push({
+ cap: 1,
+ reason: () =>
+ `This sync's ${kind} uses ${formatHostCommandVariables(
+ singleCertificateVariables
+ )}. A variable that names one certificate can only be used on a sync with a single certificate linked. Use {{certificateFiles}} or {{certificateDirectory}} to write a command that covers every certificate in the run.`
+ });
+ }
+ });
+
+ if (destination === PkiSync.GcpCertificateManager) {
+ const gcpConfig = destinationConfig as TGcpCertificateManagerPkiSyncConfig | undefined;
+ if (gcpConfig?.certificateMapBinding?.certificateMap) {
+ caps.push({
+ cap: GCP_MAX_CERTIFICATES_PER_MAP_ENTRY,
+ reason: (resultingCertificateCount) =>
+ buildGcpTooManyCertificatesMessage(gcpConfig.certificateMapBinding!.certificateMap, resultingCertificateCount)
+ });
+ }
+ }
+
+ return caps;
+};
+
+export const getPkiSyncCertificateCap = (
+ destination: PkiSync,
+ syncOptions: Record<string, unknown> | undefined,
+ destinationConfig: Record<string, unknown> | undefined
+): number | undefined => {
+ const caps = getPkiSyncCertificateCaps(destination, syncOptions, destinationConfig);
+ return caps.length ? Math.min(...caps.map(({ cap }) => cap)) : undefined;
+};
+
+export const assertPkiSyncCanHoldCertificateCount = (
+ destination: PkiSync,
+ 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`
+ });
+ }
+
+ const exceeded = getPkiSyncCertificateCaps(destination, syncOptions, destinationConfig).find(
+ ({ cap }) => resultingCertificateCount > cap
+ );
+
+ if (exceeded) throw new BadRequestError({ message: exceeded.reason(resultingCertificateCount) });
+};
+
+const PKI_SYNC_FILTER_LABELS: Record<TPkiSyncFilterKind, string> = {
+ profileIds: "certificate profile",
+ certificateOrderIds: "certificate order",
+ metadata: "metadata"
+};
+
+export const assertFiltersCannotExceedCertificateCap = (
+ destination: PkiSync,
+ syncOptions: Record<string, unknown> | undefined,
+ destinationConfig: Record<string, unknown> | undefined,
+ filters: TPkiSyncFilters | null | undefined
+) => {
+ const cap = getPkiSyncCertificateCap(destination, syncOptions, destinationConfig);
+ if (cap === undefined) return;
+ if (!hasAnyPkiSyncFilter(filters)) return;
+
+ const noun = `${cap} certificate${cap === 1 ? "" : "s"}`;
+
+ const growableKinds = PKI_SYNC_FILTER_KINDS.filter(
+ (kind) => kind !== "certificateOrderIds" && filters?.[kind] !== undefined
+ );
+
+ if (growableKinds.length > 0) {
+ throw new BadRequestError({
+ message: `This PKI sync holds at most ${noun}, so it only accepts a certificate order filter. Remove the ${growableKinds
+ .map((kind) => PKI_SYNC_FILTER_LABELS[kind])
+ .join(" and ")} filter.`
+ });
+ }
+
+ const orders = filters?.certificateOrderIds ?? [];
+ if (orders.length > cap) {
+ throw new BadRequestError({
+ message: `This PKI sync holds at most ${noun}, so its filter can name at most ${cap} certificate order${
+ cap === 1 ? "" : "s"
+ }. It names ${orders.length}.`
+ });
+ }
+};
diff --git a/backend/src/services/pki-sync/pki-sync-health-check-queue.ts b/backend/src/services/pki-sync/pki-sync-health-check-queue.ts
index 200dbca8e2..a2bb7d3c4d 100644
--- a/backend/src/services/pki-sync/pki-sync-health-check-queue.ts
+++ b/backend/src/services/pki-sync/pki-sync-health-check-queue.ts
@@ -29,6 +29,7 @@ import { TPkiSyncDALFactory } from "./pki-sync-dal";
import { PKI_SYNC_CONNECTION_LOCK_RETRY, PkiSync, PkiSyncFailureKind, PkiSyncStatus } from "./pki-sync-enums";
import { PkiSyncError } from "./pki-sync-errors";
import { notifyPkiSyncFailure } from "./pki-sync-failure-notification-fns";
+import { hasAnyPkiSyncFilter } from "./pki-sync-filter-fns";
import { PkiSyncFns, truncateSyncMessage } from "./pki-sync-fns";
import {
assertHealthCheckCommandIsTestable,
@@ -41,7 +42,7 @@ import {
} from "./pki-sync-health-check-command-fns";
import { commandNeedsCertificateData, HostCommandFailure } from "./pki-sync-host-command-fns";
import { getPkiSyncTargetHost } from "./pki-sync-target-host-fns";
-import { TCertificateMap, THealthCheckTarget, TPkiSyncRaw } from "./pki-sync-types";
+import { TCertificateMap, THealthCheckTarget, TPkiSyncFilters, TPkiSyncRaw } from "./pki-sync-types";
const ENQUEUE_CHUNK_SIZE = 200;
const WORKER_CONCURRENCY = 3;
@@ -199,10 +200,14 @@ export const pkiSyncHealthCheckQueueFactory = ({
return certificateMap;
};
+ const HEALTH_CHECK_TEST_CERTIFICATE_LIMIT = 10;
+
const $certificatesForTest = async (args: {
projectId: string;
syncId?: string;
+ applicationId?: string;
certificateIds?: string[];
+ filters?: TPkiSyncFilters | null;
syncOptions: Record<string, unknown>;
}): Promise<TCertificateMap> => {
const command = getHealthCheckCommand(args.syncOptions);
@@ -213,7 +218,18 @@ export const pkiSyncHealthCheckQueueFactory = ({
return pkiSync ? $certificatesForCheck(pkiSync, command) : {};
}
- if (!args.certificateIds?.length) return {};
+ let { certificateIds } = args;
+
+ if (!certificateIds?.length && args.applicationId && hasAnyPkiSyncFilter(args.filters)) {
+ const matched = await certificateDAL.findCertificatesMatchingSyncFilters(
+ args.filters,
+ { projectId: args.projectId, applicationId: args.applicationId },
+ { limit: HEALTH_CHECK_TEST_CERTIFICATE_LIMIT }
+ );
+ certificateIds = matched.map((certificate) => certificate.id);
+ }
+
+ if (!certificateIds?.length) return {};
const { certificateMap } = await buildCertificateMap(
{ id: "", projectId: args.projectId, subscriberId: null, syncOptions: args.syncOptions } as TPkiSyncRaw,
@@ -227,7 +243,7 @@ export const pkiSyncHealthCheckQueueFactory = ({
projectDAL,
kmsService
},
- args.certificateIds
+ certificateIds
);
return certificateMap;
@@ -328,6 +344,7 @@ export const pkiSyncHealthCheckQueueFactory = ({
try {
const checkResult = await PkiSyncFns.runHealthCheck(pkiSyncWithCredentials, certificateMap, {
certificateSyncDAL,
+ certificateDAL,
gatewayV2Service,
gatewayPoolService,
keyStore
@@ -426,6 +443,7 @@ export const pkiSyncHealthCheckQueueFactory = ({
await PkiSyncFns.testReachability(target, {
certificateSyncDAL,
+ certificateDAL,
gatewayV2Service,
gatewayPoolService,
keyStore
@@ -440,7 +458,9 @@ export const pkiSyncHealthCheckQueueFactory = ({
connectionId: string;
projectId: string;
syncId?: string;
+ applicationId?: string;
certificateIds?: string[];
+ filters?: TPkiSyncFilters | null;
destinationConfig: Record<string, unknown>;
syncOptions: Record<string, unknown>;
}) => {
@@ -479,6 +499,7 @@ export const pkiSyncHealthCheckQueueFactory = ({
return $withConnectionHostAccess(connection.id, getPkiSyncTargetHost(target.destinationConfig), async () => {
const result = await PkiSyncFns.runHealthCheck(target, linkedCertificates, {
certificateSyncDAL,
+ certificateDAL,
gatewayV2Service,
gatewayPoolService,
keyStore
diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.ts
index e7174673ad..1817ff9413 100644
--- a/backend/src/services/pki-sync/pki-sync-queue.ts
+++ b/backend/src/services/pki-sync/pki-sync-queue.ts
@@ -34,6 +34,7 @@ import { TPkiSyncDALFactory } from "./pki-sync-dal";
import { PKI_SYNC_CONNECTION_LOCK_RETRY, PkiSyncFailureKind, PkiSyncStatus } from "./pki-sync-enums";
import { PkiSyncError } from "./pki-sync-errors";
import { notifyPkiSyncFailure } from "./pki-sync-failure-notification-fns";
+import { withPkiSyncFilterLock } from "./pki-sync-filter-reconcile-fns";
import {
getPkiSyncProviderCapabilities,
parsePkiSyncErrorMessage,
@@ -59,9 +60,11 @@ import {
TPkiSyncRemoveCertificatesDTO,
TPkiSyncSyncCertificatesDTO,
TQueuePkiSyncImportCertificatesByIdDTO,
+ TQueuePkiSyncLinkMatchingCertificatesDTO,
TQueuePkiSyncRemoveCertificatesByIdDTO,
TQueuePkiSyncSyncCertificatesByIdDTO
} from "./pki-sync-types";
+import { reconcileCertificateAgainstMatchingSyncs } from "./pki-sync-utils";
export type TPkiSyncQueueFactory = ReturnType<typeof pkiSyncQueueFactory>;
@@ -78,7 +81,7 @@ type TPkiSyncQueueFactoryDep = {
>;
pkiSyncDAL: Pick<
TPkiSyncDALFactory,
- "findById" | "find" | "updateById" | "deleteById" | "update" | "findFailureNotificationRecipients"
+ "findById" | "find" | "updateById" | "deleteById" | "update" | "findFailureNotificationRecipients" | "primaryNode"
>;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
@@ -178,6 +181,18 @@ export const pkiSyncQueueFactory = ({
removeOnFail: true
});
+ const queuePkiSyncLinkMatchingCertificates = async (payload: TQueuePkiSyncLinkMatchingCertificatesDTO) =>
+ queueService.queue(QueueName.PkiSync, QueueJobs.PkiSyncLinkMatchingCertificates, payload, {
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 3000
+ },
+ jobId: `pki-sync-link-${payload.certificateId}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
+ removeOnComplete: true,
+ removeOnFail: true
+ });
+
const queuePkiSyncImportCertificatesById = async (payload: TQueuePkiSyncImportCertificatesByIdDTO) =>
queueService.queue(QueueName.PkiSync, QueueJobs.PkiSyncImportCertificates, payload, {
attempts: 5,
@@ -365,9 +380,7 @@ export const pkiSyncQueueFactory = ({
.map((record) => record.certificateId)
.filter((id): id is string => typeof id === "string");
if (strandedCertificateIds.length > 0) {
- const stillEligible = (await certificateDAL.findActiveCertificatesByIds(strandedCertificateIds)).filter(
- (cert) => !cert.renewedByCertificateId
- );
+ const stillEligible = await certificateDAL.findActiveCertificatesByIds(strandedCertificateIds);
if (stillEligible.length > 0) {
await certificateSyncDAL.bulkUpdateSyncStatus(
stillEligible.map((cert) => ({
@@ -750,7 +763,28 @@ export const pkiSyncQueueFactory = ({
};
queueService.start(QueueName.PkiSync, async (job) => {
- const { syncId } = job.data;
+ if (job.name === QueueJobs.PkiSyncLinkMatchingCertificates) {
+ const { certificateId, applicationId } = job.data as TQueuePkiSyncLinkMatchingCertificatesDTO;
+ try {
+ await reconcileCertificateAgainstMatchingSyncs(certificateId, applicationId, {
+ certificateDAL,
+ certificateSyncDAL,
+ pkiSyncDAL,
+ pkiSyncQueue: { queuePkiSyncSyncCertificatesById, queuePkiSyncRemoveCertificatesById },
+ auditLogService,
+ withSyncFilterLock: (syncId, run) => withPkiSyncFilterLock(keyStore, syncId, run)
+ });
+ } catch (error) {
+ logger.error(
+ error,
+ `Failed to reconcile certificate against matching PKI syncs [certificateId=${certificateId}] [applicationId=${applicationId}]`
+ );
+ throw error;
+ }
+ return;
+ }
+
+ const { syncId } = job.data as PkiSyncActionJob["data"];
const pkiSync = await pkiSyncDAL.findById(syncId);
@@ -828,6 +862,7 @@ export const pkiSyncQueueFactory = ({
});
return {
+ queuePkiSyncLinkMatchingCertificates,
queuePkiSyncSyncCertificatesById,
queuePkiSyncImportCertificatesById,
queuePkiSyncRemoveCertificatesById
diff --git a/backend/src/services/pki-sync/pki-sync-schemas.ts b/backend/src/services/pki-sync/pki-sync-schemas.ts
index 4b4dd78ab6..7ed487d1e5 100644
--- a/backend/src/services/pki-sync/pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/pki-sync-schemas.ts
@@ -1,10 +1,12 @@
import RE2 from "re2";
import { z } from "zod";
+import { PKI_SYNC_FILTERS } from "@app/lib/api-docs/constants";
import { HOSTNAME_MAX_LENGTH, isValidHostname } from "@app/lib/validator/validate-hostname";
import { 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 { HOST_COMMAND_MAX_LENGTH } from "./pki-sync-host-command-fns";
export const HostCommandSchema = z
@@ -105,6 +107,45 @@ export const PkiSyncDestinationConfigSchema = z.object({
config: z.record(z.unknown())
});
+const PkiSyncFiltersSchema = z
+ .object({
+ profileIds: z.string().uuid().array().max(20).optional().describe(PKI_SYNC_FILTERS.profileIds),
+ certificateOrderIds: z
+ .string()
+ .uuid()
+ .array()
+ .max(PKI_SYNC_MAX_LINKED_CERTIFICATES)
+ .optional()
+ .describe(PKI_SYNC_FILTERS.certificateOrderIds),
+ metadata: z
+ .object({
+ key: z
+ .string()
+ .trim()
+ .min(1, "Metadata filter key cannot be empty")
+ .max(255)
+ .describe(PKI_SYNC_FILTERS.metadataKey),
+ value: z.string().trim().max(1020).optional().describe(PKI_SYNC_FILTERS.metadataValue)
+ })
+ .array()
+ .max(20)
+ .optional()
+ .describe(PKI_SYNC_FILTERS.metadata)
+ })
+ .strict();
+
+export const PkiSyncFiltersField = PkiSyncFiltersSchema.nullish().describe(PKI_SYNC_FILTERS.filters);
+
+export const UpdatePkiSyncFiltersField = PkiSyncFiltersSchema.nullish().describe(PKI_SYNC_FILTERS.updateFilters);
+
+const StoredPkiSyncFiltersSchema = z.object({
+ profileIds: z.string().uuid().array().optional(),
+ certificateOrderIds: z.string().uuid().array().optional(),
+ metadata: z.object({ key: z.string(), value: z.string().optional() }).array().optional()
+});
+
+export const PkiSyncStoredFiltersField = StoredPkiSyncFiltersSchema.nullish().describe(PKI_SYNC_FILTERS.filters);
+
// Base PKI sync schema for API responses
export const PkiSyncSchema = z.object({
id: z.string().uuid(),
@@ -123,12 +164,14 @@ export const PkiSyncSchema = z.object({
lastSyncedAt: z.date().nullable().optional(),
lastHealthCheckRanAt: z.date().nullable().optional(),
lastHealthCheckStatus: z.nativeEnum(PkiSyncStatus).nullable().optional(),
- lastHealthCheckMessage: z.string().nullable().optional()
+ lastHealthCheckMessage: z.string().nullable().optional(),
+ filters: PkiSyncStoredFiltersField
});
export const BaseHealthCheckTestSchema = z.object({
connectionId: z.string().uuid(),
applicationId: z.string().uuid().optional(),
syncId: z.string().uuid().optional(),
- certificateIds: z.array(z.string().uuid()).max(100).optional()
+ certificateIds: z.array(z.string().uuid()).max(100).optional(),
+ filters: PkiSyncFiltersField
});
diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.ts
index 785dc27b11..640c785829 100644
--- a/backend/src/services/pki-sync/pki-sync-service.ts
+++ b/backend/src/services/pki-sync/pki-sync-service.ts
@@ -1,4 +1,5 @@
import { ForbiddenError, subject } from "@casl/ability";
+import { Knex } from "knex";
import { ActionProjectType, ResourceType, TCertificateSyncs } from "@app/db/schemas";
import { AuditLogInfo, EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
@@ -9,6 +10,7 @@ import {
ResourcePermissionPkiSyncActions,
ResourcePermissionSub
} from "@app/ee/services/permission/resource-permission";
+import { TKeyStoreFactory } from "@app/keystore/keystore";
import { getProcessedPermissionRules } from "@app/lib/casl/permission-filter-utils";
import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { deepEqual } from "@app/lib/fn/object";
@@ -17,21 +19,31 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enums
import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
import { ActorType } from "@app/services/auth/auth-type";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TPkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";
+import { TPkiApplicationProfileDALFactory } from "@app/services/pki-application/pki-application-profile-dal";
import { TPkiSubscriberDALFactory } from "@app/services/pki-subscriber/pki-subscriber-dal";
import { TCertificateDALFactory } from "../certificate/certificate-dal";
+import { CertStatus } from "../certificate/certificate-types";
import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";
import { CertificateSyncStatus } from "../certificate-sync/certificate-sync-enums";
import { TSyncMetadata } from "../certificate-sync/certificate-sync-schemas";
-import { certificateNameSchemaAllowsMultipleCertificates } from "./pki-sync-certificate-name-fns";
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 {
- assertPkiSyncDestinationConfigAllowsCertificateCount,
+ applyPkiSyncCertificateDiff,
+ assertPkiSyncCanHoldMatchedCertificates,
+ computePkiSyncCertificateDiff,
+ TPkiSyncReconcileTarget,
+ withPkiSyncFilterLock
+} from "./pki-sync-filter-reconcile-fns";
+import {
+ assertFiltersCannotExceedCertificateCap,
+ assertPkiSyncCanHoldCertificateCount,
assertPkiSyncLicense,
- getPkiSyncMaxCertificates,
getPkiSyncProviderCapabilities,
listPkiSyncOptions,
resolvePkiSyncDestinationConfigUpdate
@@ -43,15 +55,10 @@ import {
toHealthCheckApiResult
} from "./pki-sync-health-check-command-fns";
import { TPkiSyncHealthCheckQueueFactory } from "./pki-sync-health-check-queue";
-import {
- findSingleCertificateHostCommandVariables,
- formatHostCommandVariables,
- HostCommandKind
-} from "./pki-sync-host-command-fns";
+import { HostCommandKind } from "./pki-sync-host-command-fns";
import { getPkiSyncConnectionApps, PKI_SYNC_NAME_MAP } from "./pki-sync-maps";
import {
applyPostSyncCommandUpdate,
- getPostSyncCommand,
normalizeNewPostSyncCommand,
POST_SYNC_COMMAND_OPTION_KEY
} from "./pki-sync-post-sync-command-fns";
@@ -71,6 +78,11 @@ import {
TListPkiSyncsByProjectId,
TPkiSync,
TPkiSyncCertificate,
+ TPkiSyncCertificateRef,
+ TPkiSyncFilterPreview,
+ TPkiSyncFilters,
+ TPkiSyncRaw,
+ TPreviewPkiSyncFiltersDTO,
TRemoveCertificatesFromPkiSyncDTO,
TSetCertificateAsDefaultDTO,
TTriggerPkiSyncImportCertificatesByIdDTO,
@@ -82,9 +94,16 @@ import {
type TPkiSyncServiceFactoryDep = {
pkiSyncDAL: Pick<
TPkiSyncDALFactory,
- "findById" | "findByProjectIdWithSubscribers" | "findByNameAndProjectId" | "create" | "updateById" | "deleteById"
+ | "findById"
+ | "findByProjectIdWithSubscribers"
+ | "findByNameAndProjectId"
+ | "create"
+ | "updateById"
+ | "deleteById"
+ | "primaryNode"
>;
- certificateDAL: Pick<TCertificateDALFactory, "findActiveCertificatesByIds">;
+ certificateDAL: Pick<TCertificateDALFactory, "find" | "findCertificatesMatchingSyncFilters" | "primaryNode">;
+ pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory, "findByApplicationId">;
certificateSyncDAL: Pick<
TCertificateSyncDALFactory,
| "findByPkiSyncId"
@@ -96,11 +115,15 @@ type TPkiSyncServiceFactoryDep = {
| "findWithDetails"
| "updateSyncMetadata"
| "clearSyncMetadataFlag"
+ | "transaction"
+ | "primaryNode"
>;
pkiSubscriberDAL: Pick<TPkiSubscriberDALFactory, "findById">;
+ pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;
appConnectionService: Pick<TAppConnectionServiceFactory, "connectAppConnectionById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+ keyStore: Pick<TKeyStoreFactory, "acquireLock">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
pkiSyncHealthCheckQueue: Pick<
@@ -113,16 +136,28 @@ type TPkiSyncServiceFactoryDep = {
>;
};
+const $assertSyncAcceptsFilters = (pkiSync: Pick<TPkiSyncRaw, "applicationId">) => {
+ if (!pkiSync.applicationId) {
+ throw new BadRequestError({
+ message:
+ "This PKI sync is not attached to an Application, so its certificates cannot be changed. Create a sync inside an Application to select certificates by filter."
+ });
+ }
+};
+
export type TPkiSyncServiceFactory = ReturnType<typeof pkiSyncServiceFactory>;
export const pkiSyncServiceFactory = ({
pkiSyncDAL,
certificateDAL,
+ pkiApplicationProfileDAL,
certificateSyncDAL,
pkiSubscriberDAL,
+ pkiApplicationDAL,
appConnectionService,
permissionService,
licenseService,
+ keyStore,
kmsService,
pkiSyncQueue,
pkiSyncHealthCheckQueue,
@@ -342,92 +377,136 @@ export const pkiSyncServiceFactory = ({
$assertHostCommandsAreSupported(destination, nextSyncOptions, await resolveConnection());
};
- const validateCertificatesForSync = async (
+ const $findApplicationCertificates = async (
certificateIds: string[],
expectedProjectId: string,
expectedApplicationId: string | null | undefined
) => {
- if (certificateIds.length === 0) return;
+ const certificates = await certificateDAL.find({ projectId: expectedProjectId, $in: { id: certificateIds } });
- const certificates = await certificateDAL.findActiveCertificatesByIds(certificateIds);
+ const foundIds = new Set(certificates.map((cert) => cert.id));
+ const missingIds = certificateIds.filter((id) => !foundIds.has(id));
+ if (missingIds.length > 0) {
+ throw new NotFoundError({ message: `Certificates not found: ${missingIds.join(", ")}` });
+ }
- if (certificates.length !== certificateIds.length) {
- const foundIds = certificates.map((cert) => cert.id);
- const missingIds = certificateIds.filter((id) => !foundIds.includes(id));
- throw new NotFoundError({
- message: `Certificates not found or not active: ${missingIds.join(", ")}`
- });
+ if (expectedApplicationId) {
+ const outsideApplication = certificates.filter((cert) => cert.applicationId !== expectedApplicationId);
+ if (outsideApplication.length > 0) {
+ throw new NotFoundError({
+ message: `Certificates not found in this Application: ${outsideApplication.map((cert) => cert.id).join(", ")}`
+ });
+ }
}
- const invalidProjectCertificates = certificates.filter((cert) => cert.projectId !== expectedProjectId);
- if (invalidProjectCertificates.length > 0) {
+ return certificates;
+ };
+
+ const $resolveCertificateOrderIds = async (
+ certificateIds: string[],
+ expectedProjectId: string,
+ expectedApplicationId: string | null | undefined,
+ { requireSyncable }: { requireSyncable: boolean }
+ ): Promise<string[]> => {
+ if (certificateIds.length === 0) return [];
+
+ const certificates = await $findApplicationCertificates(certificateIds, expectedProjectId, expectedApplicationId);
+
+ const withoutOrder = certificates.filter((cert) => !cert.orderId);
+ if (withoutOrder.length > 0) {
throw new BadRequestError({
- message: `Certificates do not belong to the same project: ${invalidProjectCertificates.map((cert) => cert.id).join(", ")}`
+ message: `Certificates without a certificate order cannot be synced: ${withoutOrder
+ .map((cert) => `'${cert.commonName}'`)
+ .join(", ")}`
});
}
- if (expectedApplicationId) {
- const invalidApplicationCertificates = certificates.filter(
- (cert) => cert.applicationId !== expectedApplicationId
+ const orderIds = [...new Set(certificates.map((cert) => cert.orderId))];
+
+ if (requireSyncable && expectedApplicationId) {
+ const syncable = await certificateDAL.findCertificatesMatchingSyncFilters(
+ { certificateOrderIds: orderIds },
+ { projectId: expectedProjectId, applicationId: expectedApplicationId }
);
- if (invalidApplicationCertificates.length > 0) {
+ const liveOrderIds = new Set(syncable.map((cert) => cert.orderId));
+ const dead = certificates.filter((cert) => !liveOrderIds.has(cert.orderId));
+
+ if (dead.length > 0) {
throw new BadRequestError({
- message: `Certificates do not belong to this Application: ${invalidApplicationCertificates
- .map((cert) => cert.id)
+ message: `Certificate orders with no active certificate cannot be synced: ${dead
+ .map((cert) => `'${cert.commonName}'`)
.join(", ")}`
});
}
}
- const invalidRenewedCertificates = certificates.filter((cert) => cert.renewedByCertificateId);
- if (invalidRenewedCertificates.length > 0) {
- throw new BadRequestError({
- message: `Cannot add renewed certificates to PKI sync: ${invalidRenewedCertificates.map((cert) => cert.id).join(", ")}`
- });
- }
+ return orderIds;
};
- // Enforced only on user-initiated changes. The renewal path writes membership rows
- // directly via the DAL and relies on a transient old+new overlap, so it must not be capped here.
- const assertWithinCertificateLimit = (destination: PkiSync, prospectiveCount: number) => {
- const maxCertificates = getPkiSyncMaxCertificates(destination);
- if (maxCertificates !== undefined && prospectiveCount > maxCertificates) {
+ const validateCertificatesForSync = async (
+ certificateIds: string[],
+ expectedProjectId: string,
+ expectedApplicationId: string | null | undefined
+ ) => {
+ if (certificateIds.length === 0) return [];
+
+ const certificates = await $findApplicationCertificates(certificateIds, expectedProjectId, expectedApplicationId);
+
+ const now = new Date();
+ const ineligibleReasons = certificates
+ .filter(
+ (cert) => cert.status !== CertStatus.ACTIVE || cert.notAfter <= now || Boolean(cert.renewedByCertificateId)
+ )
+ .map((cert) => {
+ if (cert.status === CertStatus.REVOKED) return `'${cert.commonName}' is revoked`;
+ if (cert.renewedByCertificateId)
+ return `'${cert.commonName}' has been renewed, so link the certificate that replaced it instead`;
+ if (cert.notAfter <= now) return `'${cert.commonName}' has expired`;
+ return `'${cert.commonName}' is not active`;
+ });
+ if (ineligibleReasons.length > 0) {
throw new BadRequestError({
- message: `${PKI_SYNC_NAME_MAP[destination]} PKI sync supports at most ${maxCertificates} certificate${
- maxCertificates === 1 ? "" : "s"
- }`
+ message: `Only active certificates can be linked to a PKI sync: ${ineligibleReasons.join("; ")}`
});
}
+
+ return certificates;
};
- const assertSyncOptionsAllowCertificateCount = (
- syncOptions: Record<string, unknown> | undefined,
- resultingCertificateCount: number
+ const $assertFilterProfilesInApplication = async (
+ filters: TPkiSyncFilters | null | undefined,
+ applicationId: string | null | undefined
) => {
- if (resultingCertificateCount <= 1) return;
+ const profileIds = filters?.profileIds;
+ if (!profileIds?.length || !applicationId) return;
- const schema = syncOptions?.certificateNameSchema as string | undefined;
- if (!certificateNameSchemaAllowsMultipleCertificates(schema)) {
- throw new BadRequestError({
- message:
- "This sync's certificate name schema has no placeholder, so it can be linked to only one certificate. Add a placeholder such as {{commonName}} or {{certificateId}} to sync multiple certificates."
+ const applicationProfiles = await pkiApplicationProfileDAL.findByApplicationId(applicationId);
+ const profileIdsInApplication = new Set(applicationProfiles.map(({ profileId }) => profileId));
+ const profileIdsOutsideApplication = profileIds.filter((id) => !profileIdsInApplication.has(id));
+ if (profileIdsOutsideApplication.length > 0) {
+ throw new NotFoundError({
+ message: `Certificate profiles not found in this Application: ${profileIdsOutsideApplication.join(", ")}`
});
}
+ };
- [
- { kind: HostCommandKind.HealthCheck, command: getHealthCheckCommand(syncOptions) },
- { kind: HostCommandKind.PostSync, command: getPostSyncCommand(syncOptions) }
- ].forEach(({ kind, command }) => {
- const singleCertificateVariables = findSingleCertificateHostCommandVariables(command);
-
- if (singleCertificateVariables.length > 0) {
- throw new BadRequestError({
- message: `This sync's ${kind} uses ${formatHostCommandVariables(
- singleCertificateVariables
- )}. A variable that names one certificate can only be used on a sync with a single certificate linked. Use {{certificateFiles}} or {{certificateDirectory}} to write a command that covers every certificate in the run.`
- });
- }
- });
+ const $withFilterLock = <T>(syncId: string, run: () => Promise<T>): Promise<T> =>
+ withPkiSyncFilterLock(keyStore, syncId, run);
+
+ const $reconcileFilters = async (
+ pkiSync: TPkiSyncReconcileTarget,
+ filters: TPkiSyncFilters | null | undefined,
+ opts: { auditLogInfo?: AuditLogInfo; writeFilters?: (tx: Knex) => Promise<void> } = {}
+ ): Promise<{ linked: TPkiSyncCertificateRef[]; unlinked: TPkiSyncCertificateRef[] }> => {
+ const diff = await computePkiSyncCertificateDiff(pkiSync, filters, { certificateDAL, certificateSyncDAL });
+ assertPkiSyncCanHoldMatchedCertificates(pkiSync, diff.matched.length);
+ return applyPkiSyncCertificateDiff(
+ pkiSync,
+ diff,
+ { certificateDAL, certificateSyncDAL, pkiSyncQueue, auditLogService },
+ opts.auditLogInfo,
+ opts.writeFilters
+ );
};
const createPkiSync = async (
@@ -442,11 +521,13 @@ export const pkiSyncServiceFactory = ({
connectionId,
projectId,
applicationId,
- certificateIds = [],
- credentials
- }: Omit<TCreatePkiSyncDTO, "auditLogInfo">,
+ certificateIds,
+ filters,
+ credentials,
+ auditLogInfo
+ }: TCreatePkiSyncDTO,
actor: OrgServiceActor
- ): Promise<TPkiSync> => {
+ ): Promise<TPkiSync & { linkedCertificates: TPkiSyncCertificateRef[] }> => {
if (!applicationId) {
throw new BadRequestError({
message:
@@ -507,11 +588,33 @@ export const pkiSyncServiceFactory = ({
resolveConnection: async () => connection
});
- if (certificateIds.length > 0) {
- assertWithinCertificateLimit(destination, certificateIds.length);
- await validateCertificatesForSync(certificateIds, projectId, applicationId);
- assertSyncOptionsAllowCertificateCount(resolvedSyncOptions, certificateIds.length);
- assertPkiSyncDestinationConfigAllowsCertificateCount(destination, destinationConfig, certificateIds.length);
+ if (filters !== undefined && certificateIds !== undefined) {
+ throw new BadRequestError({
+ message: "Pass certificates as either 'certificateIds' or the 'certificateOrderIds' filter, not both."
+ });
+ }
+
+ const resolvedFilters =
+ filters !== undefined
+ ? filters
+ : {
+ certificateOrderIds: await $resolveCertificateOrderIds(certificateIds ?? [], projectId, applicationId, {
+ requireSyncable: true
+ })
+ };
+
+ await $assertFilterProfilesInApplication(resolvedFilters, applicationId);
+ assertFiltersCannotExceedCertificateCap(destination, resolvedSyncOptions, destinationConfig, resolvedFilters);
+
+ if (hasAnyPkiSyncFilter(resolvedFilters)) {
+ const matched = await certificateDAL.findCertificatesMatchingSyncFilters(resolvedFilters, {
+ projectId,
+ applicationId
+ });
+ assertPkiSyncCanHoldMatchedCertificates(
+ { destination, destinationConfig, syncOptions: resolvedSyncOptions } as TPkiSyncReconcileTarget,
+ matched.length
+ );
}
await $assertTargetHostReachable({ destination, connection, destinationConfig });
@@ -533,21 +636,23 @@ export const pkiSyncServiceFactory = ({
connectionId,
projectId,
applicationId: applicationId ?? null,
+ filters: resolvedFilters ?? null,
...(isAutoSyncEnabled && { syncStatus: PkiSyncStatus.Pending })
});
- if (certificateIds.length > 0) {
- await certificateSyncDAL.addCertificates(
- pkiSync.id,
- certificateIds.map((id) => ({ certificateId: id }))
- );
- }
+ const { linked: linkedCertificates } = await $reconcileFilters(
+ pkiSync as TPkiSyncReconcileTarget,
+ resolvedFilters,
+ {
+ auditLogInfo
+ }
+ );
if (pkiSync.isAutoSyncEnabled) {
await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: pkiSync.id });
}
- return pkiSync as TPkiSync;
+ return { ...(pkiSync as TPkiSync), linkedCertificates };
} catch (err) {
if (err instanceof DatabaseError && (err.error as { code: string })?.code === "23505") {
throw new BadRequestError({
@@ -569,10 +674,14 @@ export const pkiSyncServiceFactory = ({
syncOptions,
subscriberId,
connectionId,
- credentials
- }: Omit<TUpdatePkiSyncDTO, "auditLogInfo" | "projectId">,
+ filters,
+ credentials,
+ auditLogInfo
+ }: Omit<TUpdatePkiSyncDTO, "projectId">,
actor: OrgServiceActor
- ): Promise<TPkiSync> => {
+ ): Promise<
+ TPkiSync & { linkedCertificates: TPkiSyncCertificateRef[]; unlinkedCertificates: TPkiSyncCertificateRef[] }
+ > => {
const pkiSync = await pkiSyncDAL.findById(id);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
if (applicationId && pkiSync.applicationId !== applicationId) {
@@ -717,6 +826,8 @@ export const pkiSyncServiceFactory = ({
const effectiveSyncOptions = (resolvedSyncOptions ?? pkiSync.syncOptions) as Record<string, unknown> | undefined;
+ await $assertFilterProfilesInApplication(filters, pkiSync.applicationId);
+
await $assertHostCommandWrite({
destination: pkiSync.destination,
nextSyncOptions: effectiveSyncOptions,
@@ -730,12 +841,18 @@ export const pkiSyncServiceFactory = ({
if (syncOptions || destinationConfig) {
const existingCount = (await certificateSyncDAL.findByPkiSyncId(id)).length;
- assertSyncOptionsAllowCertificateCount(effectiveSyncOptions, existingCount);
- assertPkiSyncDestinationConfigAllowsCertificateCount(
+ assertPkiSyncCanHoldCertificateCount(
pkiSync.destination,
+ effectiveSyncOptions,
effectiveDestinationConfig,
existingCount
);
+ assertFiltersCannotExceedCertificateCap(
+ pkiSync.destination,
+ effectiveSyncOptions,
+ effectiveDestinationConfig,
+ filters === undefined ? (pkiSync.filters as TPkiSyncFilters | null) : filters
+ );
}
if (
@@ -763,17 +880,58 @@ export const pkiSyncServiceFactory = ({
syncOptions: resolvedSyncOptions,
subscriberId,
connectionId,
+ ...(filters === undefined ? {} : { filters }),
...(encryptedCredentials ? { encryptedCredentials } : {}),
...(isHealthCheckBeingCleared
? { lastHealthCheckRanAt: null, lastHealthCheckStatus: null, lastHealthCheckMessage: null }
: {})
};
- if (Object.values(update).every((value) => value === undefined)) return pkiSync as TPkiSync;
+ if (Object.values(update).every((value) => value === undefined)) {
+ return { ...(pkiSync as TPkiSync), linkedCertificates: [], unlinkedCertificates: [] };
+ }
+
+ const storedFilters = pkiSync.filters as TPkiSyncFilters | null;
+ const areFiltersChanging =
+ filters !== undefined && JSON.stringify(filters ?? null) !== JSON.stringify(storedFilters ?? null);
+
+ if (areFiltersChanging) $assertSyncAcceptsFilters(pkiSync);
+
+ if (!areFiltersChanging) {
+ const written = await pkiSyncDAL.updateById(id, update);
+ return { ...(written as TPkiSync), linkedCertificates: [], unlinkedCertificates: [] };
+ }
+
+ const { updatedPkiSync, linked, unlinked } = await $withFilterLock(id, async () => {
+ const current = await pkiSyncDAL.findById(id, pkiSyncDAL.primaryNode());
+ if (!current) throw new NotFoundError({ message: `Could not find PKI sync with ID ${id}` });
- const updatedPkiSync = await pkiSyncDAL.updateById(id, update);
+ const changedFields = Object.fromEntries(Object.entries(update).filter(([, value]) => value !== undefined));
+ const target = { ...current, ...changedFields, syncOptions: effectiveSyncOptions } as TPkiSyncReconcileTarget;
+ assertFiltersCannotExceedCertificateCap(
+ current.destination as PkiSync,
+ effectiveSyncOptions,
+ effectiveDestinationConfig,
+ filters
+ );
- return updatedPkiSync as TPkiSync;
+ const applied = await $reconcileFilters(target, filters, {
+ auditLogInfo,
+ writeFilters: async (tx) => {
+ await pkiSyncDAL.updateById(id, update, tx);
+ }
+ });
+
+ const written = await pkiSyncDAL.findById(id);
+
+ return { updatedPkiSync: written ?? current, ...applied };
+ });
+
+ return {
+ ...(updatedPkiSync as TPkiSync),
+ linkedCertificates: linked,
+ unlinkedCertificates: unlinked
+ };
};
const deletePkiSync = async (
@@ -1013,6 +1171,7 @@ export const pkiSyncServiceFactory = ({
applicationId?: string;
syncId?: string;
certificateIds?: string[];
+ filters?: TPkiSyncFilters | null;
destinationConfig: Record<string, unknown>;
syncOptions: Record<string, unknown>;
projectId: string;
@@ -1039,6 +1198,8 @@ export const pkiSyncServiceFactory = ({
await validateCertificatesForSync(args.certificateIds, args.projectId, args.applicationId);
}
+ await $assertFilterProfilesInApplication(args.filters, args.applicationId);
+
const connection = await appConnectionService.connectAppConnectionById(
getPkiSyncConnectionApps(args.destination),
args.connectionId,
@@ -1065,7 +1226,9 @@ export const pkiSyncServiceFactory = ({
destination: args.destination,
connectionId: args.connectionId,
syncId: args.syncId,
+ applicationId: args.applicationId,
certificateIds: args.certificateIds,
+ filters: args.filters,
projectId: args.projectId,
destinationConfig: args.destinationConfig,
syncOptions: args.syncOptions
@@ -1180,17 +1343,131 @@ export const pkiSyncServiceFactory = ({
return { message: "PKI sync remove job added to queue successfully" };
};
+ const previewPkiSyncFilters = async (
+ { applicationId, pkiSyncId, filters }: Omit<TPreviewPkiSyncFiltersDTO, "projectId">,
+ actor: OrgServiceActor
+ ): Promise<TPkiSyncFilterPreview> => {
+ if (pkiSyncId) {
+ const pkiSync = await pkiSyncDAL.findById(pkiSyncId);
+ if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
+
+ let pkiSyncSubscriber;
+ if (pkiSync.subscriberId) {
+ pkiSyncSubscriber = await pkiSubscriberDAL.findById(pkiSync.subscriberId);
+ }
+
+ await $assertSyncAction(
+ ProjectPermissionPkiSyncActions.Edit,
+ ResourcePermissionPkiSyncActions.Edit,
+ pkiSync,
+ pkiSyncSubscriber?.name,
+ actor
+ );
+
+ await $assertFilterProfilesInApplication(filters, pkiSync.applicationId);
+
+ const diff = await computePkiSyncCertificateDiff(pkiSync as TPkiSyncReconcileTarget, filters, {
+ certificateDAL,
+ certificateSyncDAL
+ });
+
+ const canRemoveCertificates = Boolean(
+ (pkiSync.syncOptions as { canRemoveCertificates?: boolean } | null)?.canRemoveCertificates
+ );
+
+ 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,
+ willRemoveFromDestination: canRemoveCertificates && diff.toUnlink.length > 0
+ };
+ }
+
+ 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.Create,
+ application.projectId,
+ applicationId,
+ actor
+ );
+ if (!allowedByResource) {
+ throw new ForbiddenRequestError({ message: "User has insufficient privileges" });
+ }
+
+ await $assertFilterProfilesInApplication(filters, applicationId);
+
+ const matched = hasAnyPkiSyncFilter(filters)
+ ? await certificateDAL.findCertificatesMatchingSyncFilters(
+ filters,
+ { projectId: application.projectId, applicationId },
+ { limit: PKI_SYNC_MAX_LINKED_CERTIFICATES + 1 }
+ )
+ : [];
+
+ 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),
+ toUnlink: [],
+ willRemoveFromDestination: false
+ };
+ };
+
+ const $assertCertificateOrderListIsTheOnlySyncFilter = (pkiSync: TPkiSyncRaw) => {
+ $assertSyncAcceptsFilters(pkiSync);
+
+ const filters = pkiSync.filters as TPkiSyncFilters | null;
+ const otherFilterKinds = PKI_SYNC_FILTER_KINDS.filter(
+ (kind) => kind !== "certificateOrderIds" && filters?.[kind] !== undefined
+ );
+
+ if (!filters || otherFilterKinds.length > 0) {
+ 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."
+ });
+ }
+
+ return filters;
+ };
+
+ const $writeCertificateOrderIdsFilter = async (
+ pkiSync: TPkiSyncRaw,
+ nextOrderIds: (currentOrderIds: string[]) => string[],
+ auditLogInfo?: AuditLogInfo
+ ) => {
+ return $withFilterLock(pkiSync.id, async () => {
+ const current = await pkiSyncDAL.findById(pkiSync.id, pkiSyncDAL.primaryNode());
+ if (!current) throw new NotFoundError({ message: `Could not find PKI sync with ID ${pkiSync.id}` });
+
+ const stored = $assertCertificateOrderListIsTheOnlySyncFilter(current);
+ const nextFilters = { ...stored, certificateOrderIds: nextOrderIds(stored.certificateOrderIds ?? []) };
+
+ return $reconcileFilters(current as TPkiSyncReconcileTarget, nextFilters, {
+ auditLogInfo,
+ writeFilters: async (tx) => {
+ await pkiSyncDAL.updateById(pkiSync.id, { filters: nextFilters }, tx);
+ }
+ });
+ });
+ };
+
const getPkiSyncOptions = () => {
return listPkiSyncOptions();
};
const addCertificatesToPkiSync = async (
- { pkiSyncId, certificateIds }: Omit<TAddCertificatesToPkiSyncDTO, "auditLogInfo" | "projectId">,
+ { pkiSyncId, certificateIds, auditLogInfo }: Omit<TAddCertificatesToPkiSyncDTO, "projectId">,
actor: OrgServiceActor
- ): Promise<{
- addedCertificates: TCertificateSyncs[];
- pkiSyncInfo: { projectId: string; destination: string; name: string; applicationId?: string | null };
- }> => {
+ ): Promise<{ addedCertificates: TCertificateSyncs[] }> => {
const pkiSync = await pkiSyncDAL.findById(pkiSyncId);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
@@ -1207,54 +1484,34 @@ export const pkiSyncServiceFactory = ({
actor
);
- const existingCertificateIds = await certificateSyncDAL.findCertificateIdsByPkiSyncId(pkiSyncId);
- const prospectiveCount = new Set([...existingCertificateIds, ...certificateIds]).size;
- assertWithinCertificateLimit(pkiSync.destination, prospectiveCount);
-
- await validateCertificatesForSync(certificateIds, pkiSync.projectId, pkiSync.applicationId);
-
- assertSyncOptionsAllowCertificateCount(
- pkiSync.syncOptions as Record<string, unknown> | undefined,
- prospectiveCount
- );
- assertPkiSyncDestinationConfigAllowsCertificateCount(
- pkiSync.destination,
- pkiSync.destinationConfig,
- prospectiveCount
+ $assertCertificateOrderListIsTheOnlySyncFilter(pkiSync);
+ const requestedOrderIds = await $resolveCertificateOrderIds(
+ certificateIds,
+ pkiSync.projectId,
+ pkiSync.applicationId,
+ { requireSyncable: true }
);
- const alreadyLinked = new Set(existingCertificateIds);
- const certificateIdsToAdd = certificateIds.filter((id) => !alreadyLinked.has(id));
+ const { linked } = await $writeCertificateOrderIdsFilter(
+ pkiSync,
+ (currentOrderIds) => [...currentOrderIds, ...requestedOrderIds.filter((id) => !currentOrderIds.includes(id))],
+ auditLogInfo
+ );
- const addedCertificates = certificateIdsToAdd.length
- ? await certificateSyncDAL.addCertificates(
- pkiSyncId,
- certificateIdsToAdd.map((id) => ({ certificateId: id }))
+ const linkedIds = new Set(linked.map(({ id }) => id));
+ const addedCertificates = linked.length
+ ? (await certificateSyncDAL.findByPkiSyncId(pkiSyncId)).filter(
+ (record) => record.certificateId && linkedIds.has(record.certificateId)
)
: [];
- if (pkiSync.isAutoSyncEnabled) {
- await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: pkiSyncId });
- }
-
- return {
- addedCertificates,
- pkiSyncInfo: {
- projectId: pkiSync.projectId,
- destination: pkiSync.destination,
- name: pkiSync.name,
- applicationId: pkiSync.applicationId
- }
- };
+ return { addedCertificates };
};
const removeCertificatesFromPkiSync = async (
- { pkiSyncId, certificateIds }: Omit<TRemoveCertificatesFromPkiSyncDTO, "auditLogInfo" | "projectId">,
+ { pkiSyncId, certificateIds, auditLogInfo }: Omit<TRemoveCertificatesFromPkiSyncDTO, "projectId">,
actor: OrgServiceActor
- ): Promise<{
- removedCount: number;
- pkiSyncInfo: { projectId: string; destination: string; name: string; applicationId?: string | null };
- }> => {
+ ): Promise<{ removedCount: number }> => {
const pkiSync = await pkiSyncDAL.findById(pkiSyncId);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
@@ -1271,27 +1528,20 @@ export const pkiSyncServiceFactory = ({
actor
);
- const syncOptions = pkiSync.syncOptions as { canRemoveCertificates?: boolean } | undefined;
- let removedCount: number;
- if (syncOptions?.canRemoveCertificates) {
- await pkiSyncQueue.queuePkiSyncRemoveCertificatesById({ syncId: pkiSyncId, certificateIds });
- removedCount = certificateIds.length;
- } else {
- removedCount = await certificateSyncDAL.removeCertificates(pkiSyncId, certificateIds);
- if (pkiSync.isAutoSyncEnabled) {
- await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: pkiSyncId });
- }
- }
+ $assertCertificateOrderListIsTheOnlySyncFilter(pkiSync);
+ const removalSet = new Set(
+ await $resolveCertificateOrderIds(certificateIds, pkiSync.projectId, pkiSync.applicationId, {
+ requireSyncable: false
+ })
+ );
- return {
- removedCount,
- pkiSyncInfo: {
- projectId: pkiSync.projectId,
- destination: pkiSync.destination,
- name: pkiSync.name,
- applicationId: pkiSync.applicationId
- }
- };
+ const { unlinked } = await $writeCertificateOrderIdsFilter(
+ pkiSync,
+ (currentOrderIds) => currentOrderIds.filter((id) => !removalSet.has(id)),
+ auditLogInfo
+ );
+
+ return { removedCount: unlinked.length };
};
const listPkiSyncCertificates = async (
@@ -1336,6 +1586,7 @@ export const pkiSyncServiceFactory = ({
updatedAt: detail.updatedAt,
certificateSerialNumber: detail.certificateSerialNumber || undefined,
certificateCommonName: detail.certificateCommonName || undefined,
+ certificateOrderId: detail.certificateOrderId || undefined,
certificateAltNames: detail.certificateAltNames || undefined,
certificateStatus: detail.certificateStatus || undefined,
certificateNotBefore: detail.certificateNotBefore || undefined,
@@ -1451,6 +1702,7 @@ export const pkiSyncServiceFactory = ({
triggerPkiSyncImportCertificatesById,
triggerPkiSyncRemoveCertificatesById,
getPkiSyncOptions,
+ previewPkiSyncFilters,
addCertificatesToPkiSync,
removeCertificatesFromPkiSync,
listPkiSyncCertificates,
diff --git a/backend/src/services/pki-sync/pki-sync-types.ts b/backend/src/services/pki-sync/pki-sync-types.ts
index ba01a6ac05..97ad9578af 100644
--- a/backend/src/services/pki-sync/pki-sync-types.ts
+++ b/backend/src/services/pki-sync/pki-sync-types.ts
@@ -10,6 +10,27 @@ import { TPkiSyncDALFactory } from "./pki-sync-dal";
import { PkiSync } from "./pki-sync-enums";
import { THostCommandResult } from "./pki-sync-host-command-fns";
+export type TPkiSyncFilters = {
+ profileIds?: string[];
+ certificateOrderIds?: string[];
+ metadata?: { key: string; value?: string }[];
+};
+
+export type TPkiSyncCertificateRef = {
+ id: string;
+ commonName: string;
+ serialNumber?: string;
+ notAfter?: Date;
+ orderId?: string;
+ profileName?: string | null;
+};
+
+export type TPkiSyncCertificateDiff = {
+ matched: TPkiSyncCertificateRef[];
+ toLink: TPkiSyncCertificateRef[];
+ toUnlink: TPkiSyncCertificateRef[];
+};
+
export type TPkiSync = {
id: string;
name: string;
@@ -59,6 +80,7 @@ export type TPkiSync = {
id: string;
name: string;
} | null;
+ filters?: TPkiSyncFilters | null;
};
export type THealthCheckTarget = {
@@ -140,6 +162,7 @@ export type TCreatePkiSyncDTO = {
projectId: string;
applicationId?: string;
certificateIds?: string[];
+ filters?: TPkiSyncFilters | null;
credentials?: { exportPassword?: string };
auditLogInfo: AuditLogInfo;
resourceInternalMetadata?: ResourceMetadataDTO;
@@ -156,6 +179,7 @@ export type TUpdatePkiSyncDTO = {
syncOptions?: Record<string, unknown>;
subscriberId?: string | null;
connectionId?: string;
+ filters?: TPkiSyncFilters | null;
credentials?: { exportPassword?: string };
auditLogInfo: AuditLogInfo;
resourceInternalMetadata?: ResourceMetadataDTO;
@@ -199,6 +223,21 @@ export type TTriggerPkiSyncRemoveCertificatesByIdDTO = {
auditLogInfo: AuditLogInfo;
};
+export type TPreviewPkiSyncFiltersDTO = {
+ applicationId?: string;
+ pkiSyncId?: string;
+ filters?: TPkiSyncFilters | null;
+ projectId?: string;
+};
+
+export type TPkiSyncFilterPreview = {
+ matchedCount: number;
+ hasMoreMatches: boolean;
+ certificates: TPkiSyncCertificateRef[];
+ toUnlink: TPkiSyncCertificateRef[];
+ willRemoveFromDestination: boolean;
+};
+
export type TAddCertificatesToPkiSyncDTO = {
pkiSyncId: string;
certificateIds: string[];
@@ -242,6 +281,7 @@ export type TPkiSyncCertificate = {
updatedAt: Date;
certificateSerialNumber?: string;
certificateCommonName?: string;
+ certificateOrderId?: string;
certificateAltNames?: string;
certificateStatus?: string;
certificateNotBefore?: Date;
@@ -256,6 +296,11 @@ export type TPkiSyncCertificate = {
export type TPkiSyncRaw = NonNullable<Awaited<ReturnType<TPkiSyncDALFactory["findById"]>>>;
+export type TQueuePkiSyncLinkMatchingCertificatesDTO = {
+ certificateId: string;
+ applicationId: string;
+};
+
export type TQueuePkiSyncSyncCertificatesByIdDTO = {
syncId: string;
failedToAcquireLockCount?: number;
diff --git a/backend/src/services/pki-sync/pki-sync-utils.ts b/backend/src/services/pki-sync/pki-sync-utils.ts
index 15a77fa8b6..376e58433a 100644
--- a/backend/src/services/pki-sync/pki-sync-utils.ts
+++ b/backend/src/services/pki-sync/pki-sync-utils.ts
@@ -1,16 +1,35 @@
import { Knex } from "knex";
+import { AuditLogInfo, EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { logger } from "@app/lib/logger";
+import { ActorType } from "@app/services/auth/auth-type";
+import { TCertificateDALFactory } from "../certificate/certificate-dal";
import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";
import { TPkiSyncDALFactory } from "./pki-sync-dal";
-import { TPkiSyncQueueFactory } from "./pki-sync-queue";
+import { PkiSync } from "./pki-sync-enums";
+import { hasAnyPkiSyncFilter } from "./pki-sync-filter-fns";
+import { applyPkiSyncCertificateDiff, TPkiSyncReconcileTarget } from "./pki-sync-filter-reconcile-fns";
+import { assertPkiSyncCanHoldCertificateCount } from "./pki-sync-fns";
+import {
+ TPkiSyncFilters,
+ TQueuePkiSyncRemoveCertificatesByIdDTO,
+ TQueuePkiSyncSyncCertificatesByIdDTO
+} from "./pki-sync-types";
+
+type TPkiSyncQueueForReconcile = {
+ queuePkiSyncLinkMatchingCertificates: (payload: { certificateId: string; applicationId: string }) => Promise<unknown>;
+};
+
+type TPkiSyncRunQueue = {
+ queuePkiSyncSyncCertificatesById: (payload: TQueuePkiSyncSyncCertificatesByIdDTO) => Promise<unknown>;
+};
export const triggerAutoSyncForSubscriber = async (
subscriberId: string,
dependencies: {
pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;
- pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;
+ pkiSyncQueue: TPkiSyncRunQueue;
}
) => {
try {
@@ -34,7 +53,7 @@ export const triggerAutoSyncForCertificate = async (
dependencies: {
certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findPkiSyncIdsByCertificateId">;
pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;
- pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;
+ pkiSyncQueue: TPkiSyncRunQueue;
}
) => {
try {
@@ -60,6 +79,86 @@ export const triggerAutoSyncForCertificate = async (
}
};
+export const queueCertificateFilterReconcile = async (
+ certificateId: string,
+ applicationId: string,
+ pkiSyncQueue: Pick<TPkiSyncQueueForReconcile, "queuePkiSyncLinkMatchingCertificates">
+) => {
+ try {
+ await pkiSyncQueue.queuePkiSyncLinkMatchingCertificates({ certificateId, applicationId });
+ } catch (error) {
+ logger.error(
+ error,
+ `Failed to queue a filter reconcile [certificateId=${certificateId}] [applicationId=${applicationId}]`
+ );
+ }
+};
+
+export const findPkiSyncIdsHoldingCertificate = async (
+ certificateId: string,
+ dependencies: {
+ certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findPkiSyncIdsByCertificateId" | "primaryNode">;
+ }
+) => {
+ try {
+ return await dependencies.certificateSyncDAL.findPkiSyncIdsByCertificateId(
+ certificateId,
+ dependencies.certificateSyncDAL.primaryNode()
+ );
+ } catch (error) {
+ logger.error(error, `Failed to read PKI sync links for certificate ${certificateId}`);
+ return [];
+ }
+};
+
+export const triggerSyncsForDeletedCertificate = async (
+ certificateId: string,
+ pkiSyncIds: string[],
+ dependencies: {
+ pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;
+ pkiSyncQueue: TPkiSyncRunQueue;
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
+ },
+ certificate: { commonName: string; projectId: string; applicationId?: string | null },
+ auditLogInfo?: AuditLogInfo
+) => {
+ if (pkiSyncIds.length === 0) return;
+
+ try {
+ const pkiSyncs = await dependencies.pkiSyncDAL.find({ $in: { id: pkiSyncIds } });
+
+ await Promise.all(
+ pkiSyncs.map((pkiSync) =>
+ dependencies.auditLogService.createAuditLog({
+ ...(auditLogInfo ?? { actor: { type: ActorType.PLATFORM, metadata: {} } }),
+ projectId: certificate.projectId,
+ event: {
+ type: EventType.PKI_SYNC_UNLINK_CERTIFICATES,
+ metadata: {
+ pkiSyncId: pkiSync.id,
+ name: pkiSync.name,
+ count: 1,
+ certificates: [{ id: certificateId, commonName: certificate.commonName }],
+ removedFromDestination: Boolean(
+ (pkiSync.syncOptions as { canRemoveCertificates?: boolean } | null)?.canRemoveCertificates
+ ),
+ ...(pkiSync.applicationId ? { applicationId: pkiSync.applicationId } : {})
+ }
+ }
+ })
+ )
+ );
+
+ await Promise.all(
+ pkiSyncs
+ .filter((pkiSync) => pkiSync.isAutoSyncEnabled)
+ .map((pkiSync) => dependencies.pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: pkiSync.id }))
+ );
+ } catch (error) {
+ logger.error(error, `Failed to reconcile PKI syncs after deleting certificate ${certificateId}`);
+ }
+};
+
export const addRenewedCertificateToSyncs = async (
oldCertificateId: string,
newCertificateId: string,
@@ -110,3 +209,138 @@ export const addRenewedCertificateToSyncs = async (
throw error;
}
};
+
+type TReconcileCertificateAgainstSyncsDeps = {
+ certificateDAL: Pick<
+ TCertificateDALFactory,
+ "findActiveCertificatesByIds" | "findCertificatesMatchingSyncFilters" | "find" | "primaryNode"
+ >;
+ certificateSyncDAL: Pick<
+ TCertificateSyncDALFactory,
+ | "findCertificateIdsByPkiSyncId"
+ | "addCertificates"
+ | "findByPkiSyncId"
+ | "removeCertificates"
+ | "transaction"
+ | "primaryNode"
+ >;
+ pkiSyncDAL: Pick<TPkiSyncDALFactory, "find" | "findById" | "primaryNode">;
+ pkiSyncQueue: TPkiSyncRunQueue & {
+ queuePkiSyncRemoveCertificatesById: (payload: TQueuePkiSyncRemoveCertificatesByIdDTO) => Promise<unknown>;
+ };
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
+ withSyncFilterLock: <T>(syncId: string, run: () => Promise<T>) => Promise<T>;
+};
+
+const $reconcileCertificateAgainstSync = async (
+ certificateId: string,
+ applicationId: string,
+ pkiSync: Awaited<ReturnType<TPkiSyncDALFactory["find"]>>[number],
+ dependencies: TReconcileCertificateAgainstSyncsDeps
+) => {
+ const filters = pkiSync.filters as TPkiSyncFilters | null;
+ const matched = hasAnyPkiSyncFilter(filters)
+ ? await dependencies.certificateDAL.findCertificatesMatchingSyncFilters(filters, {
+ projectId: pkiSync.projectId,
+ applicationId,
+ certificateId
+ })
+ : [];
+
+ const existingCertificateIds = await dependencies.certificateSyncDAL.findCertificateIdsByPkiSyncId(
+ pkiSync.id,
+ dependencies.certificateSyncDAL.primaryNode()
+ );
+ const isLinked = existingCertificateIds.includes(certificateId);
+
+ if (matched.length === 0) {
+ if (!isLinked) return;
+
+ const [certificate] = await dependencies.certificateDAL.find({
+ projectId: pkiSync.projectId,
+ $in: { id: [certificateId] }
+ });
+
+ await applyPkiSyncCertificateDiff(
+ pkiSync as TPkiSyncReconcileTarget,
+ {
+ matched: [],
+ toLink: [],
+ toUnlink: [{ id: certificateId, commonName: certificate?.commonName ?? "" }]
+ },
+ dependencies
+ );
+
+ logger.info(
+ `Unlinked certificate from PKI sync by filter [certificateId=${certificateId}] [pkiSyncId=${pkiSync.id}]`
+ );
+ return;
+ }
+
+ if (isLinked) return;
+
+ const liveCertificates = await dependencies.certificateDAL.findActiveCertificatesByIds(
+ existingCertificateIds,
+ dependencies.certificateDAL.primaryNode()
+ );
+ const prospectiveCount = liveCertificates.length + 1;
+ try {
+ assertPkiSyncCanHoldCertificateCount(
+ pkiSync.destination as PkiSync,
+ pkiSync.syncOptions as Record<string, unknown> | undefined,
+ pkiSync.destinationConfig,
+ prospectiveCount
+ );
+ } catch (limitError) {
+ logger.warn(
+ limitError,
+ `Certificate matched a sync's filters but the sync cannot hold it [certificateId=${certificateId}] [pkiSyncId=${pkiSync.id}]`
+ );
+
+ await dependencies.auditLogService.createAuditLog({
+ projectId: pkiSync.projectId,
+ actor: { type: ActorType.PLATFORM, metadata: {} },
+ event: {
+ type: EventType.PKI_SYNC_SKIP_CERTIFICATE,
+ metadata: {
+ pkiSyncId: pkiSync.id,
+ name: pkiSync.name,
+ certificateId,
+ commonName: matched[0].commonName,
+ reason: limitError instanceof Error ? limitError.message : "This sync cannot hold another certificate.",
+ ...(pkiSync.applicationId ? { applicationId: pkiSync.applicationId } : {})
+ }
+ }
+ });
+ return;
+ }
+
+ await applyPkiSyncCertificateDiff(
+ pkiSync as TPkiSyncReconcileTarget,
+ { matched, toLink: [{ id: certificateId, commonName: matched[0].commonName }], toUnlink: [] },
+ dependencies
+ );
+
+ logger.info(`Linked certificate to PKI sync by filter [certificateId=${certificateId}] [pkiSyncId=${pkiSync.id}]`);
+};
+
+export const reconcileCertificateAgainstMatchingSyncs = async (
+ certificateId: string,
+ applicationId: string | null | undefined,
+ dependencies: TReconcileCertificateAgainstSyncsDeps
+) => {
+ if (!applicationId) return;
+
+ const pkiSyncs = await dependencies.pkiSyncDAL.find({ applicationId });
+
+ await Promise.all(
+ pkiSyncs.map(({ id }) =>
+ dependencies.withSyncFilterLock(id, async () => {
+ const pkiSync = await dependencies.pkiSyncDAL.findById(id, dependencies.pkiSyncDAL.primaryNode());
+ if (!pkiSync) return;
+
+ await $reconcileCertificateAgainstSync(certificateId, applicationId, pkiSync, dependencies);
+ })
+ )
+ );
+};
diff --git a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts
index 9f14c1db4c..077e683c8d 100644
--- a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts
@@ -12,6 +12,7 @@ import {
resolveLdapBackedHostCredentials
} from "@app/services/app-connection/ldap/ldap-directory-fns";
import { executeWinRMGatewayOperation, TWinRMConnection, TWinRMCredentials } from "@app/services/app-connection/winrm";
+import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";
import { TSyncMetadata } from "@app/services/certificate-sync/certificate-sync-schemas";
@@ -43,6 +44,7 @@ type TWindowsServerPkiSyncFactoryDeps = {
TCertificateSyncDALFactory,
"findByPkiSyncId" | "findByPkiSyncAndCertificate" | "updateById" | "addCertificates" | "removeCertificates"
>;
+ certificateDAL: Pick<TCertificateDALFactory, "findActiveCertificatesByIds">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId" | "getGatewayById">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
@@ -159,9 +161,10 @@ const reconcileWindowsServerRemovals = async (args: {
deliveredPaths: Set<string>;
target: TWinRMSyncTarget;
certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findByPkiSyncId" | "removeCertificates">;
+ certificateDAL: Pick<TCertificateDALFactory, "findActiveCertificatesByIds">;
gatewayDeps: Parameters<typeof executeWinRMGatewayOperation>[1];
}): Promise<{ removed: number; failedRemovals: Array<{ name: string; error: string }> }> => {
- const { pkiSync, certificateMap, deliveredPaths, target, certificateSyncDAL, gatewayDeps } = args;
+ const { pkiSync, certificateMap, deliveredPaths, target, certificateSyncDAL, certificateDAL, gatewayDeps } = args;
const failedRemovals: Array<{ name: string; error: string }> = [];
let removed = 0;
@@ -171,8 +174,19 @@ const reconcileWindowsServerRemovals = async (args: {
.filter((id): id is string => typeof id === "string")
);
const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id);
+
+ const untrackCandidateIds = existingSyncRecords
+ .map((record) => record.certificateId)
+ .filter((id): id is string => Boolean(id) && !activeCertificateIds.has(id));
+ const stillActiveIds = new Set(
+ (await certificateDAL.findActiveCertificatesByIds(untrackCandidateIds)).map((cert) => cert.id)
+ );
+
const orphans = existingSyncRecords.filter(
- (record) => record.certificateId && !activeCertificateIds.has(record.certificateId)
+ (record) =>
+ record.certificateId &&
+ !activeCertificateIds.has(record.certificateId) &&
+ !stillActiveIds.has(record.certificateId)
);
if (orphans.length === 0) return { removed, failedRemovals };
@@ -282,6 +296,7 @@ const runWindowsServerPostSyncCommand = ({
export const windowsServerPkiSyncFactory = ({
certificateSyncDAL,
+ certificateDAL,
gatewayV2Service,
gatewayPoolService,
keyStore
@@ -405,6 +420,7 @@ export const windowsServerPkiSyncFactory = ({
deliveredPaths,
target,
certificateSyncDAL,
+ certificateDAL,
gatewayDeps
});
removed += reconciliation.removed;
diff --git a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.ts b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.ts
index 942bff7da1..d9fe034db3 100644
--- a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.ts
@@ -9,9 +9,11 @@ import { PemCertificateExtension, PkiSyncExportFormat } from "@app/services/pki-
import {
BaseHealthCheckTestSchema,
HostCommandSchema,
+ PkiSyncFiltersField,
PkiSyncSchema,
PkiSyncTargetHostSchema,
- PkiSyncTargetPortSchema
+ PkiSyncTargetPortSchema,
+ UpdatePkiSyncFiltersField
} from "@app/services/pki-sync/pki-sync-schemas";
import { WINDOWS_SERVER_NAMING } from "./windows-server-pki-sync-constants";
@@ -139,7 +141,8 @@ export const CreateWindowsServerPkiSyncSchema = z
subscriberId: z.string().nullish(),
connectionId: z.string(),
applicationId: z.string().uuid().optional(),
- certificateIds: z.array(z.string().uuid()).optional()
+ certificateIds: z.array(z.string().uuid()).optional(),
+ filters: PkiSyncFiltersField
})
.superRefine((data, ctx) => {
if (data.syncOptions.exportFormat === PkiSyncExportFormat.Pkcs12 && !data.credentials?.exportPassword) {
@@ -159,7 +162,8 @@ export const UpdateWindowsServerPkiSyncSchema = z.object({
syncOptions: WindowsServerPkiSyncOptionsSchema.optional(),
credentials: WindowsServerPkiSyncCredentialsSchema.optional(),
subscriberId: z.string().nullish(),
- connectionId: z.string().optional()
+ connectionId: z.string().optional(),
+ filters: UpdatePkiSyncFiltersField
});
export const WindowsServerPkiSyncListItemSchema = z.object({
diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.ts
index 3350df746c..a976a333d2 100644
--- a/backend/src/services/project/project-service.ts
+++ b/backend/src/services/project/project-service.ts
@@ -1449,8 +1449,10 @@ export const projectServiceFactory = ({
const validatedSortBy = sortBy && ALLOWED_SORT_COLUMNS.has(sortBy) ? sortBy : "notAfter";
const validatedSortOrder = sortOrder === "asc" ? "asc" : "desc";
+ const { status: ignoredSyncStatus, ...syncEligibilityFilters } = regularFilters;
+
const certificates = forPkiSync
- ? await certificateDAL.findActiveCertificatesForSync(regularFilters, { offset, limit }, permissionFilters)
+ ? await certificateDAL.findActiveCertificatesForSync(syncEligibilityFilters, { offset, limit }, permissionFilters)
: await certificateDAL.findWithPrivateKeyInfo(
regularFilters,
{
@@ -1461,34 +1463,9 @@ export const projectServiceFactory = ({
permissionFilters
);
- const countFilter = {
- projectId,
- ...(regularFilters.friendlyName && { friendlyName: String(regularFilters.friendlyName) }),
- ...(regularFilters.commonName && { commonName: String(regularFilters.commonName) }),
- ...(regularFilters.search && { search: String(regularFilters.search) }),
- ...(regularFilters.status && { status: regularFilters.status }),
- ...(regularFilters.profileIds && { profileIds: regularFilters.profileIds }),
- ...(regularFilters.fromDate && { fromDate: regularFilters.fromDate }),
- ...(regularFilters.toDate && { toDate: regularFilters.toDate }),
- ...(regularFilters.metadataFilter && { metadataFilter: regularFilters.metadataFilter }),
- ...(regularFilters.extendedKeyUsage && { extendedKeyUsage: String(regularFilters.extendedKeyUsage) }),
- ...(regularFilters.keyAlgorithm && { keyAlgorithm: regularFilters.keyAlgorithm }),
- ...(regularFilters.signatureAlgorithm && { signatureAlgorithm: String(regularFilters.signatureAlgorithm) }),
- ...(regularFilters.keySizes && { keySizes: regularFilters.keySizes }),
- ...(regularFilters.caIds && { caIds: regularFilters.caIds }),
- ...(regularFilters.enrollmentTypes && { enrollmentTypes: regularFilters.enrollmentTypes }),
- ...(regularFilters.source && { source: regularFilters.source }),
- ...(regularFilters.notAfterFrom && { notAfterFrom: regularFilters.notAfterFrom }),
- ...(regularFilters.notAfterTo && { notAfterTo: regularFilters.notAfterTo }),
- ...(regularFilters.notBeforeFrom && { notBeforeFrom: regularFilters.notBeforeFrom }),
- ...(regularFilters.notBeforeTo && { notBeforeTo: regularFilters.notBeforeTo }),
- ...(regularFilters.applicationId && { applicationId: regularFilters.applicationId }),
- ...(regularFilters.applicationIds && { applicationIds: regularFilters.applicationIds })
- };
-
const count = forPkiSync
- ? await certificateDAL.countActiveCertificatesForSync(countFilter)
- : await certificateDAL.countCertificatesInProject(countFilter, permissionFilters);
+ ? await certificateDAL.countActiveCertificatesForSync(syncEligibilityFilters, permissionFilters)
+ : await certificateDAL.countCertificatesInProject(regularFilters, permissionFilters);
return {
certificates,
diff --git a/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt b/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt
index f1370a610c..9a15a891a8 100644
--- a/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt
+++ b/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt
@@ -354,6 +354,7 @@ I
(?i)Git\b
(?i)Go\b
(?i)unlinks
+(?i)unlinking
(?i)href
(?i)quickstart
(?i)quickstarts
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/aws-certificate-manager.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/aws-certificate-manager.mdx
index 0ac158772e..81b9a74755 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/aws-certificate-manager.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/aws-certificate-manager.mdx
@@ -60,8 +60,9 @@ Push certificates from your Application to AWS Certificate Manager (ACM). Certif
### Sample request
<Note>
- You can optionally specify `certificateIds` during sync creation to immediately add certificates to the sync.
- If not provided, you can add certificates later using the certificate management endpoints.
+ Pass `filters` to describe the certificates this sync holds. Anything in the Application that matches is
+ attached automatically, as it is issued. Omit it and the sync starts empty, and you can set filters later.
+ See [Certificate filters](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-filters).
</Note>
```bash Request
@@ -76,10 +77,12 @@ Push certificates from your Application to AWS Certificate Manager (ACM). Certif
"connectionId": "550e8400-e29b-41d4-a716-446655440000",
"destination": "aws-certificate-manager",
"isAutoSyncEnabled": true,
- "certificateIds": [
- "550e8400-e29b-41d4-a716-446655440000",
- "660f1234-e29b-41d4-a716-446655440001"
- ],
+ "filters": {
+ "certificateOrderIds": [
+ "550e8400-e29b-41d4-a716-446655440000",
+ "660f1234-e29b-41d4-a716-446655440001"
+ ]
+ },
"syncOptions": {
"canRemoveCertificates": true,
"preserveArnOnRenewal": true,
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/aws-elastic-load-balancer.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/aws-elastic-load-balancer.mdx
index 903811710a..ce8a91f0fa 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/aws-elastic-load-balancer.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/aws-elastic-load-balancer.mdx
@@ -55,8 +55,9 @@ Deploy certificates directly to your AWS Application Load Balancers (ALBs) and N
### Sample request
<Note>
- You can optionally specify `certificateIds` during sync creation to immediately add certificates to the sync.
- If not provided, you can add certificates later using the certificate management endpoints.
+ Pass `filters` to describe the certificates this sync holds. Anything in the Application that matches is
+ attached automatically, as it is issued. Omit it and the sync starts empty, and you can set filters later.
+ See [Certificate filters](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-filters).
</Note>
```bash Request
@@ -71,9 +72,9 @@ Deploy certificates directly to your AWS Application Load Balancers (ALBs) and N
"connectionId": "550e8400-e29b-41d4-a716-446655440000",
"destination": "aws-elastic-load-balancer",
"isAutoSyncEnabled": true,
- "certificateIds": [
- "550e8400-e29b-41d4-a716-446655440000"
- ],
+ "filters": {
+ "certificateOrderIds": ["550e8400-e29b-41d4-a716-446655440000"]
+ },
"syncOptions": {
"canRemoveCertificates": true,
"preserveArn": true,
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/aws-secrets-manager.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/aws-secrets-manager.mdx
index cb54411ced..cceb243528 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/aws-secrets-manager.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/aws-secrets-manager.mdx
@@ -78,8 +78,9 @@ Store certificates in AWS Secrets Manager as JSON secrets for application retrie
### Sample request
<Note>
- You can optionally specify `certificateIds` during sync creation to immediately add certificates to the sync.
- If not provided, you can add certificates later using the certificate management endpoints.
+ Pass `filters` to describe the certificates this sync holds. Anything in the Application that matches is
+ attached automatically, as it is issued. Omit it and the sync starts empty, and you can set filters later.
+ See [Certificate filters](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-filters).
</Note>
```bash Request
@@ -94,10 +95,12 @@ Store certificates in AWS Secrets Manager as JSON secrets for application retrie
"connectionId": "550e8400-e29b-41d4-a716-446655440000",
"destination": "aws-secrets-manager",
"isAutoSyncEnabled": true,
- "certificateIds": [
- "550e8400-e29b-41d4-a716-446655440000",
- "660f1234-e29b-41d4-a716-446655440001"
- ],
+ "filters": {
+ "certificateOrderIds": [
+ "550e8400-e29b-41d4-a716-446655440000",
+ "660f1234-e29b-41d4-a716-446655440001"
+ ]
+ },
"syncOptions": {
"canRemoveCertificates": true,
"preserveSecretOnRenewal": true,
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/azure-key-vault.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/azure-key-vault.mdx
index ee0eefb018..09b4d7af0f 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/azure-key-vault.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/azure-key-vault.mdx
@@ -59,8 +59,9 @@ Store certificates in Azure Key Vault as certificate objects. Certificates synce
### Sample request
<Note>
- You can optionally specify `certificateIds` during sync creation to immediately add certificates to the sync.
- If not provided, you can add certificates later using the certificate management endpoints.
+ Pass `filters` to describe the certificates this sync holds. Anything in the Application that matches is
+ attached automatically, as it is issued. Omit it and the sync starts empty, and you can set filters later.
+ See [Certificate filters](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-filters).
</Note>
```bash Request
@@ -75,10 +76,12 @@ Store certificates in Azure Key Vault as certificate objects. Certificates synce
"connectionId": "550e8400-e29b-41d4-a716-446655440000",
"destination": "azure-key-vault",
"isAutoSyncEnabled": true,
- "certificateIds": [
- "550e8400-e29b-41d4-a716-446655440000",
- "660f1234-e29b-41d4-a716-446655440001"
- ],
+ "filters": {
+ "certificateOrderIds": [
+ "550e8400-e29b-41d4-a716-446655440000",
+ "660f1234-e29b-41d4-a716-446655440001"
+ ]
+ },
"syncOptions": {
"canRemoveCertificates": true,
"enableVersioningOnRenewal": true,
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/chef.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/chef.mdx
index 1aeeebfbe8..3e20a9cba2 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/chef.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/chef.mdx
@@ -74,8 +74,9 @@ Store certificates in Chef data bags for distribution to nodes via Chef Infra. C
### Sample request
<Note>
- You can optionally specify `certificateIds` during sync creation to immediately add certificates to the sync.
- If not provided, you can add certificates later using the certificate management endpoints.
+ Pass `filters` to describe the certificates this sync holds. Anything in the Application that matches is
+ attached automatically, as it is issued. Omit it and the sync starts empty, and you can set filters later.
+ See [Certificate filters](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-filters).
</Note>
```bash Request
@@ -90,10 +91,12 @@ Store certificates in Chef data bags for distribution to nodes via Chef Infra. C
"connectionId": "550e8400-e29b-41d4-a716-446655440000",
"destination": "chef",
"isAutoSyncEnabled": true,
- "certificateIds": [
- "550e8400-e29b-41d4-a716-446655440000",
- "660f1234-e29b-41d4-a716-446655440001"
- ],
+ "filters": {
+ "certificateOrderIds": [
+ "550e8400-e29b-41d4-a716-446655440000",
+ "660f1234-e29b-41d4-a716-446655440001"
+ ]
+ },
"syncOptions": {
"canRemoveCertificates": true,
"preserveSecretOnRenewal": true,
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/cloudflare-custom-certificate.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/cloudflare-custom-certificate.mdx
index 5c08ce627c..d50ffa5d2b 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/cloudflare-custom-certificate.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/cloudflare-custom-certificate.mdx
@@ -49,8 +49,9 @@ Deploy custom SSL certificates to your Cloudflare zones. Certificates synced to
### Sample request
<Note>
- You can optionally specify `certificateIds` during sync creation to immediately add certificates to the sync.
- If not provided, you can add certificates later using the certificate management endpoints.
+ Pass `filters` to describe the certificates this sync holds. Anything in the Application that matches is
+ attached automatically, as it is issued. Omit it and the sync starts empty, and you can set filters later.
+ See [Certificate filters](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-filters).
</Note>
```bash Request
@@ -65,10 +66,12 @@ Deploy custom SSL certificates to your Cloudflare zones. Certificates synced to
"connectionId": "550e8400-e29b-41d4-a716-446655440000",
"destination": "cloudflare-custom-certificate",
"isAutoSyncEnabled": true,
- "certificateIds": [
- "550e8400-e29b-41d4-a716-446655440000",
- "660f1234-e29b-41d4-a716-446655440001"
- ],
+ "filters": {
+ "certificateOrderIds": [
+ "550e8400-e29b-41d4-a716-446655440000",
+ "660f1234-e29b-41d4-a716-446655440001"
+ ]
+ },
"syncOptions": {
"canRemoveCertificates": true,
"certificateNameSchema": "myapp-{{certificateId}}"
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/f5-big-ip.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/f5-big-ip.mdx
index 61e72f0397..06cafdff37 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/f5-big-ip.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/f5-big-ip.mdx
@@ -53,8 +53,9 @@ Deploy certificates to F5 BIG-IP appliances. Certificates can be automatically a
### Sample request
<Note>
- You can optionally specify `certificateIds` during sync creation to immediately add certificates to the sync.
- If not provided, you can add certificates later using the certificate management endpoints.
+ Pass `filters` to describe the certificates this sync holds. Anything in the Application that matches is
+ attached automatically, as it is issued. Omit it and the sync starts empty, and you can set filters later.
+ See [Certificate filters](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-filters).
</Note>
```bash Request
@@ -69,9 +70,9 @@ Deploy certificates to F5 BIG-IP appliances. Certificates can be automatically a
"connectionId": "550e8400-e29b-41d4-a716-446655440000",
"destination": "f5-big-ip",
"isAutoSyncEnabled": true,
- "certificateIds": [
- "550e8400-e29b-41d4-a716-446655440000"
- ],
+ "filters": {
+ "certificateOrderIds": ["550e8400-e29b-41d4-a716-446655440000"]
+ },
"syncOptions": {
"canRemoveCertificates": true,
"includeRootCa": false,
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/gcp-certificate-manager.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/gcp-certificate-manager.mdx
index 9ae0a0576a..c6fb626b37 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/gcp-certificate-manager.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/gcp-certificate-manager.mdx
@@ -74,8 +74,9 @@ Upload certificates managed in Infisical to GCP Certificate Manager as self-mana
### Sample request
<Note>
- You can optionally specify `certificateIds` during sync creation to immediately add certificates to the sync.
- If not provided, you can add them later using the certificate management endpoints.
+ Pass `filters` to describe the certificates this sync holds. Anything in the Application that matches is
+ attached automatically, as it is issued. Omit it and the sync starts empty, and you can set filters later.
+ See [Certificate filters](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-filters).
</Note>
```bash Request
@@ -90,9 +91,9 @@ Upload certificates managed in Infisical to GCP Certificate Manager as self-mana
"connectionId": "550e8400-e29b-41d4-a716-446655440000",
"destination": "gcp-certificate-manager",
"isAutoSyncEnabled": true,
- "certificateIds": [
- "550e8400-e29b-41d4-a716-446655440000"
- ],
+ "filters": {
+ "certificateOrderIds": ["550e8400-e29b-41d4-a716-446655440000"]
+ },
"destinationConfig": {
"gcpProjectId": "my-prod-project",
"location": "global",
@@ -210,7 +211,7 @@ For a **global** certificate, a certificate map entry maps a hostname to the cer
**Preserve certificate on renewal** is enabled by default. An existing GCP certificate is updated in place and keeps its resource name, so certificate map entries and target proxies keep working with no change in GCP. This also pins the resource name against later edits to the certificate name schema. This is the recommended setting.
-When disabled, a renewal or a name change creates a new GCP certificate under a new resource name. Whether the old certificate is deleted depends on **Remove Expired/Revoked Certificates**:
+When disabled, a renewal or a name change creates a new GCP certificate under a new resource name. Whether the old certificate is deleted depends on **Allow to remove certificates from destination**:
- **Removal enabled**: Infisical deletes the old certificate. If a certificate map entry references it, Infisical moves its own entry to the new certificate first. Anything else pointing at the old certificate has to be updated by hand, and GCP refuses to delete a certificate that is still referenced.
- **Removal disabled**: the old certificate stays in your GCP project. Infisical never deletes it, and it's no longer tracked by the sync.
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/kemp-loadmaster.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/kemp-loadmaster.mdx
index fc5595c277..8bb6aacb89 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/kemp-loadmaster.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/kemp-loadmaster.mdx
@@ -50,8 +50,9 @@ Deploy certificates to Progress Kemp LoadMaster load balancers via the RESTful A
### Sample request
<Note>
- You can optionally specify `certificateIds` during sync creation to immediately add certificates to the sync.
- If not provided, you can add certificates later using the certificate management endpoints.
+ Pass `filters` to describe the certificates this sync holds. Anything in the Application that matches is
+ attached automatically, as it is issued. Omit it and the sync starts empty, and you can set filters later.
+ See [Certificate filters](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-filters).
</Note>
```bash Request
@@ -66,9 +67,9 @@ Deploy certificates to Progress Kemp LoadMaster load balancers via the RESTful A
"connectionId": "550e8400-e29b-41d4-a716-446655440000",
"destination": "kemp-loadmaster",
"isAutoSyncEnabled": true,
- "certificateIds": [
- "550e8400-e29b-41d4-a716-446655440000"
- ],
+ "filters": {
+ "certificateOrderIds": ["550e8400-e29b-41d4-a716-446655440000"]
+ },
"syncOptions": {
"canRemoveCertificates": true,
"preserveItemOnRenewal": true,
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx
index 1c48657781..3b2049fb5a 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx
@@ -81,7 +81,9 @@ Deploy certificates from Infisical to a directory on a Linux server over SSH. Fi
"applicationId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"connectionId": "550e8400-e29b-41d4-a716-446655440000",
"isAutoSyncEnabled": true,
- "certificateIds": ["550e8400-e29b-41d4-a716-446655440000"],
+ "filters": {
+ "certificateOrderIds": ["550e8400-e29b-41d4-a716-446655440000"]
+ },
"syncOptions": {
"exportFormat": "pem",
"includePrivateKey": true,
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/netscaler.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/netscaler.mdx
index 2b57dac435..51025308ed 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/netscaler.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/netscaler.mdx
@@ -48,8 +48,9 @@ Deploy certificates to Citrix NetScaler ADC appliances via the NITRO API. Certif
### Sample request
<Note>
- You can optionally specify `certificateIds` during sync creation to immediately add certificates to the sync.
- If not provided, you can add certificates later using the certificate management endpoints.
+ Pass `filters` to describe the certificates this sync holds. Anything in the Application that matches is
+ attached automatically, as it is issued. Omit it and the sync starts empty, and you can set filters later.
+ See [Certificate filters](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-filters).
</Note>
```bash Request
@@ -64,9 +65,9 @@ Deploy certificates to Citrix NetScaler ADC appliances via the NITRO API. Certif
"connectionId": "550e8400-e29b-41d4-a716-446655440000",
"destination": "netscaler",
"isAutoSyncEnabled": true,
- "certificateIds": [
- "550e8400-e29b-41d4-a716-446655440000"
- ],
+ "filters": {
+ "certificateOrderIds": ["550e8400-e29b-41d4-a716-446655440000"]
+ },
"syncOptions": {
"canRemoveCertificates": true,
"preserveItemOnRenewal": true,
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/nutanix-prism-central.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/nutanix-prism-central.mdx
index 42b7c828e1..0e46a1b914 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/nutanix-prism-central.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/nutanix-prism-central.mdx
@@ -47,8 +47,9 @@ Before setting up the sync, gather the following from your Nutanix environment:
### Sample request
<Note>
- You can optionally specify `certificateIds` during sync creation to immediately add a certificate to the sync.
- If not provided, you can add one later using the certificate management endpoints.
+ Pass `filters` to describe the certificate this sync holds. This destination holds one certificate, so the
+ filters have to match exactly one. Omit it and the sync starts empty, and you can set filters later.
+ See [Certificate filters](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-filters).
</Note>
```bash Request
@@ -63,9 +64,9 @@ Before setting up the sync, gather the following from your Nutanix environment:
"connectionId": "550e8400-e29b-41d4-a716-446655440000",
"destination": "nutanix-prism-central",
"isAutoSyncEnabled": true,
- "certificateIds": [
- "550e8400-e29b-41d4-a716-446655440000"
- ],
+ "filters": {
+ "certificateOrderIds": ["550e8400-e29b-41d4-a716-446655440000"]
+ },
"destinationConfig": {
"clusterId": "a29facad-8d6e-4f64-b745-bceca6f990d6",
"clusterName": "prod-cluster-01"
@@ -126,6 +127,8 @@ The Nutanix Prism Central Certificate Sync provides:
<Note>
Certificate removal isn't supported for Nutanix Prism Central. A cluster always has exactly one active SSL certificate, which can only be replaced, not deleted.
+
+ For the same reason, this destination doesn't support [certificate filters](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-filters). Select the certificate you want instead.
</Note>
## Manual certificate sync
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx
index 6d630da348..a5da836744 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 LR
Configure:
- **Destination**: Select the App Connection and target endpoint
- - **Certificates**: Choose which certificates to sync
+ - **Certificates**: Add filters describing the certificates this sync holds. A sync with no filters holds nothing
- **Options**: Configure sync behavior (see below)
</Step>
<Step title="Certificates are synced">
@@ -123,11 +123,95 @@ flowchart LR
</Step>
</Steps>
+## 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.
+
+Filters live on the **Certificates** step of the sync, under the **Add Filter** menu. Three are available, and they can be combined:
+
+| 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 |
+
+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.
+
+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.
+
+### Syncs with a certificate limit
+
+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
+
+A 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 certificates, 500 orders, 20 certificate profiles, or 20 metadata pairs.
+</Note>
+
## Sync options
| Option | Description |
|--------|-------------|
-| **Remove on expiry** | Automatically remove expired certificates from the destination |
+| **Allow to remove certificates from destination** | Delete a certificate from the destination once it leaves this sync |
| **Include Root CA** | Include the root CA certificate in the chain |
| **Certificate naming** | Customize how certificates are named in the destination via the Certificate Name Schema (default: `Infisical-{{certificateId}}`) |
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx
index ac2f37195f..bb497ef398 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx
@@ -89,7 +89,9 @@ Deploy certificates from Infisical to a directory on a Windows server over WinRM
"applicationId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"connectionId": "550e8400-e29b-41d4-a716-446655440000",
"isAutoSyncEnabled": true,
- "certificateIds": ["550e8400-e29b-41d4-a716-446655440000"],
+ "filters": {
+ "certificateOrderIds": ["550e8400-e29b-41d4-a716-446655440000"]
+ },
"credentials": {
"exportPassword": "a-strong-password"
},
diff --git a/frontend/src/components/pki-syncs/CertificateManagementModal.tsx b/frontend/src/components/pki-syncs/CertificateManagementModal.tsx
index 2f27a5bfd3..4b1ed95fd5 100644
--- a/frontend/src/components/pki-syncs/CertificateManagementModal.tsx
+++ b/frontend/src/components/pki-syncs/CertificateManagementModal.tsx
@@ -31,24 +31,18 @@ import {
} from "@app/components/v3";
import { useProject } from "@app/context";
import { getCertificateDisplayName, truncateCertificateSerialNumber } from "@app/helpers/pkiSyncs";
-import {
- CertStatus,
- useAddCertificatesToPkiSync,
- useListPkiSyncCertificates,
- useRemoveCertificatesFromPkiSync
-} from "@app/hooks/api";
-import { PkiSync, TPkiSync, usePkiSyncOption } from "@app/hooks/api/pkiSyncs";
+import { CertStatus } from "@app/hooks/api";
+import { PkiSync, usePkiSyncOption } from "@app/hooks/api/pkiSyncs";
import { useListWorkspaceCertificates } from "@app/hooks/api/projects";
type Props = {
isOpen: boolean;
onClose: () => void;
- pkiSync?: TPkiSync;
destination?: PkiSync;
applicationId?: string;
- onCertificatesUpdated?: () => void;
- selectedCertificateIds?: string[];
- onCertificateSelectionChange?: (certificateIds: string[]) => void;
+ selectedOrderIds?: string[];
+ maxSelectable?: number;
+ onOrderSelectionChange?: (orderIds: string[], orderNames: [string, string][]) => void;
title?: string;
subtitle?: string;
saveButtonText?: string;
@@ -57,12 +51,11 @@ type Props = {
export const CertificateManagementModal = ({
isOpen,
onClose,
- pkiSync,
destination,
applicationId: applicationIdProp,
- onCertificatesUpdated,
- selectedCertificateIds,
- onCertificateSelectionChange,
+ selectedOrderIds,
+ maxSelectable,
+ onOrderSelectionChange,
title = "Manage Certificate Sync",
subtitle = "Select which certificates should be synced.",
saveButtonText = "Save Changes"
@@ -73,11 +66,11 @@ export const CertificateManagementModal = ({
const [debouncedSearchTerm, setDebouncedSearchTerm] = useState("");
const pageSize = 10;
- const isCreateMode = !pkiSync;
- const scopedApplicationId = pkiSync?.applicationId ?? applicationIdProp;
+ const scopedApplicationId = applicationIdProp;
- const { syncOption } = usePkiSyncOption((pkiSync?.destination ?? destination) as PkiSync);
- const isSingleSelect = syncOption?.maxCertificates === 1;
+ const { syncOption } = usePkiSyncOption(destination as PkiSync);
+ const selectionLimit = maxSelectable ?? syncOption?.maxCertificates;
+ const isSingleSelect = selectionLimit === 1;
useEffect(() => {
const handler = setTimeout(() => {
@@ -103,44 +96,60 @@ export const CertificateManagementModal = ({
const allCertificates = data?.certificates || [];
const totalCount = data?.totalCount || 0;
- const { data: syncData } = useListPkiSyncCertificates(pkiSync?.id || "", undefined, {
- enabled: Boolean(pkiSync?.id)
- });
- const syncCertificates = syncData?.certificates || [];
- const addCertificatesToSync = useAddCertificatesToPkiSync();
- const removeCertificatesFromSync = useRemoveCertificatesFromPkiSync();
-
- const syncedCertificateIds = isCreateMode
- ? selectedCertificateIds || []
- : syncCertificates.map((sc) => sc.certificateId);
+ const preselectedOrderIds = selectedOrderIds ?? [];
const totalPages = Math.ceil(totalCount / pageSize);
const [selectedIds, setSelectedIds] = useState<string[]>([]);
React.useEffect(() => {
- setSelectedIds(syncedCertificateIds);
- }, [JSON.stringify(syncedCertificateIds)]);
+ setSelectedIds(preselectedOrderIds);
+ }, [JSON.stringify(preselectedOrderIds)]);
- const handleToggleSelection = (certId: string) => {
+ const handleToggleSelection = (orderId: string) => {
setSelectedIds((prev) => {
- if (prev.includes(certId)) {
- return prev.filter((id) => id !== certId);
+ if (prev.includes(orderId)) {
+ return prev.filter((id) => id !== orderId);
}
- // Single-slot destinations (e.g. Nutanix) allow only one certificate
- return isSingleSelect ? [certId] : [...prev, certId];
+
+ if (isSingleSelect) return [orderId];
+
+ if (selectionLimit !== undefined && prev.length >= selectionLimit) {
+ createNotification({
+ text: `This sync holds at most ${selectionLimit} certificates. Deselect one first.`,
+ type: "error"
+ });
+ return prev;
+ }
+
+ return [...prev, orderId];
});
};
const handleSelectAll = () => {
- const currentPageIds = allCertificates.map((cert) => cert.id);
- const allCurrentPageSelected = currentPageIds.every((id) => selectedIds.includes(id));
+ const currentPageOrderIds = allCertificates
+ .map((cert) => cert.orderId)
+ .filter((orderId): orderId is string => Boolean(orderId));
+ const allCurrentPageSelected = currentPageOrderIds.every((id) => selectedIds.includes(id));
if (allCurrentPageSelected) {
- setSelectedIds((prev) => prev.filter((id) => !currentPageIds.includes(id)));
- } else {
- setSelectedIds((prev) => [...new Set([...prev, ...currentPageIds])]);
+ setSelectedIds((prev) => prev.filter((id) => !currentPageOrderIds.includes(id)));
+ return;
}
+
+ setSelectedIds((prev) => {
+ const next = [...new Set([...prev, ...currentPageOrderIds])];
+
+ if (selectionLimit !== undefined && next.length > selectionLimit) {
+ createNotification({
+ text: `This sync holds at most ${selectionLimit} certificates. Only the first ${selectionLimit} were selected.`,
+ type: "error"
+ });
+ return next.slice(0, selectionLimit);
+ }
+
+ return next;
+ });
};
const clearSearch = () => {
@@ -155,150 +164,15 @@ export const CertificateManagementModal = ({
}
}, [isOpen]);
- const handleSaveCertificates = async () => {
- try {
- if (isCreateMode) {
- if (onCertificateSelectionChange) {
- onCertificateSelectionChange(selectedIds);
- onClose();
- }
- return;
- }
+ const handleSaveCertificates = () => {
+ const orderNames = allCertificates
+ .filter((cert) => cert.orderId && selectedIds.includes(cert.orderId))
+ .map((cert) => [cert.orderId as string, cert.commonName] as [string, string]);
- if (!pkiSync) return;
-
- const certificatesToAdd = selectedIds.filter((id) => !syncedCertificateIds.includes(id));
- const certificatesToRemove = syncedCertificateIds.filter((id) => !selectedIds.includes(id));
-
- const invalidCertificates = certificatesToAdd
- .map((id) => allCertificates.find((cert) => cert.id === id))
- .filter((cert) => {
- if (!cert) return false;
- const isExpired = new Date(cert.notAfter) < new Date();
- const isRevoked = cert.status === CertStatus.REVOKED;
- return isExpired || isRevoked;
- });
-
- if (invalidCertificates.length > 0) {
- const invalidNames = invalidCertificates.map((cert) => cert?.commonName).join(", ");
- createNotification({
- text: `Cannot add expired or revoked certificates: ${invalidNames}`,
- type: "error"
- });
- return;
- }
-
- type TOperationResult = {
- type: "add" | "remove";
- count: number;
- success: boolean;
- error?: unknown;
- };
-
- const runRemove = async (): Promise<TOperationResult | null> => {
- if (certificatesToRemove.length === 0) return null;
- try {
- await removeCertificatesFromSync.mutateAsync({
- pkiSyncId: pkiSync.id,
- certificateIds: certificatesToRemove
- });
- return { type: "remove", count: certificatesToRemove.length, success: true };
- } catch (error) {
- return { type: "remove", count: certificatesToRemove.length, success: false, error };
- }
- };
-
- const runAdd = async (): Promise<TOperationResult | null> => {
- if (certificatesToAdd.length === 0) return null;
- try {
- await addCertificatesToSync.mutateAsync({
- pkiSyncId: pkiSync.id,
- certificateIds: certificatesToAdd
- });
- return { type: "add", count: certificatesToAdd.length, success: true };
- } catch (error) {
- return { type: "add", count: certificatesToAdd.length, success: false, error };
- }
- };
-
- let results: (TOperationResult | null)[];
- if (isSingleSelect) {
- // Single-slot destinations (e.g. Nutanix, maxCertificates: 1) must remove the
- // existing certificate before adding the replacement, otherwise the add would
- // transiently exceed the limit and be rejected. Other destinations keep the
- // original parallel behavior so their flow is unchanged.
- results = [await runRemove(), await runAdd()];
- } else {
- results = await Promise.all([runAdd(), runRemove()]);
- }
-
- const completed = results.filter((r): r is TOperationResult => r !== null);
-
- if (completed.length === 0) {
- createNotification({
- text: "No changes to save",
- type: "info"
- });
- onClose();
- return;
- }
-
- const failures = completed.filter((r) => !r.success);
- const successes = completed.filter((r) => r.success);
-
- if (failures.length === 0) {
- const addCount = successes.find((r) => r.type === "add")?.count || 0;
- const removeCount = successes.find((r) => r.type === "remove")?.count || 0;
-
- let message = "Certificate selection updated successfully";
- if (addCount > 0 && removeCount > 0) {
- message = `Added ${addCount} and removed ${removeCount} certificate(s)`;
- } else if (addCount > 0) {
- message = `Added ${addCount} certificate(s)`;
- } else if (removeCount > 0) {
- message = `Removed ${removeCount} certificate(s)`;
- }
-
- createNotification({
- text: message,
- type: "success"
- });
-
- if (onCertificatesUpdated) {
- onCertificatesUpdated();
- }
- onClose();
- } else {
- const partialSuccess = successes.length > 0;
-
- const firstError = failures.map((f) => (f as { error?: unknown }).error).find(Boolean) as
- | { response?: { data?: { message?: string } }; message?: string }
- | undefined;
- const reason =
- firstError?.response?.data?.message ?? firstError?.message ?? "Please try again.";
-
- createNotification({
- text: partialSuccess
- ? `Some certificate changes could not be saved: ${reason}`
- : `Failed to update certificate selection: ${reason}`,
- type: partialSuccess ? "warning" : "error"
- });
-
- if (partialSuccess && onCertificatesUpdated) {
- onCertificatesUpdated();
- }
- }
- } catch (error) {
- console.error("Unexpected error during certificate sync operation:", error);
- createNotification({
- text: "An unexpected error occurred while updating certificates",
- type: "error"
- });
- }
+ onOrderSelectionChange?.(selectedIds, orderNames);
+ onClose();
};
- const isLoading = addCertificatesToSync.isPending || removeCertificatesFromSync.isPending;
-
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-4xl">
@@ -358,7 +232,9 @@ export const CertificateManagementModal = ({
variant="project"
isChecked={
allCertificates.length > 0 &&
- allCertificates.every((cert) => selectedIds.includes(cert.id))
+ allCertificates.every(
+ (cert) => cert.orderId && selectedIds.includes(cert.orderId)
+ )
}
onCheckedChange={handleSelectAll}
/>
@@ -375,7 +251,9 @@ export const CertificateManagementModal = ({
const isExpired = new Date(cert.notAfter) < new Date();
const isRevoked = cert.status === CertStatus.REVOKED;
const cannotBeAdded = isExpired || isRevoked;
- const isAlreadySynced = syncedCertificateIds.includes(cert.id);
+ const isAlreadySynced = Boolean(
+ cert.orderId && preselectedOrderIds.includes(cert.orderId)
+ );
const { originalDisplayName, displayName, isTruncated } =
getCertificateDisplayName(cert);
@@ -388,8 +266,8 @@ export const CertificateManagementModal = ({
cannotBeAdded && !isAlreadySynced ? "opacity-50" : ""
}`}
onClick={() => {
- if (!cannotBeAdded || isAlreadySynced) {
- handleToggleSelection(cert.id);
+ if (cert.orderId && (!cannotBeAdded || isAlreadySynced)) {
+ handleToggleSelection(cert.orderId);
}
}}
>
@@ -397,10 +275,10 @@ export const CertificateManagementModal = ({
<Checkbox
id={cert.id}
variant="project"
- isChecked={selectedIds.includes(cert.id)}
+ isChecked={Boolean(cert.orderId && selectedIds.includes(cert.orderId))}
onCheckedChange={() => {
- if (!cannotBeAdded || isAlreadySynced) {
- handleToggleSelection(cert.id);
+ if (cert.orderId && (!cannotBeAdded || isAlreadySynced)) {
+ handleToggleSelection(cert.orderId);
}
}}
isDisabled={cannotBeAdded && !isAlreadySynced}
@@ -458,7 +336,7 @@ export const CertificateManagementModal = ({
<Button variant="outline" onClick={onClose}>
Cancel
</Button>
- <Button variant="project" onClick={handleSaveCertificates} isPending={isLoading}>
+ <Button variant="project" onClick={handleSaveCertificates}>
{saveButtonText}
</Button>
</DialogFooter>
diff --git a/frontend/src/components/pki-syncs/EditPkiSyncModal.tsx b/frontend/src/components/pki-syncs/EditPkiSyncModal.tsx
index b5065ca2d2..02865bb377 100644
--- a/frontend/src/components/pki-syncs/EditPkiSyncModal.tsx
+++ b/frontend/src/components/pki-syncs/EditPkiSyncModal.tsx
@@ -18,16 +18,17 @@ import {
} from "@app/components/v3";
import { TPkiSync } from "@app/hooks/api/pkiSyncs";
-import { EditPkiSyncForm } from "./forms";
+import { EditPkiSyncForm, TPkiSyncEditStepKey } from "./forms";
import { PkiSyncModalHeader } from "./PkiSyncModalHeader";
type Props = {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
pkiSync?: TPkiSync;
+ initialStepKey?: TPkiSyncEditStepKey;
};
-export const EditPkiSyncModal = ({ isOpen, pkiSync, onOpenChange }: Props) => {
+export const EditPkiSyncModal = ({ isOpen, pkiSync, onOpenChange, initialStepKey }: Props) => {
const [isDirty, setIsDirty] = useState(false);
const [confirmDiscardOpen, setConfirmDiscardOpen] = useState(false);
@@ -61,6 +62,7 @@ export const EditPkiSyncModal = ({ isOpen, pkiSync, onOpenChange }: Props) => {
</SheetHeader>
<div className="flex min-h-0 flex-1 flex-col">
<EditPkiSyncForm
+ initialStepKey={initialStepKey}
pkiSync={pkiSync}
onComplete={() => onOpenChange(false)}
onDirtyChange={setIsDirty}
diff --git a/frontend/src/components/pki-syncs/PkiSyncFilterBadges.tsx b/frontend/src/components/pki-syncs/PkiSyncFilterBadges.tsx
new file mode 100644
index 0000000000..ee7457e69e
--- /dev/null
+++ b/frontend/src/components/pki-syncs/PkiSyncFilterBadges.tsx
@@ -0,0 +1,132 @@
+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";
+
+type TFilterCountLabelProps = { count: number; names: string[] };
+
+const FilterBadgeOverflow = ({ badges }: { badges: ReactNode[] }) => {
+ const [first, ...rest] = badges;
+
+ return (
+ <div className="flex min-w-0 flex-wrap items-center gap-1">
+ {first}
+ {rest.length > 0 && (
+ <HoverCard openDelay={100}>
+ <HoverCardTrigger asChild>
+ <Badge variant="neutral" className="cursor-default">
+ +{rest.length}
+ </Badge>
+ </HoverCardTrigger>
+ <HoverCardContent className="flex w-auto max-w-xs flex-wrap gap-1.5">
+ {rest}
+ </HoverCardContent>
+ </HoverCard>
+ )}
+ </div>
+ );
+};
+
+export const PkiSyncAnyFilterLabel = <span className="text-sm text-muted/50 italic">Any</span>;
+
+export const PkiSyncNoFilterLabel = <span className="text-sm text-muted/50 italic">None</span>;
+
+export const PkiSyncFilterCountLabel = ({ count, names }: TFilterCountLabelProps) => {
+ const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(null);
+
+ const rootRef = useCallback((node: HTMLSpanElement | null) => {
+ if (node) setPortalContainer(node.closest<HTMLElement>('[role="dialog"]'));
+ }, []);
+
+ if (names.length === 0) return <span className="text-sm text-foreground">{count}</span>;
+
+ return (
+ <HoverCard openDelay={100}>
+ <HoverCardTrigger asChild>
+ <span ref={rootRef} className="text-sm text-foreground">
+ {count}
+ </span>
+ </HoverCardTrigger>
+ <HoverCardContent
+ container={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">
+ {name}
+ </span>
+ ))}
+ </HoverCardContent>
+ </HoverCard>
+ );
+};
+
+export const PkiSyncFilterValueBadges = ({ values }: { values: string[] }) => {
+ if (values.length === 0) return null;
+
+ return (
+ <FilterBadgeOverflow
+ badges={values.map((value) => (
+ <Badge key={value} variant="neutral" isTruncatable className="max-w-[12rem]">
+ <span>{value}</span>
+ </Badge>
+ ))}
+ />
+ );
+};
+
+export const buildPkiSyncFilterSummary = ({
+ filters,
+ profileNameById,
+ orderNameById
+}: {
+ filters: TPkiSyncFilters | null | undefined;
+ profileNameById: Map<string, string>;
+ orderNameById: Map<string, string>;
+}): { label: string; value: ReactNode }[] | null => {
+ if (!hasAnyFilter(filters)) return null;
+
+ const metadataPairs = (filters?.metadata ?? [])
+ .filter((pair) => pair.key)
+ .map((pair) => (pair.value === undefined ? pair.key : `${pair.key}=${pair.value}`));
+
+ const emptyOrAny = (kind: TFilterKind) =>
+ 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));
+
+ return [
+ {
+ label: "Profiles",
+ value: filters?.profileIds?.length ? (
+ <PkiSyncFilterValueBadges
+ values={filters.profileIds.map((id) => profileNameById.get(id) ?? id)}
+ />
+ ) : (
+ emptyOrAny("profileIds")
+ )
+ },
+ {
+ label: "Certificate Orders",
+ value: filters?.certificateOrderIds?.length ? (
+ <PkiSyncFilterCountLabel
+ count={filters.certificateOrderIds.length}
+ names={namesFor(filters.certificateOrderIds, orderNameById)}
+ />
+ ) : (
+ emptyOrAny("certificateOrderIds")
+ )
+ },
+ {
+ label: "Metadata",
+ value: metadataPairs.length ? (
+ <PkiSyncFilterCountLabel count={metadataPairs.length} names={metadataPairs} />
+ ) : (
+ emptyOrAny("metadata")
+ )
+ }
+ ];
+};
diff --git a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
index 90b3fc527d..cd43850b13 100644
--- a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
+++ b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
@@ -110,10 +110,10 @@ const STEP_META: Record<
},
certificates: {
short: "Certificates to sync",
- subtitle: "Select which of this application's certificates are included in the sync.",
+ subtitle: "Link the certificates this sync pushes.",
rightLabel: "CERTIFICATES",
rightDescription:
- "Select which of this application's certificates are included in the sync. You can change this selection after the sync is created."
+ "Anything in the Application matching these filters is attached as it is issued. A sync with no filters holds nothing."
},
review: {
short: "Confirm and create",
@@ -168,7 +168,7 @@ const getFormTabs = (
{
name: "Certificates",
key: "certificates",
- fields: ["certificateIds"] as FieldPath<TPkiSyncForm>[]
+ fields: ["filters"] as FieldPath<TPkiSyncForm>[]
}
);
@@ -210,7 +210,7 @@ export const CreatePkiSyncForm = ({
defaultValues: {
destination,
isAutoSyncEnabled: false,
- certificateIds: [],
+ filters: null,
syncOptions: {
canImportCertificates: false,
canRemoveCertificates: false,
@@ -255,34 +255,24 @@ export const CreatePkiSyncForm = ({
selectedConnectionApp === AppConnection.LDAP
);
- const onSubmit = async ({
- connection,
- destinationConfig,
- certificateIds,
- ...formData
- }: TPkiSyncForm) => {
+ const onSubmit = async ({ connection, destinationConfig, ...formData }: TPkiSyncForm) => {
try {
const pkiSync = await createPkiSync.mutateAsync({
...formData,
connectionId: connection.id,
projectId: currentProject.id,
applicationId,
- destinationConfig,
- certificateIds: certificateIds || []
+ destinationConfig
});
createNotification({
- text: `Successfully created ${destinationName} Certificate Sync${
- certificateIds && certificateIds.length > 0
- ? ` with ${certificateIds.length} certificate(s)`
- : ""
- }`,
+ text: `Successfully created ${destinationName} Certificate Sync`,
type: "success"
});
setShowConfirmation(false);
onComplete(pkiSync);
} catch {
- /* empty */
+ setShowConfirmation(false);
}
};
@@ -443,7 +433,7 @@ export const CreatePkiSyncForm = ({
{currentKey === "certificates" && (
<PkiSyncCertificatesFields applicationId={applicationId} />
)}
- {currentKey === "review" && <PkiSyncReviewFields />}
+ {currentKey === "review" && <PkiSyncReviewFields applicationId={applicationId} />}
</div>
<aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">
@@ -508,8 +498,9 @@ export const CreatePkiSyncForm = ({
</p>
{syncOption?.canRemoveCertificates && canRemoveCertificates && (
<p>
- Certificates in {destinationName} that are no longer active in Infisical will be
- removed.
+ Certificates that leave this sync will be deleted from {destinationName},
+ whether they stopped being active, were deleted, or stopped matching the
+ sync&apos;s filters.
</p>
)}
</div>
diff --git a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
index da30c74205..f31892064d 100644
--- a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
+++ b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
@@ -1,9 +1,19 @@
import { useEffect, useState } from "react";
import { Controller, FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
+import { AlertTriangleIcon } from "lucide-react";
import { createNotification } from "@app/components/notifications";
import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogMedia,
+ AlertDialogTitle,
Button,
DocumentationLinkBadge,
Field,
@@ -23,10 +33,13 @@ import {
useCanSetHealthCheckCommand,
useCanSetPostSyncCommand,
usePkiSyncOption,
+ usePreviewPkiSyncFilters,
useUpdatePkiSync
} from "@app/hooks/api/pkiSyncs";
+import { TPkiSyncFilterPreview } from "@app/hooks/api/pkiSyncs/types";
import { TUpdatePkiSyncForm, UpdatePkiSyncFormSchema } from "./schemas/pki-sync-schema";
+import { PkiSyncCertificatesFields } from "./PkiSyncCertificatesFields";
import { PkiSyncDestinationFields } from "./PkiSyncDestinationFields";
import { PkiSyncDetailsFields } from "./PkiSyncDetailsFields";
import { PkiSyncFieldMappingsFields } from "./PkiSyncFieldMappingsFields";
@@ -40,10 +53,20 @@ type Props = {
pkiSync: TPkiSync;
onDirtyChange?: (isDirty: boolean) => void;
onCancel?: () => void;
+ initialStepKey?: TPkiSyncEditStepKey;
};
+export type TPkiSyncEditStepKey =
+ | "destination"
+ | "targetHost"
+ | "options"
+ | "mappings"
+ | "hostCommands"
+ | "certificates"
+ | "details";
+
type FormStep = {
- key: string;
+ key: TPkiSyncEditStepKey;
name: string;
description: string;
title: string;
@@ -69,7 +92,7 @@ const getFormSteps = (
"Choose the connection and the destination where certificates will be pushed. The available fields depend on the selected service."
},
...(needsTargetHost
- ? [
+ ? ([
{
key: "targetHost",
name: "Target Host",
@@ -80,7 +103,7 @@ const getFormSteps = (
rightDescription:
"An LDAP Connection supplies the credential for a whole domain rather than one machine, so each sync names its own host.\n\nMachines found in the directory are offered as suggestions, and you can enter one that is not listed."
}
- ]
+ ] as FormStep[])
: []),
{
key: "options",
@@ -120,6 +143,17 @@ const getFormSteps = (
});
}
+ steps.push({
+ key: "certificates",
+ name: "Certificates",
+ description: "Filters and certificates",
+ title: "Certificates",
+ 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."
+ });
+
steps.push({
key: "details",
name: "Details",
@@ -142,13 +176,27 @@ const LDAP_TARGET_DEFAULTS = {
sslCertificate: undefined
};
-export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel }: Props) => {
+export const EditPkiSyncForm = ({
+ pkiSync,
+ onComplete,
+ onDirtyChange,
+ onCancel,
+ initialStepKey
+}: Props) => {
const updatePkiSync = useUpdatePkiSync();
const { name: destinationName } = PKI_SYNC_MAP[pkiSync.destination];
const { syncOption } = usePkiSyncOption(pkiSync.destination);
const canSetPostSyncCommand = useCanSetPostSyncCommand(pkiSync.applicationId);
const canSetHealthCheckCommand = useCanSetHealthCheckCommand(pkiSync.applicationId);
- const [selectedStepIndex, setSelectedStepIndex] = useState(0);
+ const [selectedStepIndex, setSelectedStepIndex] = useState(() => {
+ const initialSteps = getFormSteps(
+ pkiSync.destination,
+ Boolean(syncOption?.canRunHealthCheckCommand || syncOption?.canRunPostSyncCommand),
+ pkiSync.connection.app === AppConnection.LDAP
+ );
+ const initialIndex = initialSteps.findIndex((step) => step.key === initialStepKey);
+ return initialIndex === -1 ? 0 : initialIndex;
+ });
const formMethods = useForm<TUpdatePkiSyncForm>({
resolver: zodResolver(UpdatePkiSyncFormSchema),
@@ -163,7 +211,8 @@ export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel }
},
syncOptions: pkiSync.syncOptions,
destinationConfig: { ...LDAP_TARGET_DEFAULTS, ...pkiSync.destinationConfig },
- isAutoSyncEnabled: pkiSync.isAutoSyncEnabled
+ isAutoSyncEnabled: pkiSync.isAutoSyncEnabled,
+ filters: pkiSync.filters ?? null
} as Partial<TUpdatePkiSyncForm>,
reValidateMode: "onChange"
});
@@ -183,11 +232,17 @@ export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel }
formState: { isSubmitting, isDirty }
} = formMethods;
+ const previewFilters = usePreviewPkiSyncFilters();
+ const [pendingUnlink, setPendingUnlink] = useState<{
+ preview: TPkiSyncFilterPreview;
+ formData: TUpdatePkiSyncForm;
+ } | null>(null);
+
useEffect(() => {
onDirtyChange?.(isDirty);
}, [isDirty, onDirtyChange]);
- const onSubmit = async ({ connection, ...formData }: TUpdatePkiSyncForm) => {
+ const applyUpdate = async ({ connection, ...formData }: TUpdatePkiSyncForm) => {
try {
const updatedPkiSync = await updatePkiSync.mutateAsync({
syncId: pkiSync.id,
@@ -207,6 +262,29 @@ export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel }
}
};
+ const onSubmit = async (formData: TUpdatePkiSyncForm) => {
+ const haveFiltersChanged =
+ JSON.stringify(formData.filters ?? null) !== JSON.stringify(pkiSync.filters ?? null);
+
+ if (haveFiltersChanged) {
+ try {
+ const preview = await previewFilters.mutateAsync({
+ pkiSyncId: pkiSync.id,
+ filters: formData.filters
+ });
+
+ if (preview.toUnlink.length > 0) {
+ setPendingUnlink({ preview, formData });
+ return;
+ }
+ } catch {
+ return;
+ }
+ }
+
+ await applyUpdate(formData);
+ };
+
const currentStep = steps[selectedStepIndex];
const renderStep = () => {
@@ -261,6 +339,13 @@ export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel }
/>
</div>
);
+ case "certificates":
+ return (
+ <PkiSyncCertificatesFields
+ applicationId={pkiSync.applicationId ?? undefined}
+ pkiSyncId={pkiSync.id}
+ />
+ );
case "details":
return <PkiSyncDetailsFields />;
default:
@@ -365,6 +450,56 @@ export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel }
</div>
</div>
</form>
+
+ <AlertDialog
+ open={Boolean(pendingUnlink)}
+ onOpenChange={(open) => {
+ if (!open && !isSubmitting) setPendingUnlink(null);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogMedia>
+ <AlertTriangleIcon className="text-warning" />
+ </AlertDialogMedia>
+ <AlertDialogTitle>
+ {pendingUnlink?.preview.toUnlink.length} certificate
+ {pendingUnlink?.preview.toUnlink.length === 1 ? "" : "s"} will be detached
+ </AlertDialogTitle>
+ <AlertDialogDescription asChild>
+ <div className="flex flex-col gap-2">
+ <p>These certificates no longer match the filters and will be detached:</p>
+ <ul className="max-h-40 overflow-y-auto font-mono text-xs">
+ {pendingUnlink?.preview.toUnlink.map((certificate) => (
+ <li key={certificate.id}>{certificate.commonName}</li>
+ ))}
+ </ul>
+ {pendingUnlink?.preview.willRemoveFromDestination && (
+ <p>
+ Removal is enabled on this sync, so they will also be deleted from{" "}
+ {destinationName}.
+ </p>
+ )}
+ </div>
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel isDisabled={isSubmitting}>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="danger"
+ isPending={isSubmitting}
+ onClick={(event) => {
+ event.preventDefault();
+ const pending = pendingUnlink;
+ setPendingUnlink(null);
+ if (pending) applyUpdate(pending.formData).catch(() => {});
+ }}
+ >
+ Detach and save
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</FormProvider>
);
};
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncCertificateAddMenu.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncCertificateAddMenu.tsx
new file mode 100644
index 0000000000..165b5051bb
--- /dev/null
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncCertificateAddMenu.tsx
@@ -0,0 +1,86 @@
+import { useFormContext } from "react-hook-form";
+import { PlusIcon } from "lucide-react";
+
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger
+} from "@app/components/v3";
+import { PkiSync, usePkiSyncOption } from "@app/hooks/api/pkiSyncs";
+import { TPkiSyncFilters } from "@app/hooks/api/pkiSyncs/types";
+
+import { TPkiSyncForm } from "./schemas/pki-sync-schema";
+import {
+ FILTER_KINDS,
+ FILTER_LABELS,
+ getPkiSyncCertificateCap,
+ isFilterPresent,
+ TFilterKind
+} from "./pki-sync-filter-fns";
+
+const FILTER_HINTS: Record<TFilterKind, string> = {
+ certificateOrderIds: "Follows every renewal of a certificate",
+ profileIds: "Issued from one of these profiles",
+ metadata: "Carries this key and value"
+};
+
+type Props = {
+ applicationId?: string;
+ onOpenPicker: () => void;
+};
+
+export const PkiSyncCertificateAddMenu = ({ applicationId, onOpenPicker }: Props) => {
+ const { watch, setValue } = useFormContext<TPkiSyncForm>();
+ const { syncOption } = usePkiSyncOption(watch("destination") as PkiSync);
+ const filters = (watch("filters") ?? {}) as TPkiSyncFilters;
+
+ const certificateCap = getPkiSyncCertificateCap({
+ destinationMaxCertificates: syncOption?.maxCertificates,
+ syncOptions: watch("syncOptions") as Record<string, unknown> | undefined,
+ destinationConfig: watch("destinationConfig") as Record<string, unknown> | undefined
+ });
+
+ const supportsFilters = Boolean(applicationId);
+
+ const addableFilterKinds = FILTER_KINDS.filter(
+ (kind) =>
+ (certificateCap === undefined || kind === "certificateOrderIds") &&
+ (kind === "metadata" || !isFilterPresent(filters, kind))
+ );
+
+ const addFilter = (kind: TFilterKind) => {
+ if (kind === "certificateOrderIds") {
+ setValue("filters", { ...filters, [kind]: [] }, { shouldDirty: true });
+ onOpenPicker();
+ return;
+ }
+
+ const next = kind === "metadata" ? [...(filters.metadata ?? []), { key: "" }] : [];
+ setValue("filters", { ...filters, [kind]: next }, { shouldDirty: true });
+ };
+
+ if (!supportsFilters || addableFilterKinds.length === 0) return null;
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button type="button" variant="outline" size="sm">
+ <PlusIcon className="size-3.5" />
+ Add Filter
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-64">
+ {addableFilterKinds.map((kind) => (
+ <DropdownMenuItem key={kind} onClick={() => addFilter(kind)}>
+ <div className="flex flex-col">
+ <span>{FILTER_LABELS[kind]}</span>
+ <span className="text-xs text-muted">{FILTER_HINTS[kind]}</span>
+ </div>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+};
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncCertificatesFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncCertificatesFields.tsx
index ea4b547e91..81177e1fcb 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncCertificatesFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncCertificatesFields.tsx
@@ -1,186 +1,229 @@
import { useMemo, useState } from "react";
-import { Controller, useFormContext } from "react-hook-form";
-import { Pencil, ScrollText, Trash2 } from "lucide-react";
+import { useFormContext } from "react-hook-form";
+import { FilterIcon, RefreshCwIcon, TriangleAlertIcon } from "lucide-react";
import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
Button,
Empty,
+ EmptyDescription,
EmptyMedia,
- EmptyTitle,
- Field,
- FieldError,
- IconButton,
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
Tooltip,
TooltipContent,
TooltipTrigger
} from "@app/components/v3";
import { useProject } from "@app/context";
-import { getCertificateDisplayName, truncateCertificateSerialNumber } from "@app/helpers/pkiSyncs";
-import { CertStatus } from "@app/hooks/api";
-import { useListWorkspaceCertificates } from "@app/hooks/api/projects";
+import { PkiSync, usePkiSyncOption, usePkiSyncPreviewCertificates } from "@app/hooks/api/pkiSyncs";
+import { TPkiSyncFilters } from "@app/hooks/api/pkiSyncs/types";
import { CertificateManagementModal } from "../CertificateManagementModal";
import { TPkiSyncForm } from "./schemas/pki-sync-schema";
+import {
+ buildOrderNameMap,
+ getPkiSyncCertificateCap,
+ hasAnyFilter,
+ hasUnfinishedFilter
+} from "./pki-sync-filter-fns";
+import { PkiSyncCertificateAddMenu } from "./PkiSyncCertificateAddMenu";
+import { PkiSyncFilterFields } from "./PkiSyncFilterFields";
+import {
+ PkiSyncMatchedCertificatesTable,
+ TMatchedCertificateRow
+} from "./PkiSyncMatchedCertificatesTable";
type Props = {
applicationId?: string;
+ pkiSyncId?: string;
};
-export const PkiSyncCertificatesFields = ({ applicationId }: Props = {}) => {
- const { control, watch, setValue } = useFormContext<TPkiSyncForm>();
+export const PkiSyncCertificatesFields = ({ applicationId, pkiSyncId }: Props) => {
+ const { watch, setValue } = useFormContext<TPkiSyncForm>();
const { currentProject } = useProject();
- const [isSelectionModalOpen, setIsSelectionModalOpen] = useState(false);
- const certificateIds = watch("certificateIds") || [];
+ const filters = watch("filters") as TPkiSyncFilters | null | undefined;
+ const filtersKey = JSON.stringify(filters ?? null);
+
+ const { syncOption } = usePkiSyncOption(watch("destination") as PkiSync);
+ const certificateCap = getPkiSyncCertificateCap({
+ destinationMaxCertificates: syncOption?.maxCertificates,
+ syncOptions: watch("syncOptions") as Record<string, unknown> | undefined,
+ destinationConfig: watch("destinationConfig") as Record<string, unknown> | undefined
+ });
+
+ const growableFilterKinds = [
+ filters?.profileIds === undefined ? null : "certificate profile",
+ filters?.metadata === undefined ? null : "metadata"
+ ].filter((kind): kind is string => Boolean(kind));
- const { data, isLoading } = useListWorkspaceCertificates({
+ const [isPickerOpen, setIsPickerOpen] = useState(false);
+ const [previewFilters, setPreviewFilters] = useState<TPkiSyncFilters | null>(filters ?? null);
+ const previewKey = JSON.stringify(previewFilters ?? null);
+
+ const isStale = filtersKey !== previewKey;
+ const isUnfinished = hasUnfinishedFilter(filters);
+
+ const {
+ data: preview,
+ refetch: refetchPreview,
+ isFetching: isPreviewing
+ } = usePkiSyncPreviewCertificates({
projectId: currentProject?.id || "",
- offset: 0,
- limit: 100,
- forPkiSync: true,
- applicationId
+ applicationId,
+ pkiSyncId,
+ filters: previewFilters,
+ enabled: Boolean(applicationId) && hasAnyFilter(previewFilters)
});
- const certificates = data?.certificates || [];
+ const reloadPreview = () => {
+ if (isStale) setPreviewFilters(filters ?? null);
+ else refetchPreview().catch(() => {});
+ };
- const activeCertificates = useMemo(
- () => certificates.filter((cert) => cert.status === CertStatus.ACTIVE),
- [certificates]
+ const [pickedOrderNames, setPickedOrderNames] = useState<[string, string][]>([]);
+
+ const orderNameById = useMemo(
+ () => new Map([...buildOrderNameMap(preview?.certificates), ...pickedOrderNames]),
+ [preview, pickedOrderNames]
);
- const selectedCertificates = useMemo(
- () => activeCertificates.filter((cert) => certificateIds.includes(cert.id)),
- [activeCertificates, certificateIds]
+ const matchedRows: TMatchedCertificateRow[] = preview?.certificates ?? [];
+
+ 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.`;
+ }
+ return `Showing ${matchedRows.length} certificate${matchedRows.length === 1 ? "" : "s"} matched by these filters.`;
+ };
+
+ 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>
);
- if (isLoading) {
+ if (!applicationId) {
return (
- <div className="flex items-center justify-center py-8">
- <div className="text-sm text-muted">Loading certificates...</div>
- </div>
+ <Empty className="flex-none border py-8">
+ <EmptyMedia variant="icon">
+ <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.
+ </EmptyDescription>
+ </Empty>
);
}
return (
<div className="flex min-h-0 flex-1 flex-col">
- <Controller
- control={control}
- name="certificateIds"
- render={({ field: { value = [], onChange }, fieldState: { error } }) => (
- <Field className="min-h-0 flex-1">
- <div className="flex min-h-0 flex-1 flex-col gap-4">
- <Button
- type="button"
- variant="outline"
- size="sm"
- className="self-end"
- onClick={() => setIsSelectionModalOpen(true)}
- >
- <Pencil className="size-3.5" />
- Add Certificates
- </Button>
- <div className="min-h-0 flex-1 overflow-y-auto">
- {selectedCertificates.length > 0 ? (
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>SAN / CN</TableHead>
- <TableHead className="w-1/5">Serial Number</TableHead>
- <TableHead className="w-1/6">Issued At</TableHead>
- <TableHead className="w-1/6">Expires At</TableHead>
- <TableHead variant="action" />
- </TableRow>
- </TableHeader>
- <TableBody>
- {selectedCertificates.map((cert) => {
- const { originalDisplayName, displayName, isTruncated } =
- getCertificateDisplayName(cert);
- const truncatedSerial = truncateCertificateSerialNumber(cert.serialNumber);
-
- const isExpired = new Date(cert.notAfter) < new Date();
-
- return (
- <TableRow key={cert.id}>
- <TableCell className="max-w-0">
- {isTruncated ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <div className="truncate">{displayName}</div>
- </TooltipTrigger>
- <TooltipContent className="max-w-lg">
- {originalDisplayName}
- </TooltipContent>
- </Tooltip>
- ) : (
- <div className="truncate">{displayName}</div>
- )}
- </TableCell>
- <TableCell className="max-w-0">
- <div className="font-mono text-xs" title={cert.serialNumber}>
- {truncatedSerial}
- </div>
- </TableCell>
- <TableCell className="max-w-0">
- <span className="text-sm">
- {new Date(cert.notBefore).toLocaleDateString()}
- </span>
- </TableCell>
- <TableCell className="max-w-0">
- <span className={isExpired ? "text-sm text-danger" : "text-sm"}>
- {new Date(cert.notAfter).toLocaleDateString()}
- </span>
- </TableCell>
- <TableCell variant="action">
- <IconButton
- type="button"
- size="xs"
- variant="ghost"
- aria-label="Remove certificate"
- onClick={() => {
- const newIds = value.filter((id: string) => id !== cert.id);
- onChange(newIds);
- }}
- >
- <Trash2 />
- </IconButton>
- </TableCell>
- </TableRow>
- );
- })}
- </TableBody>
- </Table>
- ) : (
- <Empty className="border py-8">
- <EmptyMedia variant="icon">
- <ScrollText />
- </EmptyMedia>
- <EmptyTitle>No certificates selected</EmptyTitle>
- </Empty>
- )}
- </div>
+ <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>
+ </div>
+ <PkiSyncCertificateAddMenu
+ applicationId={applicationId}
+ onOpenPicker={() => setIsPickerOpen(true)}
+ />
+ </div>
+
+ {certificateCap !== undefined && growableFilterKinds.length > 0 && (
+ <Alert variant="warning" className="mt-3">
+ <AlertTitle>
+ {growableFilterKinds.length === 1
+ ? `Remove the ${growableFilterKinds[0]} filter`
+ : "Remove the filters below"}
+ </AlertTitle>
+ <AlertDescription>
+ {`This sync holds at most ${certificateCap} certificate${
+ certificateCap === 1 ? "" : "s"
+ }, so it only accepts a certificate order filter.`}
+ </AlertDescription>
+ </Alert>
+ )}
+
+ {hasAnyFilter(filters) ? (
+ <PkiSyncFilterFields
+ applicationId={applicationId}
+ orderNameById={orderNameById}
+ onOpenPicker={() => setIsPickerOpen(true)}
+ />
+ ) : (
+ <Empty className="mt-3 flex-none border py-8">
+ <EmptyMedia variant="icon">
+ <FilterIcon />
+ </EmptyMedia>
+ <EmptyDescription>
+ No filters, so this sync holds nothing. Add one to select certificates.
+ </EmptyDescription>
+ </Empty>
+ )}
+
+ {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>
</div>
- <FieldError errors={[error]} />
- </Field>
- )}
- />
+ {isStale ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>{reloadButton}</span>
+ </TooltipTrigger>
+ <TooltipContent>
+ {isUnfinished
+ ? "A filter is unfinished. Complete it, then reload the preview."
+ : "Filters changed. Reload the preview to see what they match now."}
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ reloadButton
+ )}
+ </div>
+
+ <div className="mt-3 min-h-0 flex-1 overflow-y-auto">
+ <PkiSyncMatchedCertificatesTable
+ rows={matchedRows}
+ isLoading={isPreviewing}
+ emptyTitle="No certificates match"
+ emptyDescription="Nothing in this Application matches these filters yet."
+ />
+ </div>
+ </>
+ )}
<CertificateManagementModal
- isOpen={isSelectionModalOpen}
- onClose={() => setIsSelectionModalOpen(false)}
+ isOpen={isPickerOpen}
+ onClose={() => setIsPickerOpen(false)}
destination={watch("destination")}
applicationId={applicationId}
- selectedCertificateIds={certificateIds}
- onCertificateSelectionChange={(newCertificateIds) => {
- setValue("certificateIds", newCertificateIds);
+ maxSelectable={certificateCap}
+ selectedOrderIds={filters?.certificateOrderIds ?? []}
+ onOrderSelectionChange={(certificateOrderIds, orderNames) => {
+ setPickedOrderNames((prev) => [...prev, ...orderNames]);
+ setValue("filters", { ...(filters ?? {}), certificateOrderIds }, { shouldDirty: true });
}}
- title="Select Certificates for Sync"
- subtitle="Choose which certificates you want to include in this sync. You can modify this selection after creating the sync."
+ title="Select Certificate Orders for Sync"
+ subtitle="Selecting a certificate selects its order, which follows every renewal."
saveButtonText="Update Selection"
/>
</div>
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncFilterFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncFilterFields.tsx
new file mode 100644
index 0000000000..a86230197d
--- /dev/null
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncFilterFields.tsx
@@ -0,0 +1,273 @@
+import { useCallback, useMemo, useState } from "react";
+import { Controller, useFormContext } from "react-hook-form";
+import { PlusIcon, XIcon } from "lucide-react";
+
+import {
+ Badge,
+ Button,
+ FieldError,
+ FilterableSelect,
+ IconButton,
+ Input,
+ Popover,
+ PopoverContent,
+ PopoverTrigger
+} from "@app/components/v3";
+import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";
+import { TPkiSyncFilters } from "@app/hooks/api/pkiSyncs/types";
+
+import { TPkiSyncForm } from "./schemas/pki-sync-schema";
+import { FILTER_LABELS, presentFilterKinds, TFilterKind } from "./pki-sync-filter-fns";
+
+type TProfileOption = { label: string; value: string };
+
+type TFilterErrors = {
+ metadata?: ({ key?: { message?: string }; value?: { message?: string } } | undefined)[];
+};
+
+type Props = {
+ applicationId?: string;
+ orderNameById: Map<string, string>;
+ onOpenPicker: () => void;
+};
+
+export const PkiSyncFilterFields = ({ applicationId, orderNameById, onOpenPicker }: Props) => {
+ const { control } = useFormContext<TPkiSyncForm>();
+ const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(null);
+
+ const rootRef = useCallback((node: HTMLDivElement | null) => {
+ if (node) setPortalContainer(node.closest<HTMLElement>('[role="dialog"]'));
+ }, []);
+
+ const { data: profileData } = useListCertificateProfiles({
+ applicationId,
+ limit: 100,
+ offset: 0
+ });
+
+ const profileOptions: TProfileOption[] = useMemo(
+ () =>
+ (profileData?.certificateProfiles ?? []).map((profile) => ({
+ label: profile.slug,
+ value: profile.id
+ })),
+ [profileData]
+ );
+
+ return (
+ <Controller
+ control={control}
+ name="filters"
+ render={({ field: { value, onChange }, fieldState: { error } }) => {
+ const filters = (value ?? {}) as TPkiSyncFilters;
+ const filterErrors = error as TFilterErrors | undefined;
+ const metadata = filters.metadata ?? [];
+ const kinds = presentFilterKinds(filters);
+
+ const setFilter = (kind: TFilterKind, next: unknown) =>
+ onChange({ ...filters, [kind]: next });
+
+ const removeFilter = (kind: TFilterKind) => {
+ const rest = { ...filters };
+ delete rest[kind];
+ onChange(Object.keys(rest).length ? rest : null);
+ };
+
+ const renderOrderChips = () => {
+ const kind = "certificateOrderIds" as const;
+ const ids = filters[kind] ?? [];
+ const [first, ...rest] = ids;
+ const labelFor = (id: string) => orderNameById.get(id) ?? id;
+
+ return (
+ <div className="flex h-9 w-full min-w-0 items-center justify-between gap-1.5">
+ <div className="flex min-w-0 flex-1 items-center gap-1.5">
+ {first && (
+ <Badge
+ variant="outline"
+ isTruncatable
+ className="h-9 min-w-0 flex-1 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)
+ )
+ }
+ >
+ <XIcon />
+ </IconButton>
+ </div>
+ ))}
+ </PopoverContent>
+ </Popover>
+ )}
+ </div>
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="h-9 shrink-0"
+ onClick={() => onOpenPicker()}
+ >
+ <PlusIcon className="size-3" />
+ Add
+ </Button>
+ </div>
+ );
+ };
+
+ const renderBody = (kind: TFilterKind) => {
+ if (kind === "profileIds") {
+ return (
+ <FilterableSelect
+ isMulti
+ placeholder="Select profiles"
+ options={profileOptions}
+ value={profileOptions.filter((option) =>
+ (filters.profileIds ?? []).includes(option.value)
+ )}
+ onChange={(options) =>
+ setFilter(
+ "profileIds",
+ ((options as TProfileOption[]) ?? []).map((option) => option.value)
+ )
+ }
+ />
+ );
+ }
+
+ if (kind === "metadata") {
+ return (
+ <div className="flex flex-col gap-2">
+ {metadata.map((pair, index) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <div key={index} className="flex items-center gap-2">
+ <Input
+ className="min-w-0 flex-1 font-mono"
+ placeholder="Key"
+ value={pair.key}
+ onChange={(e) =>
+ setFilter(
+ "metadata",
+ metadata.map((entry, i) =>
+ i === index ? { ...entry, key: e.target.value } : entry
+ )
+ )
+ }
+ />
+ <Input
+ className="min-w-0 flex-1 font-mono"
+ placeholder="Any value"
+ value={pair.value ?? ""}
+ onChange={(e) =>
+ setFilter(
+ "metadata",
+ metadata.map((entry, i) =>
+ i === index ? { ...entry, value: e.target.value || undefined } : entry
+ )
+ )
+ }
+ />
+ <IconButton
+ type="button"
+ size="sm"
+ variant="ghost"
+ className="ml-2"
+ aria-label="Remove metadata pair"
+ onClick={() => {
+ if (metadata.length === 1) {
+ removeFilter("metadata");
+ return;
+ }
+ setFilter(
+ "metadata",
+ metadata.filter((_, i) => i !== index)
+ );
+ }}
+ >
+ <XIcon />
+ </IconButton>
+ </div>
+ ))}
+ <FieldError
+ errors={metadata.flatMap((_, index) => [
+ filterErrors?.metadata?.[index]?.key,
+ filterErrors?.metadata?.[index]?.value
+ ])}
+ />
+ </div>
+ );
+ }
+
+ return renderOrderChips();
+ };
+
+ 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>
+ ))}
+ </div>
+ );
+ }}
+ />
+ );
+};
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncHealthCheckCommandFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncHealthCheckCommandFields.tsx
index 8efaf26ab0..2c2ac42319 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncHealthCheckCommandFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncHealthCheckCommandFields.tsx
@@ -4,6 +4,7 @@ import { createNotification } from "@app/components/notifications";
import { Button } from "@app/components/v3";
import { HEALTH_CHECK_COMMAND_VARIABLE_DESCRIPTIONS } from "@app/helpers/pkiSyncs";
import { PkiSync, PkiSyncStatus, useTestPkiSyncHealthCheck } from "@app/hooks/api/pkiSyncs";
+import { TPkiSyncFilters } from "@app/hooks/api/pkiSyncs/types";
import { TPkiSyncForm } from "./schemas/pki-sync-schema";
import { notifyUnhandledHostCommandError } from "./hostCommandErrors";
@@ -43,7 +44,7 @@ export const PkiSyncHealthCheckCommandFields = ({
connectionId,
applicationId: applicationId ?? undefined,
syncId,
- certificateIds: syncId ? undefined : watch("certificateIds"),
+ filters: syncId ? undefined : ((watch("filters") ?? null) as TPkiSyncFilters | null),
destinationConfig: (destinationConfig ?? {}) as Record<string, unknown>,
syncOptions: { ...(watch("syncOptions") ?? {}), healthCheckCommand: command }
});
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable.tsx
new file mode 100644
index 0000000000..2e457a56f5
--- /dev/null
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable.tsx
@@ -0,0 +1,107 @@
+import { ScrollText } from "lucide-react";
+
+import {
+ Empty,
+ EmptyDescription,
+ EmptyMedia,
+ EmptyTitle,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { truncateCertificateSerialNumber } from "@app/helpers/pkiSyncs";
+
+export type TMatchedCertificateRow = {
+ id: string;
+ commonName: string;
+ serialNumber?: string | null;
+ notAfter?: string | null;
+ profileName?: string | null;
+};
+
+type Props = {
+ rows: TMatchedCertificateRow[];
+ isLoading: boolean;
+ emptyTitle: string;
+ emptyDescription: string;
+};
+
+export const PkiSyncMatchedCertificatesTable = ({
+ rows,
+ isLoading,
+ emptyTitle,
+ emptyDescription
+}: Props) => {
+ if (isLoading) {
+ return (
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-8 w-full" />
+ <Skeleton className="h-8 w-full" />
+ <Skeleton className="h-8 w-full" />
+ </div>
+ );
+ }
+
+ if (rows.length === 0) {
+ return (
+ <Empty className="border py-8">
+ <EmptyMedia variant="icon">
+ <ScrollText />
+ </EmptyMedia>
+ <EmptyTitle>{emptyTitle}</EmptyTitle>
+ <EmptyDescription>{emptyDescription}</EmptyDescription>
+ </Empty>
+ );
+ }
+
+ return (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Common Name</TableHead>
+ <TableHead className="w-1/5">Serial Number</TableHead>
+ <TableHead className="w-1/5">Profile</TableHead>
+ <TableHead className="w-1/6">Expires At</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map((row) => {
+ const isExpired = row.notAfter ? new Date(row.notAfter) < new Date() : false;
+
+ return (
+ <TableRow key={row.id}>
+ <TableCell className="max-w-0">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="truncate font-mono text-sm">{row.commonName}</div>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-lg">{row.commonName}</TooltipContent>
+ </Tooltip>
+ </TableCell>
+ <TableCell className="max-w-0">
+ <div className="font-mono text-xs" title={row.serialNumber ?? ""}>
+ {truncateCertificateSerialNumber(row.serialNumber ?? "")}
+ </div>
+ </TableCell>
+ <TableCell className="max-w-0">
+ <div className="truncate text-sm">{row.profileName ?? "-"}</div>
+ </TableCell>
+ <TableCell className="max-w-0">
+ <span className={isExpired ? "text-sm text-danger" : "text-sm"}>
+ {row.notAfter ? new Date(row.notAfter).toLocaleDateString() : "-"}
+ </span>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ );
+};
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx
index 9561e7400b..9e095c6a20 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx
@@ -63,12 +63,13 @@ export const PkiSyncOptionsFields = ({ destination, isUpdate }: Props) => {
<SyncSwitchField
name="syncOptions.canRemoveCertificates"
id="can-remove-certificates"
- label="Enable removal of expired/revoked certificates"
+ label="Allow to remove certificates from destination"
description={
<>
- When enabled, Infisical removes certificates from the destination during a sync once
- they are no longer active in Infisical. Disable this if you manage some certificates
- manually outside of Infisical.
+ 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&apos;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.tsx
index caeb3f6fba..c76a0f2ac6 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx
@@ -1,31 +1,23 @@
import { ReactNode } from "react";
import { useFormContext } from "react-hook-form";
+import { FilterIcon } from "lucide-react";
-import {
- Badge,
- CodeBlock,
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
- Tooltip,
- TooltipContent,
- TooltipTrigger
-} from "@app/components/v3";
+import { buildPkiSyncFilterSummary } from "@app/components/pki-syncs/PkiSyncFilterBadges";
+import { Badge, CodeBlock, Empty, EmptyDescription, EmptyMedia } from "@app/components/v3";
import { useProject } from "@app/context";
import {
BOOLEAN_SYNC_OPTION_FIELDS,
- getCertificateDisplayName,
KEY_VALUE_SYNC_OPTION_FIELDS,
PKI_SYNC_MAP,
- truncateCertificateSerialNumber,
VALUE_SYNC_OPTION_FIELDS
} from "@app/helpers/pkiSyncs";
-import { useListWorkspaceCertificates } from "@app/hooks/api/projects";
+import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";
+import { 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 { PkiSyncMatchedCertificatesTable } from "./PkiSyncMatchedCertificatesTable";
const ReviewFieldLabel = ({ label, children }: { label: string; children?: ReactNode }) => (
<div className="row-span-2 grid min-w-0 grid-rows-subgrid pb-2">
@@ -38,28 +30,25 @@ const ReviewFieldLabel = ({ label, children }: { label: string; children?: React
</div>
);
-export const PkiSyncReviewFields = () => {
+type Props = {
+ applicationId?: string;
+};
+
+export const PkiSyncReviewFields = ({ applicationId }: Props = {}) => {
const { watch } = useFormContext<TPkiSyncForm>();
const { currentProject } = useProject();
- const { data } = useListWorkspaceCertificates({
- projectId: currentProject?.id || "",
+ const { data: profileData } = useListCertificateProfiles({
+ limit: 100,
offset: 0,
- limit: 100
+ applicationId
});
- const certificates = data?.certificates || [];
-
- const getSelectedCertificates = (certificateIds?: string[]) => {
- if (!certificateIds || certificateIds.length === 0) return [];
- return certificates.filter((cert) => certificateIds.includes(cert.id));
- };
-
const {
name,
description,
connection,
- certificateIds,
+ filters,
syncOptions,
destination,
destinationConfig,
@@ -67,7 +56,24 @@ export const PkiSyncReviewFields = () => {
} = watch();
const destinationName = PKI_SYNC_MAP[destination].name;
- const selectedCertificates = getSelectedCertificates(certificateIds);
+
+ const { data: preview, isPending: isPreviewPending } = usePkiSyncPreviewCertificates({
+ projectId: currentProject?.id || "",
+ applicationId,
+ filters: (filters ?? null) as TPkiSyncFilters | null,
+ enabled: Boolean(applicationId) && hasAnyFilter(filters)
+ });
+
+ const orderNameById = buildOrderNameMap(preview?.certificates);
+
+ const matchedRows = hasAnyFilter(filters) ? (preview?.certificates ?? []) : [];
+ const filterFields = buildPkiSyncFilterSummary({
+ filters: (filters ?? null) as TPkiSyncFilters | null,
+ profileNameById: new Map(
+ (profileData?.certificateProfiles ?? []).map(({ id, slug }) => [id, slug])
+ ),
+ orderNameById
+ });
const postSyncCommand =
syncOptions && "postSyncCommand" in syncOptions ? syncOptions.postSyncCommand : undefined;
const healthCheckCommand =
@@ -80,60 +86,38 @@ export const PkiSyncReviewFields = () => {
<span className="text-sm text-muted">Certificates</span>
</div>
<div className="w-full">
- {selectedCertificates.length === 0 ? (
- <span className="text-sm text-muted/50 italic">No certificates selected</span>
+ <p className="mb-2 text-sm font-medium text-foreground">Filters</p>
+ {filterFields ? (
+ <div className="mb-4 grid grid-cols-3 gap-x-8">
+ {filterFields.map(({ label, value }) => (
+ <ReviewFieldLabel key={label} label={label}>
+ {value}
+ </ReviewFieldLabel>
+ ))}
+ </div>
) : (
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>SAN / CN</TableHead>
- <TableHead className="w-1/5">Serial Number</TableHead>
- <TableHead className="w-1/6">Issued At</TableHead>
- <TableHead className="w-1/6 pr-5">Expires At</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {selectedCertificates.map((cert) => {
- const { originalDisplayName, displayName, isTruncated } =
- getCertificateDisplayName(cert);
- const truncatedSerial = truncateCertificateSerialNumber(cert.serialNumber);
-
- return (
- <TableRow key={cert.id}>
- <TableCell className="max-w-0">
- {isTruncated ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <div className="truncate">{displayName}</div>
- </TooltipTrigger>
- <TooltipContent className="max-w-lg">
- {originalDisplayName}
- </TooltipContent>
- </Tooltip>
- ) : (
- <div className="truncate">{displayName}</div>
- )}
- </TableCell>
- <TableCell className="max-w-0">
- <div className="font-mono text-xs" title={cert.serialNumber}>
- {truncatedSerial}
- </div>
- </TableCell>
- <TableCell className="max-w-0">
- <span className="text-sm">
- {new Date(cert.notBefore).toLocaleDateString()}
- </span>
- </TableCell>
- <TableCell className="max-w-0 pr-5">
- <span className="text-sm">
- {new Date(cert.notAfter).toLocaleDateString()}
- </span>
- </TableCell>
- </TableRow>
- );
- })}
- </TableBody>
- </Table>
+ <Empty className="mb-4 border py-8">
+ <EmptyMedia variant="icon">
+ <FilterIcon />
+ </EmptyMedia>
+ <EmptyDescription>No filters, so this sync holds nothing.</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.`}
+ </p>
+ <PkiSyncMatchedCertificatesTable
+ rows={matchedRows}
+ isLoading={isPreviewPending}
+ emptyTitle="No certificates match"
+ emptyDescription="Nothing in this Application matches these filters yet."
+ />
+ </>
)}
</div>
</div>
diff --git a/frontend/src/components/pki-syncs/forms/index.ts b/frontend/src/components/pki-syncs/forms/index.ts
index 89810f60e2..74de354f85 100644
--- a/frontend/src/components/pki-syncs/forms/index.ts
+++ b/frontend/src/components/pki-syncs/forms/index.ts
@@ -1,5 +1,5 @@
export { CreatePkiSyncForm } from "./CreatePkiSyncForm";
-export { EditPkiSyncForm } from "./EditPkiSyncForm";
+export { EditPkiSyncForm, type TPkiSyncEditStepKey } from "./EditPkiSyncForm";
export { PkiSyncDestinationFields } from "./PkiSyncDestinationFields";
export { PkiSyncDetailsFields } from "./PkiSyncDetailsFields";
export { PkiSyncHealthCheckCommandFields } from "./PkiSyncHealthCheckCommandFields";
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.ts
new file mode 100644
index 0000000000..2ec21090c2
--- /dev/null
+++ b/frontend/src/components/pki-syncs/forms/pki-sync-filter-fns.ts
@@ -0,0 +1,93 @@
+import { TPkiSyncFilters } from "@app/hooks/api/pkiSyncs/types";
+
+export const FILTER_KINDS = ["certificateOrderIds", "profileIds", "metadata"] as const;
+
+export type TFilterKind = (typeof FILTER_KINDS)[number];
+
+export const FILTER_LABELS: Record<TFilterKind, string> = {
+ certificateOrderIds: "Certificate Order",
+ 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);
+
+export const presentFilterKinds = (filters: TPkiSyncFilters | null | undefined): TFilterKind[] =>
+ FILTER_KINDS.filter((kind) => isFilterPresent(filters, kind));
+
+const isFilterUnfinished = (filters: TPkiSyncFilters | null | undefined, kind: TFilterKind) => {
+ if (!isFilterPresent(filters, kind)) return false;
+ if (kind === "profileIds") return false;
+ if (kind === "metadata") return (filters?.metadata ?? []).some((pair) => !pair.key.trim());
+ return (filters?.[kind] ?? []).length === 0;
+};
+
+export const hasUnfinishedFilter = (filters: TPkiSyncFilters | null | undefined) =>
+ FILTER_KINDS.some((kind) => isFilterUnfinished(filters, kind));
+
+export const isCertificateOrderTheOnlyFilter = (filters: TPkiSyncFilters | null | undefined) =>
+ Boolean(filters) &&
+ FILTER_KINDS.every((kind) => kind === "certificateOrderIds" || !isFilterPresent(filters, kind));
+
+export const buildOrderNameMap = (
+ certificates: { orderId?: string; commonName: string }[] | undefined
+): Map<string, string> =>
+ new Map(
+ (certificates ?? [])
+ .filter((certificate) => certificate.orderId)
+ .map(({ orderId, commonName }) => [orderId as string, commonName])
+ );
+
+const GCP_MAX_CERTIFICATES_PER_MAP_ENTRY = 4;
+
+const NAME_SCHEMA_PLACEHOLDER_PATTERN =
+ /\{\{(certificateId|shortCertificateId|profileId|applicationId|applicationName|commonName)\}\}/;
+
+const COMMAND_VARIABLE_PATTERN = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g;
+
+const SINGLE_CERTIFICATE_COMMAND_VARIABLES = ["certificatePath", "commonName"];
+
+type TCapInputs = {
+ destinationMaxCertificates?: number;
+ syncOptions?: Record<string, unknown>;
+ destinationConfig?: Record<string, unknown>;
+};
+
+export const getPkiSyncCertificateCap = ({
+ destinationMaxCertificates,
+ syncOptions,
+ destinationConfig
+}: TCapInputs): number | undefined => {
+ const caps: number[] = [];
+
+ if (destinationMaxCertificates !== undefined) caps.push(destinationMaxCertificates);
+
+ const nameSchema = syncOptions?.certificateNameSchema as string | undefined;
+ if (!nameSchema || !NAME_SCHEMA_PLACEHOLDER_PATTERN.test(nameSchema)) caps.push(1);
+
+ const namesOneCertificate = (command: unknown) => {
+ if (typeof command !== "string") return false;
+
+ return [...command.matchAll(COMMAND_VARIABLE_PATTERN)].some(([, name]) =>
+ SINGLE_CERTIFICATE_COMMAND_VARIABLES.includes(name)
+ );
+ };
+
+ if (
+ namesOneCertificate(syncOptions?.healthCheckCommand) ||
+ namesOneCertificate(syncOptions?.postSyncCommand)
+ ) {
+ caps.push(1);
+ }
+
+ const certificateMapBinding = destinationConfig?.certificateMapBinding as
+ | { certificateMap?: string }
+ | undefined;
+ if (certificateMapBinding?.certificateMap) caps.push(GCP_MAX_CERTIFICATES_PER_MAP_ENTRY);
+
+ return caps.length ? Math.min(...caps) : undefined;
+};
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.ts
index e99a1472d7..d6c3bcba1a 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
@@ -101,7 +101,21 @@ export const BasePkiSyncSchema = <T extends AnyZodObject | undefined = undefined
description: z.string().optional(),
isAutoSyncEnabled: z.boolean().default(true),
subscriberId: z.string().nullable().optional(),
- certificateIds: z.array(z.string()).optional(),
+ filters: z
+ .object({
+ profileIds: z.array(z.string().uuid()).max(20).optional(),
+ certificateOrderIds: z.string().uuid().array().max(500).optional(),
+ metadata: z
+ .array(
+ z.object({
+ key: z.string().trim().min(1, "Enter a metadata key or remove the pair").max(255),
+ value: z.string().trim().max(1020).optional()
+ })
+ )
+ .max(20, "A filter can use at most 20 metadata pairs")
+ .optional()
+ })
+ .nullish(),
connection: PkiSyncConnectionSchema,
syncOptions: syncOptionsSchema
});
diff --git a/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts
index 325d7bd44b..cb1de60701 100644
--- a/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts
+++ b/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts
@@ -119,12 +119,12 @@ export const PkiSyncFormSchema = PkiSyncUnionSchema.superRefine((data, ctx) => {
if (
data.destination === PkiSync.GcpCertificateManager &&
data.destinationConfig?.certificateMapBinding &&
- (data.certificateIds?.length ?? 0) > GCP_MAX_CERTIFICATES_PER_MAP_ENTRY
+ (data.filters?.certificateOrderIds?.length ?? 0) > GCP_MAX_CERTIFICATES_PER_MAP_ENTRY
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["destinationConfig", "certificateMapBinding"],
- message: `Certificate map binding supports up to ${GCP_MAX_CERTIFICATES_PER_MAP_ENTRY} certificates, which is the GCP limit for one certificate map entry.`
+ message: `Certificate map binding supports up to ${GCP_MAX_CERTIFICATES_PER_MAP_ENTRY} certificate orders, which is the GCP limit for one certificate map entry.`
});
}
diff --git a/frontend/src/components/pki-syncs/index.ts b/frontend/src/components/pki-syncs/index.ts
index db70024633..20e7dd1ee1 100644
--- a/frontend/src/components/pki-syncs/index.ts
+++ b/frontend/src/components/pki-syncs/index.ts
@@ -1,6 +1,7 @@
export { CreatePkiSyncModal } from "./CreatePkiSyncModal";
export { DeletePkiSyncModal } from "./DeletePkiSyncModal";
export { EditPkiSyncModal } from "./EditPkiSyncModal";
+export type { TPkiSyncEditStepKey } from "./forms";
export { PkiSyncImportCertificatesModal } from "./PkiSyncImportCertificatesModal";
export { PkiSyncImportStatusBadge } from "./PkiSyncImportStatusBadge";
export { PkiSyncRemoveCertificatesModal } from "./PkiSyncRemoveCertificatesModal";
diff --git a/frontend/src/components/v3/generic/HoverCard/HoverCard.tsx b/frontend/src/components/v3/generic/HoverCard/HoverCard.tsx
index 0edb6d69d0..cecdfa0e89 100644
--- a/frontend/src/components/v3/generic/HoverCard/HoverCard.tsx
+++ b/frontend/src/components/v3/generic/HoverCard/HoverCard.tsx
@@ -16,10 +16,13 @@ function HoverCardContent({
align = "center",
sideOffset = 4,
collisionPadding = 8,
+ container,
...props
-}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
+}: React.ComponentProps<typeof HoverCardPrimitive.Content> & {
+ container?: React.ComponentProps<typeof HoverCardPrimitive.Portal>["container"];
+}) {
return (
- <HoverCardPrimitive.Portal data-slot="hover-card-portal">
+ <HoverCardPrimitive.Portal data-slot="hover-card-portal" container={container}>
<HoverCardPrimitive.Content
data-slot="hover-card-content"
align={align}
diff --git a/frontend/src/helpers/pkiSyncs.ts b/frontend/src/helpers/pkiSyncs.ts
index 65374a8627..76eb0be609 100644
--- a/frontend/src/helpers/pkiSyncs.ts
+++ b/frontend/src/helpers/pkiSyncs.ts
@@ -144,7 +144,7 @@ export const getPkiSyncConnectionApps = (destination: PkiSync): AppConnection[]
];
export const BOOLEAN_SYNC_OPTION_FIELDS = [
- { key: "canRemoveCertificates", label: "Remove Expired/Revoked Certificates" },
+ { key: "canRemoveCertificates", label: "Allow to remove certificates from destination" },
{ key: "canImportCertificates", label: "Import Certificates" },
{ key: "includeRootCa", label: "Include Root CA in Chain" },
{ key: "preserveArn", label: "Preserve ARN on Renewal" },
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index 70175ada10..90f0f83c86 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -188,6 +188,9 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.CREATE_PKI_SYNC]: "Create PKI sync",
[EventType.UPDATE_PKI_SYNC]: "Update PKI sync",
[EventType.DELETE_PKI_SYNC]: "Delete PKI sync",
+ [EventType.PKI_SYNC_LINK_CERTIFICATES]: "PKI Sync linked certificates",
+ [EventType.PKI_SYNC_UNLINK_CERTIFICATES]: "PKI Sync unlinked certificates",
+ [EventType.PKI_SYNC_SKIP_CERTIFICATE]: "PKI Sync skipped a certificate",
[EventType.PKI_SYNC_SYNC_CERTIFICATES]: "PKI Sync synced certificates",
[EventType.PKI_SYNC_IMPORT_CERTIFICATES]: "PKI Sync imported certificates",
[EventType.PKI_SYNC_REMOVE_CERTIFICATES]: "PKI Sync removed certificates",
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index c6aebbdce1..49205b85cb 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -198,6 +198,9 @@ export enum EventType {
CREATE_PKI_SYNC = "create-pki-sync",
UPDATE_PKI_SYNC = "update-pki-sync",
DELETE_PKI_SYNC = "delete-pki-sync",
+ PKI_SYNC_LINK_CERTIFICATES = "pki-sync-link-certificates",
+ PKI_SYNC_UNLINK_CERTIFICATES = "pki-sync-unlink-certificates",
+ PKI_SYNC_SKIP_CERTIFICATE = "pki-sync-skip-certificate",
PKI_SYNC_SYNC_CERTIFICATES = "pki-sync-sync-certificates",
PKI_SYNC_IMPORT_CERTIFICATES = "pki-sync-import-certificates",
PKI_SYNC_REMOVE_CERTIFICATES = "pki-sync-remove-certificates",
diff --git a/frontend/src/hooks/api/certificates/types.ts b/frontend/src/hooks/api/certificates/types.ts
index 09b3a4f132..4d7162aa86 100644
--- a/frontend/src/hooks/api/certificates/types.ts
+++ b/frontend/src/hooks/api/certificates/types.ts
@@ -39,6 +39,7 @@ export type TCertificate = {
subjectAltNames: string;
altNames?: string;
serialNumber: string;
+ orderId?: string;
notBefore: string;
notAfter: string;
keyUsages: CertKeyUsage[];
diff --git a/frontend/src/hooks/api/pkiSyncs/mutations.tsx b/frontend/src/hooks/api/pkiSyncs/mutations.tsx
index 5fd8890f35..6399488350 100644
--- a/frontend/src/hooks/api/pkiSyncs/mutations.tsx
+++ b/frontend/src/hooks/api/pkiSyncs/mutations.tsx
@@ -7,6 +7,8 @@ import {
TCreatePkiSyncDTO,
TDeletePkiSyncDTO,
TPkiSync,
+ TPkiSyncFilterPreview,
+ TPkiSyncFilters,
TPkiSyncHealthCheckResult,
TTriggerPkiSyncImportCertificatesDTO,
TTriggerPkiSyncRemoveCertificatesDTO,
@@ -59,6 +61,7 @@ export const useUpdatePkiSync = () => {
onSuccess: (_, { syncId, projectId }) => {
queryClient.invalidateQueries({ queryKey: pkiSyncKeys.list(projectId) });
queryClient.invalidateQueries({ queryKey: pkiSyncKeys.byId(syncId, projectId) });
+ queryClient.invalidateQueries({ queryKey: pkiSyncKeys.certificates(syncId) });
}
});
};
@@ -92,6 +95,7 @@ export const useTestPkiSyncHealthCheck = () => {
applicationId,
syncId,
certificateIds,
+ filters,
destinationConfig,
syncOptions
}: {
@@ -100,12 +104,21 @@ export const useTestPkiSyncHealthCheck = () => {
applicationId?: string;
syncId?: string;
certificateIds?: string[];
+ filters?: TPkiSyncFilters | null;
destinationConfig: Record<string, unknown>;
syncOptions: Record<string, unknown>;
}) => {
const { data } = await apiRequest.post<{ healthCheck: TPkiSyncHealthCheckResult }>(
`/api/v1/cert-manager/syncs/${destination}/test-health-check`,
- { connectionId, applicationId, syncId, certificateIds, destinationConfig, syncOptions }
+ {
+ connectionId,
+ applicationId,
+ syncId,
+ certificateIds,
+ filters,
+ destinationConfig,
+ syncOptions
+ }
);
return data.healthCheck;
@@ -289,6 +302,25 @@ export const useTriggerPkiSyncRemoveCertificates = () => {
});
};
+export const usePreviewPkiSyncFilters = () => {
+ return useMutation({
+ mutationFn: async ({
+ pkiSyncId,
+ filters
+ }: {
+ pkiSyncId: string;
+ filters?: TPkiSyncFilters | null;
+ }) => {
+ const { data } = await apiRequest.post<TPkiSyncFilterPreview>(
+ "/api/v1/cert-manager/syncs/certificates/preview",
+ { pkiSyncId, filters: filters ?? null }
+ );
+
+ return data;
+ }
+ });
+};
+
export const useAddCertificatesToPkiSync = () => {
const queryClient = useQueryClient();
return useMutation({
diff --git a/frontend/src/hooks/api/pkiSyncs/queries.tsx b/frontend/src/hooks/api/pkiSyncs/queries.tsx
index b1435be7e5..c83471b405 100644
--- a/frontend/src/hooks/api/pkiSyncs/queries.tsx
+++ b/frontend/src/hooks/api/pkiSyncs/queries.tsx
@@ -9,7 +9,9 @@ import {
TListPkiSyncOptions,
TListPkiSyncs,
TPkiSync,
- TPkiSyncCertificate
+ TPkiSyncCertificate,
+ TPkiSyncFilterPreview,
+ TPkiSyncFilters
} from "@app/hooks/api/pkiSyncs/types";
import { PkiSyncStatus } from "./enums";
@@ -34,7 +36,59 @@ export const pkiSyncKeys = {
awsListeners: (connectionId: string, region: string, loadBalancerArn: string) =>
[...pkiSyncKeys.all, "aws-listeners", connectionId, region, loadBalancerArn] as const,
kempVirtualServices: (connectionId: string) =>
- [...pkiSyncKeys.all, "kemp-virtual-services", connectionId] as const
+ [...pkiSyncKeys.all, "kemp-virtual-services", connectionId] as const,
+ matchingCertificateIds: (
+ projectId: string,
+ applicationId: string,
+ filters?: TPkiSyncFilters | null
+ ) =>
+ [
+ ...pkiSyncKeys.all,
+ "matching-certificate-ids",
+ projectId,
+ applicationId,
+ filters ?? null
+ ] as const
+};
+
+export const usePkiSyncPreviewCertificates = ({
+ projectId,
+ applicationId,
+ pkiSyncId,
+ filters,
+ enabled = false
+}: {
+ projectId: string;
+ applicationId?: string | null;
+ pkiSyncId?: string | null;
+ filters?: TPkiSyncFilters | null;
+ enabled?: boolean;
+}) => {
+ return useQuery({
+ queryKey: pkiSyncKeys.matchingCertificateIds(
+ projectId,
+ pkiSyncId ?? applicationId ?? "",
+ filters
+ ),
+ enabled,
+ staleTime: Infinity,
+ queryFn: async () => {
+ const { data } = await apiRequest.post<TPkiSyncFilterPreview>(
+ "/api/v1/cert-manager/syncs/certificates/preview",
+ pkiSyncId
+ ? { pkiSyncId, filters: filters ?? null }
+ : { applicationId, filters: filters ?? null }
+ );
+
+ return {
+ certificates: data.certificates,
+ totalCount: data.matchedCount,
+ hasMoreMatches: data.hasMoreMatches,
+ toUnlink: data.toUnlink,
+ willRemoveFromDestination: data.willRemoveFromDestination
+ };
+ }
+ });
};
export const usePkiSyncOptions = (
diff --git a/frontend/src/hooks/api/pkiSyncs/types/common.ts b/frontend/src/hooks/api/pkiSyncs/types/common.ts
index 05838b972a..bc2e43d500 100644
--- a/frontend/src/hooks/api/pkiSyncs/types/common.ts
+++ b/frontend/src/hooks/api/pkiSyncs/types/common.ts
@@ -23,6 +23,12 @@ export type RootPkiSyncOptions = {
postSyncCommand?: string | null;
};
+export type TPkiSyncFilters = {
+ profileIds?: string[];
+ certificateOrderIds?: string[];
+ metadata?: { key: string; value?: string }[];
+};
+
export type TRootPkiSync = {
id: string;
name: string;
@@ -62,6 +68,7 @@ export type TRootPkiSync = {
appConnectionName?: string;
appConnectionApp?: string;
hasCertificate?: boolean;
+ filters?: TPkiSyncFilters | null;
};
export type TPkiSyncCertificate = {
@@ -75,6 +82,7 @@ export type TPkiSyncCertificate = {
updatedAt: string;
certificateSerialNumber?: string;
certificateCommonName?: string;
+ certificateOrderId?: string;
certificateAltNames?: string;
certificateStatus?: string;
certificateNotBefore?: Date;
@@ -99,3 +107,20 @@ export type TPkiSyncHealthCheckResult = {
failureDetail?: string;
message?: string;
};
+
+export type TPkiSyncPreviewCertificate = {
+ id: string;
+ commonName: string;
+ serialNumber?: string;
+ notAfter?: string;
+ orderId?: string;
+ profileName?: string | null;
+};
+
+export type TPkiSyncFilterPreview = {
+ matchedCount: number;
+ hasMoreMatches: boolean;
+ certificates: TPkiSyncPreviewCertificate[];
+ toUnlink: { id: string; commonName: string }[];
+ willRemoveFromDestination: boolean;
+};
diff --git a/frontend/src/hooks/api/pkiSyncs/types/index.ts b/frontend/src/hooks/api/pkiSyncs/types/index.ts
index 118afb598a..94a7b72e84 100644
--- a/frontend/src/hooks/api/pkiSyncs/types/index.ts
+++ b/frontend/src/hooks/api/pkiSyncs/types/index.ts
@@ -6,6 +6,7 @@ import { TAwsSecretsManagerPkiSync } from "./aws-secrets-manager-sync";
import { TAzureKeyVaultPkiSync } from "./azure-key-vault-sync";
import { TChefPkiSync } from "./chef-sync";
import { TCloudflareCustomCertificatePkiSync } from "./cloudflare-custom-certificate-sync";
+import { TPkiSyncFilters } from "./common";
import { TF5BigIpPkiSync } from "./f5-big-ip-sync";
import {
GcpCertificateManagerScope,
@@ -84,7 +85,7 @@ type TCreatePkiSyncDTOBase = {
};
isAutoSyncEnabled: boolean;
subscriberId?: string | null;
- certificateIds?: string[];
+ filters?: TPkiSyncFilters | null;
projectId: string;
applicationId?: string;
};
@@ -122,7 +123,7 @@ export type TCreatePkiSyncDTO = TCreatePkiSyncDTOBase & {
};
};
-export type TUpdatePkiSyncDTO = Partial<Omit<TCreatePkiSyncDTO, "projectId" | "certificateIds">> & {
+export type TUpdatePkiSyncDTO = Partial<Omit<TCreatePkiSyncDTO, "projectId">> & {
syncId: string;
projectId: string;
};
diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsx
index a7547984ac..5ddc4ef131 100644
--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsx
@@ -114,6 +114,19 @@ export const CertificateOverviewSection = ({ certificateId }: Props) => {
<CopyButton value={certificate.id} size="xs" variant="plain" />
</DetailValue>
</Detail>
+ <Detail>
+ <DetailLabel>Order ID</DetailLabel>
+ <DetailValue className="flex items-center gap-2 font-mono text-xs">
+ {certificate.orderId ? (
+ <>
+ {certificate.orderId}
+ <CopyButton value={certificate.orderId} size="xs" variant="plain" />
+ </>
+ ) : (
+ <span className="text-muted">—</span>
+ )}
+ </DetailValue>
+ </Detail>
<Detail>
<DetailLabel>Status</DetailLabel>
<DetailValue>
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx
index 4b9ba0fe92..b8c7b9adff 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx
@@ -3,6 +3,7 @@ import { faPlus, faSearch } from "@fortawesome/free-solid-svg-icons";
import { useNavigate } from "@tanstack/react-router";
import { createNotification } from "@app/components/notifications";
+import { isCertificateOrderTheOnlyFilter } from "@app/components/pki-syncs/forms/pki-sync-filter-fns";
import {
Button,
Checkbox,
@@ -240,34 +241,50 @@ export const CertificateManagePkiSyncsModal = ({
</Tr>
</THead>
<TBody>
- {paginatedSyncs.map((sync) => (
- <Tr
- key={sync.id}
- className="cursor-pointer hover:bg-mineshaft-700"
- onClick={() => handleSyncToggle(sync.id)}
- >
- <Td>
- <Checkbox
- isChecked={selectedSyncIds.has(sync.id)}
- onCheckedChange={() => handleSyncToggle(sync.id)}
- id={`sync-${sync.id}`}
- />
- </Td>
- <Td className="w-1/2 max-w-0">
- <div className="truncate" title={sync.name}>
- {sync.name}
- </div>
- </Td>
- <Td className="w-1/2 max-w-0">
- <div
- className="truncate capitalize"
- title={PKI_SYNC_MAP[sync.destination].name}
- >
- {PKI_SYNC_MAP[sync.destination].name}
- </div>
- </Td>
- </Tr>
- ))}
+ {paginatedSyncs.map((sync) => {
+ const managesItsOwnCertificates = !isCertificateOrderTheOnlyFilter(
+ sync.filters
+ );
+
+ return (
+ <Tr
+ key={sync.id}
+ className={
+ managesItsOwnCertificates
+ ? "opacity-60"
+ : "cursor-pointer hover:bg-mineshaft-700"
+ }
+ onClick={() => !managesItsOwnCertificates && handleSyncToggle(sync.id)}
+ >
+ <Td>
+ <Checkbox
+ isChecked={selectedSyncIds.has(sync.id)}
+ isDisabled={managesItsOwnCertificates}
+ onCheckedChange={() => handleSyncToggle(sync.id)}
+ id={`sync-${sync.id}`}
+ />
+ </Td>
+ <Td className="w-1/2 max-w-0">
+ <div className="truncate" title={sync.name}>
+ {sync.name}
+ </div>
+ {managesItsOwnCertificates && (
+ <div className="truncate text-xs text-mineshaft-400">
+ Selects certificates by filter
+ </div>
+ )}
+ </Td>
+ <Td className="w-1/2 max-w-0">
+ <div
+ className="truncate capitalize"
+ title={PKI_SYNC_MAP[sync.destination].name}
+ >
+ {PKI_SYNC_MAP[sync.destination].name}
+ </div>
+ </Td>
+ </Tr>
+ );
+ })}
</TBody>
</Table>
</TableContainer>
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx
index 9100859819..8f541a4df5 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx
@@ -1,3 +1,4 @@
+import { useState } from "react";
import { Helmet } from "react-helmet";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { BanIcon, ChevronLeftIcon } from "lucide-react";
@@ -5,7 +6,8 @@ import { BanIcon, ChevronLeftIcon } from "lucide-react";
import {
EditPkiSyncModal,
PkiSyncImportStatusBadge,
- PkiSyncRemoveStatusBadge
+ PkiSyncRemoveStatusBadge,
+ TPkiSyncEditStepKey
} from "@app/components/pki-syncs";
import {
Card,
@@ -48,6 +50,7 @@ const PageContent = () => {
});
const { handlePopUpToggle, popUp, handlePopUpOpen } = usePopUp(["editSync"] as const);
+ const [editStepKey, setEditStepKey] = useState<TPkiSyncEditStepKey | undefined>(undefined);
const { data: pkiSync, isPending } = useGetPkiSync(
{ syncId, projectId },
@@ -93,7 +96,14 @@ const PageContent = () => {
});
};
- const handleEdit = () => handlePopUpOpen("editSync");
+ const handleEdit = () => {
+ setEditStepKey(undefined);
+ handlePopUpOpen("editSync");
+ };
+ const handleEditCertificates = () => {
+ setEditStepKey("certificates");
+ handlePopUpOpen("editSync");
+ };
return (
<>
@@ -145,7 +155,10 @@ const PageContent = () => {
</Card>
</div>
<div className="flex flex-1 flex-col gap-4">
- <PkiSyncCertificatesSection pkiSync={pkiSync} />
+ <PkiSyncCertificatesSection
+ pkiSync={pkiSync}
+ onEditCertificates={handleEditCertificates}
+ />
<PkiSyncAuditLogsSection pkiSync={pkiSync} />
</div>
</div>
@@ -155,6 +168,7 @@ const PageContent = () => {
isOpen={popUp.editSync.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("editSync", isOpen)}
pkiSync={pkiSync}
+ initialStepKey={editStepKey}
/>
</>
);
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCertificatesSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCertificatesSection.tsx
index f949f9259f..7fdea644ca 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCertificatesSection.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCertificatesSection.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useMemo, useState } from "react";
import {
CheckCircle2Icon,
CircleHelpIcon,
@@ -12,7 +12,8 @@ import {
} from "lucide-react";
import { createNotification } from "@app/components/notifications";
-import { CertificateManagementModal } from "@app/components/pki-syncs/CertificateManagementModal";
+import { isCertificateOrderTheOnlyFilter } 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 {
Badge,
@@ -48,6 +49,7 @@ import {
useRemoveCertificatesFromPkiSync,
useSetCertificateAsDefault
} from "@app/hooks/api";
+import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";
import {
CertificateSyncStatus,
PkiSync,
@@ -56,6 +58,7 @@ import {
} from "@app/hooks/api/pkiSyncs";
type Props = {
+ onEditCertificates: () => void;
pkiSync: TPkiSync;
};
@@ -97,8 +100,7 @@ const truncateSerialNumber = (serial?: string | null) => {
return `${serial.substring(0, 4)}...${serial.substring(serial.length - 4)}`;
};
-export const PkiSyncCertificatesSection = ({ pkiSync }: Props) => {
- const [isManageModalOpen, setIsManageModalOpen] = useState(false);
+export const PkiSyncCertificatesSection = ({ pkiSync, onEditCertificates }: Props) => {
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const [certificateToDelete, setCertificateToDelete] = useState<{
id: string;
@@ -119,7 +121,53 @@ export const PkiSyncCertificatesSection = ({ pkiSync }: Props) => {
const supportsDefaultCertificate = pkiSync.destination === PkiSync.AwsElasticLoadBalancer;
- const { canEdit } = usePkiSyncPermissions(pkiSync);
+ const { canEdit: hasEditPermission } = usePkiSyncPermissions(pkiSync);
+ const canEdit = hasEditPermission && Boolean(pkiSync.applicationId);
+
+ const { data: profileData } = useListCertificateProfiles({
+ limit: 100,
+ offset: 0,
+ applicationId: 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 orderId = orderIdByCertificateId.get(certificateId);
+ return Boolean(orderId && explicitOrderIds.has(orderId));
+ };
+
+ const filterFields = useMemo(
+ () =>
+ buildPkiSyncFilterSummary({
+ filters: pkiSync.filters,
+ profileNameById: new Map(
+ (profileData?.certificateProfiles ?? []).map(({ id, slug }) => [id, slug])
+ ),
+ orderNameById
+ }),
+ [pkiSync.filters, profileData, orderNameById]
+ );
const handleRemoveCertificate = async (certificateId: string) => {
try {
@@ -138,10 +186,8 @@ export const PkiSyncCertificatesSection = ({ pkiSync }: Props) => {
setIsDeleteModalOpen(false);
setCertificateToDelete(null);
} catch {
- createNotification({
- text: "Failed to remove certificate from sync",
- type: "error"
- });
+ setIsDeleteModalOpen(false);
+ setCertificateToDelete(null);
}
};
@@ -202,15 +248,32 @@ export const PkiSyncCertificatesSection = ({ pkiSync }: Props) => {
<IconButton
variant="ghost"
size="xs"
- aria-label="Manage certificates"
+ aria-label="Manage certificates and filters"
isDisabled={!canEdit}
- onClick={() => setIsManageModalOpen(true)}
+ 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">
@@ -385,15 +448,22 @@ export const PkiSyncCertificatesSection = ({ pkiSync }: Props) => {
Unset Default
</DropdownMenuItem>
)}
- <DropdownMenuItem
- variant="danger"
- onClick={() =>
- handleDeleteClick(syncCert.certificateId, originalDisplayName)
- }
- >
- <Trash2Icon />
- Remove from Sync
- </DropdownMenuItem>
+ {isExplicitlyNamed(syncCert.certificateId) ? (
+ <DropdownMenuItem
+ variant="danger"
+ onClick={() =>
+ handleDeleteClick(syncCert.certificateId, originalDisplayName)
+ }
+ >
+ <Trash2Icon />
+ Remove from Sync
+ </DropdownMenuItem>
+ ) : (
+ <DropdownMenuItem onClick={onEditCertificates}>
+ <Trash2Icon />
+ Edit Filters to Remove
+ </DropdownMenuItem>
+ )}
</DropdownMenuContent>
</DropdownMenu>
</div>
@@ -418,15 +488,6 @@ export const PkiSyncCertificatesSection = ({ pkiSync }: Props) => {
</CardContent>
</Card>
- <CertificateManagementModal
- pkiSync={pkiSync}
- isOpen={isManageModalOpen}
- onClose={() => setIsManageModalOpen(false)}
- onCertificatesUpdated={() => {
- refetchSyncCertificates();
- }}
- />
-
<DeleteConfirmDialog
isOpen={isDeleteModalOpen}
onOpenChange={(isOpen) => {