Skip to content

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

fix(pki-syncs): match one certificate per order and guard profile detach

Carlos Monastyrski013155bc35eb
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 6bd8c0c4c1..30dea98d39 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -48,7 +48,6 @@ 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,
@@ -4709,7 +4708,6 @@ interface PkiSyncLinkCertificatesEvent {
name: string;
count: number;
certificates: { id: string; commonName: string }[];
- filters?: TPkiSyncFilters;
applicationId?: string;
applicationName?: string;
};
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 59bb05504e..0b2567f32b 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -53,6 +53,7 @@ import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types
import {
TQueuePkiSyncImportCertificatesByIdDTO,
TQueuePkiSyncLinkMatchingCertificatesDTO,
+ TQueuePkiSyncReconcileFiltersDTO,
TQueuePkiSyncRemoveCertificatesByIdDTO,
TQueuePkiSyncRunHealthCheckByIdDTO,
TQueuePkiSyncSyncCertificatesByIdDTO
@@ -164,6 +165,7 @@ export enum QueueJobs {
SecretSyncSendActionFailedNotifications = "secret-sync-send-action-failed-notifications",
PkiSyncSyncCertificates = "pki-sync-sync-certificates",
PkiSyncLinkMatchingCertificates = "pki-sync-link-matching-certificates",
+ PkiSyncReconcileFilters = "pki-sync-reconcile-filters",
PkiSyncImportCertificates = "pki-sync-import-certificates",
PkiSyncRemoveCertificates = "pki-sync-remove-certificates",
PkiSyncRunHealthCheck = "pki-sync-run-health-check",
@@ -375,6 +377,10 @@ export type TQueueJobTypes = {
| {
name: QueueJobs.PkiSyncLinkMatchingCertificates;
payload: TQueuePkiSyncLinkMatchingCertificatesDTO;
+ }
+ | {
+ name: QueueJobs.PkiSyncReconcileFilters;
+ payload: TQueuePkiSyncReconcileFiltersDTO;
};
[QueueName.PkiSyncHealthCheck]: {
name: QueueJobs.PkiSyncRunHealthCheck;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index c897141ea5..bbdf0b7f76 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1772,6 +1772,7 @@ export const registerRoutes = async (
membershipRoleDAL,
approvalPolicyDAL,
approvalRequestDAL,
+ pkiSyncDAL,
permissionService
});
@@ -3386,7 +3387,6 @@ export const registerRoutes = async (
const pkiSyncCleanup = pkiSyncCleanupQueueServiceFactory({
cronJob,
pkiSyncDAL,
- certificateSyncDAL,
pkiSyncQueue
});
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 b4188e0abd..960549db6c 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
@@ -15,6 +15,7 @@ import { PkiSyncFiltersField, PkiSyncStoredFiltersField } from "@app/services/pk
const PkiSyncCertificateRefSchema = z.object({
id: z.string().uuid(),
commonName: z.string(),
+ altNames: z.string().nullable().optional(),
serialNumber: z.string().optional(),
notAfter: z.date().optional(),
orderId: z.string().uuid().optional(),
diff --git a/backend/src/services/certificate-sync/certificate-sync-dal.ts b/backend/src/services/certificate-sync/certificate-sync-dal.ts
index bbf185002f..9512f05681 100644
--- a/backend/src/services/certificate-sync/certificate-sync-dal.ts
+++ b/backend/src/services/certificate-sync/certificate-sync-dal.ts
@@ -4,7 +4,6 @@ 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";
@@ -49,35 +48,6 @@ export const certificateSyncDALFactory = (db: TDbClient) => {
}
};
- const findIneligibleFilteredLinks = async (
- limit: number,
- offset = 0
- ): 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)
- .offset(offset)) 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)
@@ -355,7 +325,6 @@ export const certificateSyncDALFactory = (db: TDbClient) => {
findByCertificateId,
findByPkiSyncAndCertificate,
findCertificateIdsByPkiSyncId,
- findIneligibleFilteredLinks,
findPkiSyncIdsByCertificateId,
findExternalIdentifiersInUse,
addCertificates,
diff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.ts
index 1b60066ce2..a0c1f7b2e7 100644
--- a/backend/src/services/certificate/certificate-dal.ts
+++ b/backend/src/services/certificate/certificate-dal.ts
@@ -145,6 +145,7 @@ export const certificateDALFactory = (db: TDbClient) => {
type TMatchedSyncCertificate = {
id: string;
commonName: string;
+ altNames?: string | null;
serialNumber: string;
notAfter: Date;
orderId: string;
@@ -523,6 +524,7 @@ export const certificateDALFactory = (db: TDbClient) => {
): Promise<TMatchedSyncCertificate[]> => {
try {
let query = db(TableName.Certificate)
+ .distinctOn(`${TableName.Certificate}.orderId`)
.leftJoin(
TableName.PkiCertificateProfile,
`${TableName.Certificate}.profileId`,
@@ -555,16 +557,24 @@ export const certificateDALFactory = (db: TDbClient) => {
query = query.limit(options.limit);
}
- return (await query
- .orderBy(`${TableName.Certificate}.commonName`, "asc")
+ const certificates = (await query
+ .orderBy([
+ { column: `${TableName.Certificate}.orderId` },
+ { column: `${TableName.Certificate}.notBefore`, order: "desc" }
+ ])
.select(
`${TableName.Certificate}.id`,
`${TableName.Certificate}.commonName`,
+ `${TableName.Certificate}.altNames`,
`${TableName.Certificate}.serialNumber`,
`${TableName.Certificate}.notAfter`,
`${TableName.Certificate}.orderId`,
db.ref("slug").withSchema(TableName.PkiCertificateProfile).as("profileName")
)) as TMatchedSyncCertificate[];
+
+ return certificates.sort((a, b) =>
+ (a.altNames?.trim() || a.commonName).localeCompare(b.altNames?.trim() || b.commonName)
+ );
} catch (error) {
throw new DatabaseError({ error, name: "Find certificates matching sync filters" });
}
diff --git a/backend/src/services/pki-application/pki-application-service.ts b/backend/src/services/pki-application/pki-application-service.ts
index 02444df3d3..a52f3d5aca 100644
--- a/backend/src/services/pki-application/pki-application-service.ts
+++ b/backend/src/services/pki-application/pki-application-service.ts
@@ -26,6 +26,8 @@ import { TApprovalRequestDALFactory } from "../approval-policy/approval-request-
import { ActorType } from "../auth/auth-type";
import { TMembershipDALFactory } from "../membership/membership-dal";
import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";
+import { TPkiSyncDALFactory } from "../pki-sync/pki-sync-dal";
+import { TPkiSyncFilters } from "../pki-sync/pki-sync-types";
import { TPkiApplicationDALFactory } from "./pki-application-dal";
import { TPkiApplicationProfileDALFactory } from "./pki-application-profile-dal";
import {
@@ -60,6 +62,7 @@ type TPkiApplicationServiceFactoryDep = {
membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create" | "delete">;
approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "delete">;
approvalRequestDAL: Pick<TApprovalRequestDALFactory, "delete">;
+ pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
};
@@ -72,6 +75,7 @@ export const pkiApplicationServiceFactory = ({
membershipRoleDAL,
approvalPolicyDAL,
approvalRequestDAL,
+ pkiSyncDAL,
permissionService
}: TPkiApplicationServiceFactoryDep) => {
const $loadProjectPermission = (
@@ -537,6 +541,25 @@ export const pkiApplicationServiceFactory = ({
subject(ProjectPermissionSub.CertificateProfiles, { slug: profile.slug })
);
+ const pkiSyncs = await pkiSyncDAL.find({ applicationId });
+ const syncsFilteringOnProfile = pkiSyncs.filter((pkiSync) =>
+ ((pkiSync.filters as TPkiSyncFilters | null)?.profileIds ?? []).includes(profileId)
+ );
+
+ if (syncsFilteringOnProfile.length > 0) {
+ const names = syncsFilteringOnProfile.map(({ name }) => name).sort();
+ const preview = names.slice(0, 5).join(", ");
+ const remaining = names.length - 5;
+ const isSingular = names.length === 1;
+ throw new BadRequestError({
+ message: `Cannot detach this certificate profile while ${names.length} certificate sync${
+ isSingular ? " selects" : "s select"
+ } certificates by it (${
+ remaining > 0 ? `${preview}, and ${remaining} more` : preview
+ }). Remove the certificate profile filter from ${isSingular ? "that sync" : "those syncs"} first.`
+ });
+ }
+
await pkiApplicationProfileDAL.delete({ applicationId, profileId });
return { applicationId, profileId };
};
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 20e484e5b1..76117bb24c 100644
--- a/backend/src/services/pki-sync/pki-sync-cleanup-queue.ts
+++ b/backend/src/services/pki-sync/pki-sync-cleanup-queue.ts
@@ -2,18 +2,16 @@ 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;
-const INELIGIBLE_LINK_MAX_BATCHES_PER_RUN = 10;
+const FILTERED_SYNC_BATCH = 500;
+const FILTERED_SYNC_MAX_BATCHES_PER_RUN = 20;
type TPkiSyncCleanupQueueServiceFactoryDep = {
cronJob: TCronJobFactory;
- pkiSyncDAL: Pick<TPkiSyncDALFactory, "findPkiSyncsWithExpiredCertificates">;
- certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findIneligibleFilteredLinks">;
- pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById" | "queuePkiSyncLinkMatchingCertificates">;
+ pkiSyncDAL: Pick<TPkiSyncDALFactory, "findPkiSyncsWithExpiredCertificates" | "findFilteredSyncIds">;
+ pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById" | "queuePkiSyncReconcileFilters">;
};
export type TPkiSyncCleanupQueueServiceFactory = ReturnType<typeof pkiSyncCleanupQueueServiceFactory>;
@@ -21,7 +19,6 @@ export type TPkiSyncCleanupQueueServiceFactory = ReturnType<typeof pkiSyncCleanu
export const pkiSyncCleanupQueueServiceFactory = ({
cronJob,
pkiSyncDAL,
- certificateSyncDAL,
pkiSyncQueue
}: TPkiSyncCleanupQueueServiceFactoryDep) => {
const appCfg = getConfig();
@@ -59,37 +56,35 @@ export const pkiSyncCleanupQueueServiceFactory = ({
}
};
- const reconcileIneligibleFilteredLinks = async () => {
+ const reconcileFilteredSyncs = async () => {
try {
let queued = 0;
+ let afterId: string | undefined;
- for (let page = 0; page < INELIGIBLE_LINK_MAX_BATCHES_PER_RUN; page += 1) {
+ for (let batch = 0; batch < FILTERED_SYNC_MAX_BATCHES_PER_RUN; batch += 1) {
// eslint-disable-next-line no-await-in-loop
- const stale = await certificateSyncDAL.findIneligibleFilteredLinks(
- INELIGIBLE_LINK_BATCH,
- page * INELIGIBLE_LINK_BATCH
- );
+ const syncIds = await pkiSyncDAL.findFilteredSyncIds(FILTERED_SYNC_BATCH, afterId);
+ if (syncIds.length === 0) break;
- if (stale.length === 0) break;
-
- for (const { certificateId, applicationId } of stale) {
+ for (const syncId of syncIds) {
try {
// eslint-disable-next-line no-await-in-loop
- await pkiSyncQueue.queuePkiSyncLinkMatchingCertificates({ certificateId, applicationId });
+ await pkiSyncQueue.queuePkiSyncReconcileFilters({ syncId });
queued += 1;
} catch (error) {
- logger.error(error, `Failed to queue a filter reconcile [certificateId=${certificateId}]`);
+ logger.error(error, `Failed to queue a filter reconcile [pkiSyncId=${syncId}]`);
}
}
- if (stale.length < INELIGIBLE_LINK_BATCH) break;
+ afterId = syncIds[syncIds.length - 1];
+ if (syncIds.length < FILTERED_SYNC_BATCH) break;
}
if (queued === 0) return;
- logger.info(`cron[pki-sync-cleanup]: re-evaluating ${queued} certificate(s) held by a filtered sync`);
+ logger.info(`cron[pki-sync-cleanup]: re-evaluating the certificates held by ${queued} filtered sync(s)`);
} catch (error) {
- logger.error(error, "Failed to re-evaluate certificates held by a filtered sync");
+ logger.error(error, "Failed to re-evaluate the certificates held by filtered syncs");
}
};
@@ -104,7 +99,7 @@ export const pkiSyncCleanupQueueServiceFactory = ({
const [expiredCertificateSweep] = await Promise.allSettled([
syncExpiredCertificatesForPkiSyncs(),
- reconcileIneligibleFilteredLinks()
+ reconcileFilteredSyncs()
]);
if (expiredCertificateSweep.status === "rejected") throw expiredCertificateSweep.reason;
@@ -115,6 +110,6 @@ export const pkiSyncCleanupQueueServiceFactory = ({
return {
init,
syncExpiredCertificatesForPkiSyncs,
- reconcileIneligibleFilteredLinks
+ reconcileFilteredSyncs
};
};
diff --git a/backend/src/services/pki-sync/pki-sync-dal.ts b/backend/src/services/pki-sync/pki-sync-dal.ts
index 0f920b9368..9903f45d9e 100644
--- a/backend/src/services/pki-sync/pki-sync-dal.ts
+++ b/backend/src/services/pki-sync/pki-sync-dal.ts
@@ -304,6 +304,26 @@ export const pkiSyncDALFactory = (db: TDbClient) => {
return expandPkiSync(pkiSync);
};
+ const findFilteredSyncIds = async (limit: number, afterId?: string): Promise<string[]> => {
+ try {
+ let query = db
+ .replicaNode()(TableName.PkiSync)
+ .whereNotNull(`${TableName.PkiSync}.applicationId`)
+ .whereNotNull(`${TableName.PkiSync}.filters`);
+
+ if (afterId) query = query.where(`${TableName.PkiSync}.id`, ">", afterId);
+
+ const rows = (await query
+ .select(`${TableName.PkiSync}.id`)
+ .orderBy(`${TableName.PkiSync}.id`, "asc")
+ .limit(limit)) as Array<{ id: string }>;
+
+ return rows.map(({ id }) => id);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find filtered PKI sync ids" });
+ }
+ };
+
const findPkiSyncsWithExpiredCertificates = async (): Promise<Array<{ id: string; subscriberId: string }>> => {
try {
const yesterday = new Date();
@@ -438,6 +458,7 @@ export const pkiSyncDALFactory = (db: TDbClient) => {
find,
create,
updateById,
+ findFilteredSyncIds,
findPkiSyncsWithExpiredCertificates
};
};
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
index badc70b5f5..b6c31f87e3 100644
--- a/backend/src/services/pki-sync/pki-sync-filter-reconcile-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-filter-reconcile-fns.ts
@@ -122,7 +122,7 @@ export const computePkiSyncCertificateDiff = async (
const toUnlink: TPkiSyncCertificateRef[] = unlinkIds.length
? (await certificateDAL.find({ projectId: pkiSync.projectId, $in: { id: unlinkIds } })).map(
- ({ id, commonName }) => ({ id, commonName })
+ ({ id, commonName, altNames }) => ({ id, commonName, altNames })
)
: [];
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 ec2a30bca3..7aa858e8dd 100644
--- a/backend/src/services/pki-sync/pki-sync-fns.test.ts
+++ b/backend/src/services/pki-sync/pki-sync-fns.test.ts
@@ -180,7 +180,7 @@ describe("assertPkiSyncCanHoldCertificateCount", () => {
undefined,
PKI_SYNC_MAX_LINKED_CERTIFICATES + 1
)
- ).toThrow(/at most 500 certificates/);
+ ).toThrow("at most 500 certificates");
});
test("rejects more than one certificate on a single-certificate destination", () => {
@@ -189,7 +189,7 @@ describe("assertPkiSyncCanHoldCertificateCount", () => {
).not.toThrow();
expect(() =>
assertPkiSyncCanHoldCertificateCount(PkiSync.NutanixPrismCentral, multiCertSchema, undefined, 2)
- ).toThrow(/at most 1 certificate/);
+ ).toThrow("at most 1 certificate");
});
test("does not constrain a sync that holds one certificate", () => {
@@ -201,12 +201,12 @@ describe("assertPkiSyncCanHoldCertificateCount", () => {
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/);
+ ).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/
+ "no placeholder"
);
});
@@ -224,7 +224,7 @@ describe("assertPkiSyncCanHoldCertificateCount", () => {
undefined,
2
)
- ).toThrow(/certificatePath/);
+ ).toThrow("certificatePath");
});
test("rejects a health-check command that names a single certificate", () => {
@@ -235,7 +235,7 @@ describe("assertPkiSyncCanHoldCertificateCount", () => {
undefined,
2
)
- ).toThrow(/certificatePath/);
+ ).toThrow("certificatePath");
});
test("accepts a command that covers every certificate in the run", () => {
@@ -261,7 +261,7 @@ describe("assertPkiSyncCanHoldCertificateCount", () => {
assertPkiSyncCanHoldCertificateCount(PkiSync.GcpCertificateManager, multiCertSchema, gcp, 4)
).not.toThrow();
expect(() => assertPkiSyncCanHoldCertificateCount(PkiSync.GcpCertificateManager, multiCertSchema, gcp, 5)).toThrow(
- /at most 4 certificates/
+ "at most 4 certificates"
);
});
});
@@ -350,27 +350,27 @@ describe("assertFiltersCannotExceedCertificateCap", () => {
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
+ "only accepts a certificate order filter. Remove the certificate profile filter."
);
expect(assertSingle({ certificateOrderIds: ["o"], metadata: [{ key: "tier" }] })).toThrow(
- /only accepts a certificate order filter.*metadata/s
+ "only accepts a certificate order filter. Remove the metadata filter."
);
expect(assertSingle({ certificateOrderIds: ["o"], profileIds: ["p"], metadata: [{ key: "tier" }] })).toThrow(
- /certificate profile and metadata/
+ "Remove the certificate profile and metadata filter."
);
});
test("two certificate orders are rejected", () => {
- expect(assertSingle({ certificateOrderIds: ["o1", "o2"] })).toThrow(/can name at most 1 certificate order/);
+ 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/);
+ 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/
+ "only accepts a certificate order filter"
);
});
@@ -381,7 +381,7 @@ describe("assertFiltersCannotExceedCertificateCap", () => {
certificateOrderIds: ["o1"],
profileIds: ["p"]
})
- ).toThrow(/holds at most 4 certificates, so it only accepts a certificate order filter/);
+ ).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", () => {
@@ -400,6 +400,6 @@ describe("assertFiltersCannotExceedCertificateCap", () => {
assertFiltersCannotExceedCertificateCap(PkiSync.GcpCertificateManager, many, gcp, {
certificateOrderIds: [...four, "e"]
})
- ).toThrow(/can name at most 4 certificate orders/);
+ ).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 e67cc37fc7..28a33e718c 100644
--- a/backend/src/services/pki-sync/pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-fns.ts
@@ -760,6 +760,19 @@ export const getPkiSyncCertificateCap = (
return caps.length ? Math.min(...caps.map(({ cap }) => cap)) : undefined;
};
+export const assertPkiSyncCertificateCapsAllowCount = (
+ destination: PkiSync,
+ syncOptions: Record<string, unknown> | undefined,
+ destinationConfig: Record<string, unknown> | undefined,
+ resultingCertificateCount: number
+) => {
+ const exceeded = getPkiSyncCertificateCaps(destination, syncOptions, destinationConfig).find(
+ ({ cap }) => resultingCertificateCount > cap
+ );
+
+ if (exceeded) throw new BadRequestError({ message: exceeded.reason(resultingCertificateCount) });
+};
+
export const assertPkiSyncCanHoldCertificateCount = (
destination: PkiSync,
syncOptions: Record<string, unknown> | undefined,
@@ -772,11 +785,7 @@ export const assertPkiSyncCanHoldCertificateCount = (
});
}
- const exceeded = getPkiSyncCertificateCaps(destination, syncOptions, destinationConfig).find(
- ({ cap }) => resultingCertificateCount > cap
- );
-
- if (exceeded) throw new BadRequestError({ message: exceeded.reason(resultingCertificateCount) });
+ assertPkiSyncCertificateCapsAllowCount(destination, syncOptions, destinationConfig, resultingCertificateCount);
};
const PKI_SYNC_FILTER_LABELS: Record<TPkiSyncFilterKind, string> = {
diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.ts
index d563065797..37faa443ef 100644
--- a/backend/src/services/pki-sync/pki-sync-queue.ts
+++ b/backend/src/services/pki-sync/pki-sync-queue.ts
@@ -61,10 +61,11 @@ import {
TPkiSyncSyncCertificatesDTO,
TQueuePkiSyncImportCertificatesByIdDTO,
TQueuePkiSyncLinkMatchingCertificatesDTO,
+ TQueuePkiSyncReconcileFiltersDTO,
TQueuePkiSyncRemoveCertificatesByIdDTO,
TQueuePkiSyncSyncCertificatesByIdDTO
} from "./pki-sync-types";
-import { reconcileCertificateAgainstMatchingSyncs } from "./pki-sync-utils";
+import { reconcileCertificateAgainstMatchingSyncs, reconcileSyncFilters } from "./pki-sync-utils";
export type TPkiSyncQueueFactory = ReturnType<typeof pkiSyncQueueFactory>;
@@ -193,6 +194,18 @@ export const pkiSyncQueueFactory = ({
removeOnFail: true
});
+ const queuePkiSyncReconcileFilters = async (payload: TQueuePkiSyncReconcileFiltersDTO) =>
+ queueService.queue(QueueName.PkiSync, QueueJobs.PkiSyncReconcileFilters, payload, {
+ attempts: 3,
+ backoff: {
+ type: "exponential",
+ delay: 3000
+ },
+ jobId: `pki-sync-reconcile-filters-${payload.syncId}`,
+ removeOnComplete: true,
+ removeOnFail: true
+ });
+
const queuePkiSyncImportCertificatesById = async (payload: TQueuePkiSyncImportCertificatesByIdDTO) =>
queueService.queue(QueueName.PkiSync, QueueJobs.PkiSyncImportCertificates, payload, {
attempts: 5,
@@ -748,6 +761,16 @@ export const pkiSyncQueueFactory = ({
break;
}
case QueueJobs.PkiSyncRemoveCertificates: {
+ const { failedToAcquireLockCount = 0, ...rest } = job.data as TQueuePkiSyncRemoveCertificatesByIdDTO;
+
+ if (failedToAcquireLockCount < REQUEUE_LIMIT) {
+ await queuePkiSyncRemoveCertificatesById({
+ ...rest,
+ failedToAcquireLockCount: failedToAcquireLockCount + 1
+ });
+ return;
+ }
+
await pkiSyncDAL.updateById(syncId, {
removeStatus: PkiSyncStatus.Failed,
lastRemoveMessage:
@@ -785,6 +808,20 @@ export const pkiSyncQueueFactory = ({
return;
}
+ if (job.name === QueueJobs.PkiSyncReconcileFilters) {
+ const { syncId: reconcileSyncId } = job.data as TQueuePkiSyncReconcileFiltersDTO;
+ await reconcileSyncFilters(reconcileSyncId, {
+ certificateDAL,
+ certificateSyncDAL,
+ pkiSyncDAL,
+ pkiSyncQueue: { queuePkiSyncSyncCertificatesById, queuePkiSyncRemoveCertificatesById },
+ auditLogService,
+ pkiApplicationDAL,
+ withSyncFilterLock: (lockSyncId, run) => withPkiSyncFilterLock(keyStore, lockSyncId, run)
+ });
+ return;
+ }
+
const { syncId } = job.data as PkiSyncActionJob["data"];
const pkiSync = await pkiSyncDAL.findById(syncId);
@@ -864,6 +901,7 @@ export const pkiSyncQueueFactory = ({
return {
queuePkiSyncLinkMatchingCertificates,
+ queuePkiSyncReconcileFilters,
queuePkiSyncSyncCertificatesById,
queuePkiSyncImportCertificatesById,
queuePkiSyncRemoveCertificatesById
diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.ts
index 1999e16001..439ba97e78 100644
--- a/backend/src/services/pki-sync/pki-sync-service.ts
+++ b/backend/src/services/pki-sync/pki-sync-service.ts
@@ -42,7 +42,7 @@ import {
} from "./pki-sync-filter-reconcile-fns";
import {
assertFiltersCannotExceedCertificateCap,
- assertPkiSyncCanHoldCertificateCount,
+ assertPkiSyncCertificateCapsAllowCount,
assertPkiSyncLicense,
getPkiSyncProviderCapabilities,
listPkiSyncOptions,
@@ -412,15 +412,6 @@ export const pkiSyncServiceFactory = ({
const certificates = await $findApplicationCertificates(certificateIds, expectedProjectId, expectedApplicationId);
- const withoutOrder = certificates.filter((cert) => !cert.orderId);
- if (withoutOrder.length > 0) {
- throw new BadRequestError({
- message: `Certificates without a certificate order cannot be synced: ${withoutOrder
- .map((cert) => `'${cert.commonName}'`)
- .join(", ")}`
- });
- }
-
const orderIds = [...new Set(certificates.map((cert) => cert.orderId))];
if (requireSyncable && expectedApplicationId) {
@@ -527,7 +518,7 @@ export const pkiSyncServiceFactory = ({
auditLogInfo
}: TCreatePkiSyncDTO,
actor: OrgServiceActor
- ): Promise<TPkiSync & { linkedCertificates: TPkiSyncCertificateRef[] }> => {
+ ): Promise<TPkiSync> => {
if (!applicationId) {
throw new BadRequestError({
message:
@@ -652,7 +643,7 @@ export const pkiSyncServiceFactory = ({
await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: pkiSync.id });
}
- return { ...(pkiSync as TPkiSync), linkedCertificates };
+ return pkiSync as TPkiSync;
} catch (err) {
if (err instanceof DatabaseError && (err.error as { code: string })?.code === "23505") {
throw new BadRequestError({
@@ -679,9 +670,7 @@ export const pkiSyncServiceFactory = ({
auditLogInfo
}: Omit<TUpdatePkiSyncDTO, "projectId">,
actor: OrgServiceActor
- ): Promise<
- TPkiSync & { linkedCertificates: TPkiSyncCertificateRef[]; unlinkedCertificates: TPkiSyncCertificateRef[] }
- > => {
+ ): Promise<TPkiSync> => {
const pkiSync = await pkiSyncDAL.findById(id);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
if (applicationId && pkiSync.applicationId !== applicationId) {
@@ -841,7 +830,7 @@ export const pkiSyncServiceFactory = ({
if (syncOptions || destinationConfig) {
const existingCount = (await certificateSyncDAL.findByPkiSyncId(id)).length;
- assertPkiSyncCanHoldCertificateCount(
+ assertPkiSyncCertificateCapsAllowCount(
pkiSync.destination,
effectiveSyncOptions,
effectiveDestinationConfig,
@@ -888,7 +877,7 @@ export const pkiSyncServiceFactory = ({
};
if (Object.values(update).every((value) => value === undefined)) {
- return { ...(pkiSync as TPkiSync), linkedCertificates: [], unlinkedCertificates: [] };
+ return pkiSync as TPkiSync;
}
const storedFilters = pkiSync.filters as TPkiSyncFilters | null;
@@ -899,10 +888,10 @@ export const pkiSyncServiceFactory = ({
if (!areFiltersChanging) {
const written = await pkiSyncDAL.updateById(id, update);
- return { ...(written as TPkiSync), linkedCertificates: [], unlinkedCertificates: [] };
+ return written as TPkiSync;
}
- const { updatedPkiSync, linked, unlinked } = await $withFilterLock(id, async () => {
+ const { updatedPkiSync } = 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}` });
@@ -915,23 +904,19 @@ export const pkiSyncServiceFactory = ({
filters
);
- const applied = await $reconcileFilters(target, filters, {
+ await $reconcileFilters(target, filters, {
auditLogInfo,
writeFilters: async (tx) => {
await pkiSyncDAL.updateById(id, update, tx);
}
});
- const written = await pkiSyncDAL.findById(id);
+ const written = await pkiSyncDAL.findById(id, pkiSyncDAL.primaryNode());
- return { updatedPkiSync: written ?? current, ...applied };
+ return { updatedPkiSync: written ?? current };
});
- return {
- ...(updatedPkiSync as TPkiSync),
- linkedCertificates: linked,
- unlinkedCertificates: unlinked
- };
+ return updatedPkiSync as TPkiSync;
};
const deletePkiSync = async (
@@ -1449,14 +1434,36 @@ export const pkiSyncServiceFactory = ({
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 ?? []) };
+ const storedOrderIds = stored.certificateOrderIds ?? [];
+ const requestedOrderIds = nextOrderIds(storedOrderIds);
+
+ if (deepEqual(storedOrderIds, requestedOrderIds)) return { linked: [], unlinked: [] };
- return $reconcileFilters(current as TPkiSyncReconcileTarget, nextFilters, {
+ const nextFilters = { ...stored, certificateOrderIds: requestedOrderIds };
+
+ const applied = await $reconcileFilters(current as TPkiSyncReconcileTarget, nextFilters, {
auditLogInfo,
writeFilters: async (tx) => {
await pkiSyncDAL.updateById(pkiSync.id, { filters: nextFilters }, tx);
}
});
+
+ await auditLogService.createAuditLog({
+ ...(auditLogInfo ?? { actor: { type: ActorType.PLATFORM, metadata: {} } }),
+ projectId: current.projectId,
+ event: {
+ type: EventType.UPDATE_PKI_SYNC,
+ metadata: {
+ pkiSyncId: current.id,
+ name: current.name,
+ destination: current.destination,
+ hasFilters: true,
+ ...(current.applicationId && { applicationId: current.applicationId })
+ }
+ }
+ });
+
+ return applied;
});
};
diff --git a/backend/src/services/pki-sync/pki-sync-types.ts b/backend/src/services/pki-sync/pki-sync-types.ts
index 97ad9578af..463d436100 100644
--- a/backend/src/services/pki-sync/pki-sync-types.ts
+++ b/backend/src/services/pki-sync/pki-sync-types.ts
@@ -19,6 +19,7 @@ export type TPkiSyncFilters = {
export type TPkiSyncCertificateRef = {
id: string;
commonName: string;
+ altNames?: string | null;
serialNumber?: string;
notAfter?: Date;
orderId?: string;
@@ -301,6 +302,10 @@ export type TQueuePkiSyncLinkMatchingCertificatesDTO = {
applicationId: string;
};
+export type TQueuePkiSyncReconcileFiltersDTO = {
+ syncId: string;
+};
+
export type TQueuePkiSyncSyncCertificatesByIdDTO = {
syncId: string;
failedToAcquireLockCount?: number;
@@ -321,6 +326,7 @@ export type TQueuePkiSyncRemoveCertificatesByIdDTO = {
auditLogInfo?: AuditLogInfo;
deleteSyncOnComplete?: boolean;
certificateIds?: string[];
+ failedToAcquireLockCount?: number;
};
export type TPkiSyncSyncCertificatesDTO = Job<
diff --git a/backend/src/services/pki-sync/pki-sync-utils.ts b/backend/src/services/pki-sync/pki-sync-utils.ts
index fe7acc7447..dd4518c849 100644
--- a/backend/src/services/pki-sync/pki-sync-utils.ts
+++ b/backend/src/services/pki-sync/pki-sync-utils.ts
@@ -12,6 +12,8 @@ import { PkiSync } from "./pki-sync-enums";
import { hasAnyPkiSyncFilter } from "./pki-sync-filter-fns";
import {
applyPkiSyncCertificateDiff,
+ assertPkiSyncCanHoldMatchedCertificates,
+ computePkiSyncCertificateDiff,
describePkiSyncApplication,
TPkiSyncReconcileTarget
} from "./pki-sync-filter-reconcile-fns";
@@ -335,6 +337,34 @@ const $reconcileCertificateAgainstSync = async (
logger.info(`Linked certificate to PKI sync by filter [certificateId=${certificateId}] [pkiSyncId=${pkiSync.id}]`);
};
+export const reconcileSyncFilters = async (syncId: string, dependencies: TReconcileCertificateAgainstSyncsDeps) => {
+ await dependencies.withSyncFilterLock(syncId, async () => {
+ const pkiSync = await dependencies.pkiSyncDAL.findById(syncId, dependencies.pkiSyncDAL.primaryNode());
+ if (!pkiSync?.applicationId) return;
+
+ const target = pkiSync as TPkiSyncReconcileTarget;
+ const diff = await computePkiSyncCertificateDiff(target, pkiSync.filters as TPkiSyncFilters | null, dependencies);
+ if (diff.toLink.length === 0 && diff.toUnlink.length === 0) return;
+
+ let applicableDiff = diff;
+ try {
+ assertPkiSyncCanHoldMatchedCertificates(target, diff.matched.length);
+ } catch (capError) {
+ logger.warn(
+ capError,
+ `A filtered PKI sync matches more certificates than it can hold, so only detachments were applied [pkiSyncId=${syncId}]`
+ );
+ applicableDiff = { ...diff, toLink: [] };
+ if (applicableDiff.toUnlink.length === 0) return;
+ }
+
+ const { linked, unlinked } = await applyPkiSyncCertificateDiff(target, applicableDiff, dependencies);
+ logger.info(
+ `Reconciled a filtered PKI sync [pkiSyncId=${syncId}] [linked=${linked.length}] [unlinked=${unlinked.length}]`
+ );
+ });
+};
+
export const reconcileCertificateAgainstMatchingSyncs = async (
certificateId: string,
applicationId: string | null | undefined,
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 cf82dcbf4a..202b451fd9 100644
--- a/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt
+++ b/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt
@@ -356,7 +356,6 @@ 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/overview.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx
index a5da836744..cb2bdcd67d 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx
@@ -204,7 +204,7 @@ The response carries `matchedCount` and `certificates` for what the filters matc
<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.
+ - One filter can name at most 500 certificate orders, 20 certificate profiles, or 20 metadata pairs.
</Note>
## Sync options
diff --git a/frontend/src/components/pki-syncs/PkiSyncFilterBadges.tsx b/frontend/src/components/pki-syncs/PkiSyncFilterBadges.tsx
index ee7457e69e..f6e23cc049 100644
--- a/frontend/src/components/pki-syncs/PkiSyncFilterBadges.tsx
+++ b/frontend/src/components/pki-syncs/PkiSyncFilterBadges.tsx
@@ -29,9 +29,9 @@ const FilterBadgeOverflow = ({ badges }: { badges: ReactNode[] }) => {
);
};
-export const PkiSyncAnyFilterLabel = <span className="text-sm text-muted/50 italic">Any</span>;
+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>;
+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);
@@ -63,7 +63,7 @@ export const PkiSyncFilterCountLabel = ({ count, names }: TFilterCountLabelProps
);
};
-export const PkiSyncFilterValueBadges = ({ values }: { values: string[] }) => {
+const PkiSyncFilterValueBadges = ({ values }: { values: string[] }) => {
if (values.length === 0) return null;
return (
diff --git a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
index f31892064d..38e729822a 100644
--- a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
+++ b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
@@ -25,7 +25,7 @@ import {
StepperStep,
Toggle
} from "@app/components/v3";
-import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";
+import { getCertificateDisplayName, PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import {
PkiSync,
@@ -471,7 +471,9 @@ export const EditPkiSyncForm = ({
<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>
+ <li key={certificate.id}>
+ {getCertificateDisplayName(certificate).originalDisplayName}
+ </li>
))}
</ul>
{pendingUnlink?.preview.willRemoveFromDestination && (
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable.tsx
index 2e457a56f5..b3535643af 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncMatchedCertificatesTable.tsx
@@ -16,11 +16,12 @@ import {
TooltipContent,
TooltipTrigger
} from "@app/components/v3";
-import { truncateCertificateSerialNumber } from "@app/helpers/pkiSyncs";
+import { getCertificateDisplayName, truncateCertificateSerialNumber } from "@app/helpers/pkiSyncs";
export type TMatchedCertificateRow = {
id: string;
commonName: string;
+ altNames?: string | null;
serialNumber?: string | null;
notAfter?: string | null;
profileName?: string | null;
@@ -65,7 +66,7 @@ export const PkiSyncMatchedCertificatesTable = ({
<Table>
<TableHeader>
<TableRow>
- <TableHead>Common Name</TableHead>
+ <TableHead className="w-full">SAN / CN</TableHead>
<TableHead className="w-1/5">Serial Number</TableHead>
<TableHead className="w-1/5">Profile</TableHead>
<TableHead className="w-1/6">Expires At</TableHead>
@@ -74,15 +75,18 @@ export const PkiSyncMatchedCertificatesTable = ({
<TableBody>
{rows.map((row) => {
const isExpired = row.notAfter ? new Date(row.notAfter) < new Date() : false;
+ const { originalDisplayName } = getCertificateDisplayName(row);
return (
<TableRow key={row.id}>
<TableCell className="max-w-0">
<Tooltip>
<TooltipTrigger asChild>
- <div className="truncate font-mono text-sm">{row.commonName}</div>
+ <div className="truncate font-mono text-sm">{originalDisplayName}</div>
</TooltipTrigger>
- <TooltipContent className="max-w-lg">{row.commonName}</TooltipContent>
+ <TooltipContent className="max-w-lg break-words">
+ {originalDisplayName}
+ </TooltipContent>
</Tooltip>
</TableCell>
<TableCell className="max-w-0">
@@ -91,7 +95,9 @@ export const PkiSyncMatchedCertificatesTable = ({
</div>
</TableCell>
<TableCell className="max-w-0">
- <div className="truncate text-sm">{row.profileName ?? "-"}</div>
+ <div className="truncate text-sm" title={row.profileName ?? ""}>
+ {row.profileName ?? "-"}
+ </div>
</TableCell>
<TableCell className="max-w-0">
<span className={isExpired ? "text-sm text-danger" : "text-sm"}>
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
index 2ec21090c2..5609665e60 100644
--- a/frontend/src/components/pki-syncs/forms/pki-sync-filter-fns.ts
+++ b/frontend/src/components/pki-syncs/forms/pki-sync-filter-fns.ts
@@ -1,3 +1,4 @@
+import { getCertificateDisplayName } from "@app/helpers/pkiSyncs";
import { TPkiSyncFilters } from "@app/hooks/api/pkiSyncs/types";
export const FILTER_KINDS = ["certificateOrderIds", "profileIds", "metadata"] as const;
@@ -34,12 +35,15 @@ export const isCertificateOrderTheOnlyFilter = (filters: TPkiSyncFilters | null
FILTER_KINDS.every((kind) => kind === "certificateOrderIds" || !isFilterPresent(filters, kind));
export const buildOrderNameMap = (
- certificates: { orderId?: string; commonName: string }[] | undefined
+ certificates: { orderId?: string; commonName: string; altNames?: string | null }[] | undefined
): Map<string, string> =>
new Map(
(certificates ?? [])
.filter((certificate) => certificate.orderId)
- .map(({ orderId, commonName }) => [orderId as string, commonName])
+ .map((certificate) => [
+ certificate.orderId as string,
+ getCertificateDisplayName(certificate).originalDisplayName
+ ])
);
const GCP_MAX_CERTIFICATES_PER_MAP_ENTRY = 4;
diff --git a/frontend/src/hooks/api/pkiSyncs/types/common.ts b/frontend/src/hooks/api/pkiSyncs/types/common.ts
index bc2e43d500..cb1063c5bf 100644
--- a/frontend/src/hooks/api/pkiSyncs/types/common.ts
+++ b/frontend/src/hooks/api/pkiSyncs/types/common.ts
@@ -111,6 +111,7 @@ export type TPkiSyncHealthCheckResult = {
export type TPkiSyncPreviewCertificate = {
id: string;
commonName: string;
+ altNames?: string | null;
serialNumber?: string;
notAfter?: string;
orderId?: string;
@@ -121,6 +122,6 @@ export type TPkiSyncFilterPreview = {
matchedCount: number;
hasMoreMatches: boolean;
certificates: TPkiSyncPreviewCertificate[];
- toUnlink: { id: string; commonName: string }[];
+ toUnlink: { id: string; commonName: string; altNames?: string | null }[];
willRemoveFromDestination: boolean;
};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx
index b8c7b9adff..49a3f0e7ab 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx
@@ -3,7 +3,10 @@ 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 {
+ hasAnyFilter,
+ isCertificateOrderTheOnlyFilter
+} from "@app/components/pki-syncs/forms/pki-sync-filter-fns";
import {
Button,
Checkbox,
@@ -28,6 +31,7 @@ import {
useListPkiSyncsWithCertificate,
useRemoveCertificatesFromPkiSync
} from "@app/hooks/api/pkiSyncs";
+import { TPkiSync } from "@app/hooks/api/pkiSyncs/types";
import { ApplicationTab } from "@app/pages/cert-manager/ApplicationDetailsByIDPage/application-tabs";
import { IntegrationsListPageTabs } from "@app/types/integrations";
@@ -43,6 +47,14 @@ type Props = {
applicationName?: string;
};
+const getSyncUnavailableReason = (sync: TPkiSync): string | null => {
+ if (!sync.applicationId) return "Not attached to an Application";
+ if (!hasAnyFilter(sync.filters)) return "No filters, so it holds nothing";
+ if (!isCertificateOrderTheOnlyFilter(sync.filters))
+ return "Selects certificates by profile or metadata";
+ return null;
+};
+
const PER_PAGE = 10;
export const CertificateManagePkiSyncsModal = ({
@@ -242,9 +254,8 @@ export const CertificateManagePkiSyncsModal = ({
</THead>
<TBody>
{paginatedSyncs.map((sync) => {
- const managesItsOwnCertificates = !isCertificateOrderTheOnlyFilter(
- sync.filters
- );
+ const unavailableReason = getSyncUnavailableReason(sync);
+ const managesItsOwnCertificates = Boolean(unavailableReason);
return (
<Tr
@@ -268,9 +279,9 @@ export const CertificateManagePkiSyncsModal = ({
<div className="truncate" title={sync.name}>
{sync.name}
</div>
- {managesItsOwnCertificates && (
+ {unavailableReason && (
<div className="truncate text-xs text-mineshaft-400">
- Selects certificates by filter
+ {unavailableReason}
</div>
)}
</Td>
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx
index 8f541a4df5..172d79d72d 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx
@@ -140,7 +140,11 @@ const PageContent = () => {
<CardHeader className="grid-cols-[1fr_auto] border-b">
<CardTitle>Details</CardTitle>
<CardAction className="col-start-2 row-start-1 self-start justify-self-end">
- <PkiSyncActionTriggers pkiSync={pkiSync} onEdit={handleEdit} />
+ <PkiSyncActionTriggers
+ pkiSync={pkiSync}
+ onEdit={handleEdit}
+ onDelete={handleBack}
+ />
</CardAction>
</CardHeader>
<CardContent>
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsx
index 1f73f897b3..60a48cfd1d 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsx
@@ -1,5 +1,4 @@
import { useCallback } from "react";
-import { useNavigate } from "@tanstack/react-router";
import {
CheckIcon,
CopyIcon,
@@ -33,8 +32,6 @@ import {
TooltipContent,
TooltipTrigger
} from "@app/components/v3";
-import { ROUTE_PATHS } from "@app/const/routes";
-import { useOrganization } from "@app/context";
import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";
import { usePopUp, useToggle } from "@app/hooks";
import {
@@ -46,17 +43,16 @@ import {
useTriggerPkiSyncSyncCertificates,
useUpdatePkiSync
} from "@app/hooks/api/pkiSyncs";
-import { IntegrationsListPageTabs } from "@app/types/integrations";
type Props = {
pkiSync: TPkiSync;
onEdit: () => void;
+ onDelete: () => void;
};
-export const PkiSyncActionTriggers = ({ pkiSync, onEdit }: Props) => {
+export const PkiSyncActionTriggers = ({ pkiSync, onEdit, onDelete }: Props) => {
const { destination, projectId, id } = pkiSync;
- const navigate = useNavigate();
const {
canEdit: canEditSync,
canDelete: canDeleteSync,
@@ -80,7 +76,6 @@ export const PkiSyncActionTriggers = ({ pkiSync, onEdit }: Props) => {
const updatePkiSyncMutation = useUpdatePkiSync();
const { syncOption } = usePkiSyncOption(destination);
- const { currentOrg } = useOrganization();
const destinationName = PKI_SYNC_MAP[destination].name;
@@ -250,18 +245,7 @@ export const PkiSyncActionTriggers = ({ pkiSync, onEdit }: Props) => {
onOpenChange={(isOpen) => handlePopUpToggle("deleteSync", isOpen)}
isOpen={popUp.deleteSync.isOpen}
pkiSync={pkiSync}
- onComplete={() =>
- navigate({
- to: ROUTE_PATHS.CertManager.IntegrationsListPage.path,
- params: {
- projectId,
- orgId: currentOrg.id
- },
- search: {
- selectedTab: IntegrationsListPageTabs.PkiSyncs
- }
- })
- }
+ onComplete={onDelete}
/>
</>
);