Skip to content

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

Add auto tidy feature for expired certificates

Carlos Monastyrski0c30a50b6244
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 03ea8d2b2c..546004f613 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -76,6 +76,7 @@ import { TCaAutoRenewalQueueFactory } from "@app/services/certificate-authority/
import { TCaSigningConfigServiceFactory } from "@app/services/certificate-authority/ca-signing-config/ca-signing-config-service";
import { TCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/certificate-authority-service";
import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service";
+import { TCertificateCleanupServiceFactory } from "@app/services/certificate-cleanup/certificate-cleanup-service";
import { TCertificateEstV3ServiceFactory } from "@app/services/certificate-est-v3/certificate-est-v3-service";
import { TCertificatePolicyServiceFactory } from "@app/services/certificate-policy/certificate-policy-service";
import { TCertificateProfileServiceFactory } from "@app/services/certificate-profile/certificate-profile-service";
@@ -306,6 +307,7 @@ declare module "fastify" {
auditLog: TAuditLogServiceFactory;
auditLogStream: TAuditLogStreamServiceFactory;
certificate: TCertificateServiceFactory;
+ certificateCleanup: TCertificateCleanupServiceFactory;
certificateV3: TCertificateV3ServiceFactory;
certificateRequest: TCertificateRequestServiceFactory;
certificateTemplate: TCertificateTemplateServiceFactory;
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 8745d2ddc4..ffca14b25f 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -107,6 +107,9 @@ import {
TCertificateBodies,
TCertificateBodiesInsert,
TCertificateBodiesUpdate,
+ TCertificateCleanupConfigs,
+ TCertificateCleanupConfigsInsert,
+ TCertificateCleanupConfigsUpdate,
TCertificates,
TCertificateSecrets,
TCertificateSecretsInsert,
@@ -1690,5 +1693,10 @@ declare module "knex/types/tables" {
TCaSigningConfigsInsert,
TCaSigningConfigsUpdate
>;
+ [TableName.CertificateCleanupConfig]: KnexOriginal.CompositeTableType<
+ TCertificateCleanupConfigs,
+ TCertificateCleanupConfigsInsert,
+ TCertificateCleanupConfigsUpdate
+ >;
}
}
diff --git a/backend/src/db/migrations/20260316124623_certificate-cleanup.ts b/backend/src/db/migrations/20260316124623_certificate-cleanup.ts
new file mode 100644
index 0000000000..6da28f3d15
--- /dev/null
+++ b/backend/src/db/migrations/20260316124623_certificate-cleanup.ts
@@ -0,0 +1,52 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasTable(TableName.CertificateCleanupConfig))) {
+ await knex.schema.createTable(TableName.CertificateCleanupConfig, (tb) => {
+ tb.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ tb.string("projectId").notNullable().unique();
+ tb.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
+ tb.boolean("isEnabled").notNullable().defaultTo(false);
+ tb.integer("daysBeforeDeletion").notNullable().defaultTo(3);
+ tb.boolean("includeRevokedCertificates").notNullable().defaultTo(false);
+ tb.boolean("skipCertsWithActiveSyncs").notNullable().defaultTo(true);
+ tb.string("lastRunStatus");
+ tb.datetime("lastRunAt");
+ tb.integer("lastRunCertsDeleted").notNullable().defaultTo(0);
+ tb.text("lastRunMessage");
+ tb.timestamps(true, true, true);
+ });
+
+ await createOnUpdateTrigger(knex, TableName.CertificateCleanupConfig);
+ }
+
+ const indexExists = await knex.raw(`SELECT 1 FROM pg_indexes WHERE tablename = ? AND indexname = ?`, [
+ TableName.Certificate,
+ "idx_certificates_status_not_after"
+ ]);
+ if (indexExists.rows.length === 0) {
+ await knex.schema.alterTable(TableName.Certificate, (tb) => {
+ tb.index(["status", "notAfter"], "idx_certificates_status_not_after");
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.schema.dropTableIfExists(TableName.CertificateCleanupConfig);
+ await dropOnUpdateTrigger(knex, TableName.CertificateCleanupConfig);
+
+ if (await knex.schema.hasTable(TableName.Certificate)) {
+ const indexExists = await knex.raw(`SELECT 1 FROM pg_indexes WHERE tablename = ? AND indexname = ?`, [
+ TableName.Certificate,
+ "idx_certificates_status_not_after"
+ ]);
+ if (indexExists.rows.length > 0) {
+ await knex.schema.alterTable(TableName.Certificate, (tb) => {
+ tb.dropIndex(["status", "notAfter"], "idx_certificates_status_not_after");
+ });
+ }
+ }
+}
diff --git a/backend/src/db/schemas/certificate-cleanup-configs.ts b/backend/src/db/schemas/certificate-cleanup-configs.ts
new file mode 100644
index 0000000000..ce9914cea7
--- /dev/null
+++ b/backend/src/db/schemas/certificate-cleanup-configs.ts
@@ -0,0 +1,29 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const CertificateCleanupConfigsSchema = z.object({
+ id: z.string().uuid(),
+ projectId: z.string(),
+ isEnabled: z.boolean().default(false),
+ daysBeforeDeletion: z.number().default(3),
+ includeRevokedCertificates: z.boolean().default(false),
+ skipCertsWithActiveSyncs: z.boolean().default(true),
+ lastRunStatus: z.string().nullable().optional(),
+ lastRunAt: z.date().nullable().optional(),
+ lastRunCertsDeleted: z.number().default(0),
+ lastRunMessage: z.string().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TCertificateCleanupConfigs = z.infer<typeof CertificateCleanupConfigsSchema>;
+export type TCertificateCleanupConfigsInsert = Omit<z.input<typeof CertificateCleanupConfigsSchema>, TImmutableDBKeys>;
+export type TCertificateCleanupConfigsUpdate = Partial<
+ Omit<z.input<typeof CertificateCleanupConfigsSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index cf3a2f1c96..b1226098da 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -33,6 +33,7 @@ export * from "./certificate-authority-certs";
export * from "./certificate-authority-crl";
export * from "./certificate-authority-secret";
export * from "./certificate-bodies";
+export * from "./certificate-cleanup-configs";
export * from "./certificate-requests";
export * from "./certificate-secrets";
export * from "./certificate-syncs";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index 2f5534f70a..2e4c2d4f46 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -248,6 +248,9 @@ export enum TableName {
PkiCertificateInstallationCert = "pki_certificate_installation_certs",
PkiDiscoveryScanHistory = "pki_discovery_scan_history",
+ // PKI Cleanup
+ CertificateCleanupConfig = "certificate_cleanup_configs",
+
// AI
AiMcpServer = "ai_mcp_servers",
AiMcpServerTool = "ai_mcp_server_tools",
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 c722fbfd1b..4b2c12cbe9 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -410,6 +410,8 @@ export enum EventType {
GET_CERTIFICATE_PROFILE_LATEST_ACTIVE_BUNDLE = "get-certificate-profile-latest-active-bundle",
UPDATE_CERTIFICATE_RENEWAL_CONFIG = "update-certificate-renewal-config",
UPDATE_CERTIFICATE_METADATA = "update-certificate-metadata",
+ UPDATE_CERTIFICATE_CLEANUP_CONFIG = "update-certificate-cleanup-config",
+ CERTIFICATE_CLEANUP_COMPLETED = "certificate-cleanup-completed",
DISABLE_CERTIFICATE_RENEWAL_CONFIG = "disable-certificate-renewal-config",
CREATE_CERTIFICATE_REQUEST = "create-certificate-request",
GET_CERTIFICATE_REQUEST = "get-certificate-request",
@@ -4754,6 +4756,29 @@ interface UpdateCertificateMetadataEvent {
};
}
+interface UpdateCertificateCleanupConfigEvent {
+ type: EventType.UPDATE_CERTIFICATE_CLEANUP_CONFIG;
+ metadata: {
+ projectId: string;
+ isEnabled: boolean;
+ daysBeforeDeletion: number;
+ includeRevokedCertificates: boolean;
+ skipCertsWithActiveSyncs: boolean;
+ };
+}
+
+interface CertificateCleanupCompletedEvent {
+ type: EventType.CERTIFICATE_CLEANUP_COMPLETED;
+ metadata: {
+ deletedCount: number;
+ certificates: {
+ serialNumber: string;
+ commonName: string;
+ altNames: string | null;
+ }[];
+ };
+}
+
interface DisableCertificateRenewalConfigEvent {
type: EventType.DISABLE_CERTIFICATE_RENEWAL_CONFIG;
metadata: {
@@ -5822,4 +5847,6 @@ export type Event =
| CreateDynamicSecretLeaseEvent
| DeleteDynamicSecretLeaseEvent
| RenewDynamicSecretLeaseEvent
- | GetDynamicSecretLeaseEvent;
+ | GetDynamicSecretLeaseEvent
+ | UpdateCertificateCleanupConfigEvent
+ | CertificateCleanupCompletedEvent;
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index ccf6da8303..dcc4e5f4ca 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -105,7 +105,8 @@ export enum QueueName {
AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate",
AuditLogClickHouseBatch = "audit-log-clickhouse-batch",
PamDiscoveryScan = "pam-discovery-scan",
- CaAutoRenewal = "ca-auto-renewal"
+ CaAutoRenewal = "ca-auto-renewal",
+ CertificateCleanup = "certificate-cleanup"
}
export enum QueueJobs {
@@ -176,7 +177,8 @@ export enum QueueJobs {
PamDiscoverySourceRunScan = "pam-discovery-run-scan",
PamDiscoveryScheduledScan = "pam-discovery-scheduled-scan",
CaDailyAutoRenewal = "ca-daily-auto-renewal",
- CaVenafiInstall = "ca-venafi-install-job"
+ CaVenafiInstall = "ca-venafi-install-job",
+ CertificateCleanup = "certificate-cleanup-job"
}
export type TQueueOptions = {
@@ -540,6 +542,10 @@ export type TQueueJobTypes = {
name: QueueJobs.CaVenafiInstall;
payload: { caId: string; maxPathLength?: number };
};
+ [QueueName.CertificateCleanup]: {
+ name: QueueJobs.CertificateCleanup;
+ payload: undefined;
+ };
};
const SECRET_SCANNING_QUEUES = [
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 97d1f892b9..e10cafa0a3 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -242,6 +242,9 @@ import { externalCertificateAuthorityDALFactory } from "@app/services/certificat
import { internalCertificateAuthorityDALFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-dal";
import { InternalCertificateAuthorityFns } from "@app/services/certificate-authority/internal/internal-certificate-authority-fns";
import { internalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service";
+import { certificateCleanupConfigDALFactory } from "@app/services/certificate-cleanup/certificate-cleanup-dal";
+import { certificateCleanupQueueFactory } from "@app/services/certificate-cleanup/certificate-cleanup-queue";
+import { certificateCleanupServiceFactory } from "@app/services/certificate-cleanup/certificate-cleanup-service";
import { certificateEstV3ServiceFactory } from "@app/services/certificate-est-v3/certificate-est-v3-service";
import { certificatePolicyDALFactory } from "@app/services/certificate-policy/certificate-policy-dal";
import { certificatePolicyServiceFactory } from "@app/services/certificate-policy/certificate-policy-service";
@@ -1222,6 +1225,7 @@ export const registerRoutes = async (
const acmeAuthDAL = pkiAcmeAuthDALFactory(db);
const acmeOrderAuthDAL = pkiAcmeOrderAuthDALFactory(db);
const acmeChallengeDAL = pkiAcmeChallengeDALFactory(db);
+ const certificateCleanupConfigDAL = certificateCleanupConfigDALFactory(db);
const certificateDAL = certificateDALFactory(db);
const certificateBodyDAL = certificateBodyDALFactory(db);
const certificateSecretDAL = certificateSecretDALFactory(db);
@@ -2027,6 +2031,19 @@ export const registerRoutes = async (
pkiAlertHistoryDAL
});
+ const certificateCleanupService = certificateCleanupServiceFactory({
+ certificateCleanupConfigDAL,
+ permissionService
+ });
+
+ const certificateCleanupQueue = certificateCleanupQueueFactory({
+ db,
+ queueService,
+ certificateCleanupConfigDAL,
+ certificateDAL,
+ auditLogService
+ });
+
const dynamicSecretProviders = buildDynamicSecretProviders({
gatewayService,
gatewayV2Service
@@ -2894,6 +2911,7 @@ export const registerRoutes = async (
await certificateAuthorityQueue.startCaCrlRebuildJob();
await pkiSubscriberQueue.startDailyAutoRenewalJob();
await pkiAlertV2Queue.init();
+ await certificateCleanupQueue.init();
await certificateV3Queue.init();
await caAutoRenewalQueue.startDailyAutoRenewalJob();
await microsoftTeamsService.start();
@@ -2961,6 +2979,7 @@ export const registerRoutes = async (
auditLog: auditLogService,
auditLogStream: auditLogStreamService,
certificate: certificateService,
+ certificateCleanup: certificateCleanupService,
certificateV3: certificateV3Service,
certificateRequest: certificateRequestService,
certificateEstV3: certificateEstV3Service,
diff --git a/backend/src/server/routes/v1/certificate-cleanup-router.ts b/backend/src/server/routes/v1/certificate-cleanup-router.ts
new file mode 100644
index 0000000000..264915f4a1
--- /dev/null
+++ b/backend/src/server/routes/v1/certificate-cleanup-router.ts
@@ -0,0 +1,103 @@
+import { z } from "zod";
+
+import { CertificateCleanupConfigsSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags } from "@app/lib/api-docs";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+export const registerCertificateCleanupRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/",
+ config: {
+ rateLimit: readLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ operationId: "getCertificateCleanupConfig",
+ description: "Get certificate cleanup configuration for a project",
+ tags: [ApiDocsTags.PkiCertificates],
+ querystring: z.object({
+ projectId: z.string().trim().describe("Project ID")
+ }),
+ response: {
+ 200: z.object({
+ config: CertificateCleanupConfigsSchema.omit({ id: true }).nullable()
+ })
+ }
+ },
+ handler: async (req) => {
+ const config = await server.services.certificateCleanup.getConfig({
+ projectId: req.query.projectId,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+ return { config };
+ }
+ });
+
+ server.route({
+ method: "PUT",
+ url: "/",
+ config: {
+ rateLimit: writeLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ operationId: "updateCertificateCleanupConfig",
+ description: "Create or update certificate cleanup configuration for a project",
+ tags: [ApiDocsTags.PkiCertificates],
+ body: z.object({
+ projectId: z.string().trim().describe("Project ID"),
+ isEnabled: z.boolean().optional().describe("Enable auto-cleanup"),
+ daysBeforeDeletion: z.number().int().min(1).max(30).optional().describe("Days past expiration before deletion"),
+ includeRevokedCertificates: z
+ .boolean()
+ .optional()
+ .describe("Also remove revoked certificates even if not yet expired"),
+ skipCertsWithActiveSyncs: z.boolean().optional().describe("Skip certificates with active syncs")
+ }),
+ response: {
+ 200: z.object({
+ config: CertificateCleanupConfigsSchema.omit({ id: true })
+ })
+ }
+ },
+ handler: async (req) => {
+ const config = await server.services.certificateCleanup.updateConfig({
+ projectId: req.body.projectId,
+ isEnabled: req.body.isEnabled,
+ daysBeforeDeletion: req.body.daysBeforeDeletion,
+ includeRevokedCertificates: req.body.includeRevokedCertificates,
+ skipCertsWithActiveSyncs: req.body.skipCertsWithActiveSyncs,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.body.projectId,
+ event: {
+ type: EventType.UPDATE_CERTIFICATE_CLEANUP_CONFIG,
+ metadata: {
+ projectId: req.body.projectId,
+ isEnabled: config.isEnabled,
+ daysBeforeDeletion: config.daysBeforeDeletion,
+ includeRevokedCertificates: config.includeRevokedCertificates,
+ skipCertsWithActiveSyncs: config.skipCertsWithActiveSyncs
+ }
+ }
+ });
+
+ return { config };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.ts
index 6b69c2c7ea..9583cb911d 100644
--- a/backend/src/server/routes/v1/index.ts
+++ b/backend/src/server/routes/v1/index.ts
@@ -14,6 +14,7 @@ import { registerProjectBotRouter } from "./bot-router";
import { registerCaRouter } from "./certificate-authority-router";
import { CERTIFICATE_AUTHORITY_REGISTER_ROUTER_MAP } from "./certificate-authority-routers";
import { registerGeneralCertificateAuthorityRouter } from "./certificate-authority-routers/general-certificate-authority-router";
+import { registerCertificateCleanupRouter } from "./certificate-cleanup-router";
import { registerCertificatePolicyRouter } from "./certificate-policy-router";
import { registerCertificateProfilesRouter } from "./certificate-profiles-router";
import { registerCertificateRouter } from "./certificate-router";
@@ -190,6 +191,7 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
{ prefix: "/certificate-profiles" }
);
await pkiRouter.register(registerPkiAlertRouter, { prefix: "/alerts" });
+ await pkiRouter.register(registerCertificateCleanupRouter, { prefix: "/certificate-cleanup" });
await pkiRouter.register(
async (pkiSyncRouter) => {
await registerPkiSyncRouter(pkiSyncRouter as unknown as FastifyZodProvider);
diff --git a/backend/src/services/certificate-cleanup/certificate-cleanup-dal.ts b/backend/src/services/certificate-cleanup/certificate-cleanup-dal.ts
new file mode 100644
index 0000000000..8a206123c8
--- /dev/null
+++ b/backend/src/services/certificate-cleanup/certificate-cleanup-dal.ts
@@ -0,0 +1,11 @@
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { ormify } from "@app/lib/knex";
+
+export type TCertificateCleanupConfigDALFactory = ReturnType<typeof certificateCleanupConfigDALFactory>;
+
+export const certificateCleanupConfigDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.CertificateCleanupConfig);
+
+ return orm;
+};
diff --git a/backend/src/services/certificate-cleanup/certificate-cleanup-queue.ts b/backend/src/services/certificate-cleanup/certificate-cleanup-queue.ts
new file mode 100644
index 0000000000..f9f7806d5b
--- /dev/null
+++ b/backend/src/services/certificate-cleanup/certificate-cleanup-queue.ts
@@ -0,0 +1,214 @@
+/* eslint-disable no-await-in-loop */
+
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
+import { getConfig } from "@app/lib/config/env";
+import { logger } from "@app/lib/logger";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { ActorType } from "@app/services/auth/auth-type";
+
+import { TCertificateDALFactory } from "../certificate/certificate-dal";
+import { CertStatus } from "../certificate/certificate-types";
+import { TCertificateCleanupConfigDALFactory } from "./certificate-cleanup-dal";
+import { CLEANUP_BATCH_SIZE, CleanupRunStatus } from "./certificate-cleanup-types";
+
+type TCertificateCleanupQueueFactoryDep = {
+ db: TDbClient;
+ queueService: TQueueServiceFactory;
+ certificateCleanupConfigDAL: TCertificateCleanupConfigDALFactory;
+ certificateDAL: Pick<TCertificateDALFactory, "delete">;
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
+};
+
+export type TCertificateCleanupQueueFactory = ReturnType<typeof certificateCleanupQueueFactory>;
+
+export const certificateCleanupQueueFactory = ({
+ db,
+ queueService,
+ certificateCleanupConfigDAL,
+ certificateDAL,
+ auditLogService
+}: TCertificateCleanupQueueFactoryDep) => {
+ const appCfg = getConfig();
+
+ const processProjectCleanup = async (config: {
+ id: string;
+ projectId: string;
+ daysBeforeDeletion: number;
+ includeRevokedCertificates: boolean;
+ skipCertsWithActiveSyncs: boolean;
+ }) => {
+ let deletedCount = 0;
+ let offset = 0;
+ const errorMessages: string[] = [];
+ const deletedCerts: { serialNumber: string; commonName: string; altNames: string | null }[] = [];
+
+ const cutoffDate = new Date();
+ cutoffDate.setDate(cutoffDate.getDate() - config.daysBeforeDeletion);
+
+ let hasMore = true;
+
+ while (hasMore) {
+ let query = db.replicaNode()(TableName.Certificate).where("projectId", config.projectId).select("id");
+
+ if (config.includeRevokedCertificates) {
+ query = query.where(function expiryOrRevoked() {
+ void this.where("notAfter", "<", cutoffDate).orWhere("status", CertStatus.REVOKED);
+ });
+ } else {
+ query = query.where("notAfter", "<", cutoffDate);
+ }
+
+ query = query.offset(offset).limit(CLEANUP_BATCH_SIZE);
+
+ const batch = await query;
+
+ if (batch.length === 0) {
+ break;
+ }
+
+ let idsToDelete = batch.map((cert) => cert.id);
+ let skippedCount = 0;
+
+ if (config.skipCertsWithActiveSyncs && idsToDelete.length > 0) {
+ try {
+ const certsWithSyncs: { certificateId: string }[] = await db
+ .replicaNode()(TableName.CertificateSync)
+ .whereIn("certificateId", idsToDelete)
+ .distinct("certificateId")
+ .select("certificateId");
+
+ const syncedCertIds = new Set(certsWithSyncs.map((row) => row.certificateId));
+ skippedCount = syncedCertIds.size;
+ idsToDelete = idsToDelete.filter((id) => !syncedCertIds.has(id));
+ } catch (err) {
+ logger.error(err, "CertificateCleanup: failed to check certificate syncs");
+ errorMessages.push("Failed to check certificate syncs for batch");
+ skippedCount = idsToDelete.length;
+ idsToDelete = [];
+ }
+ }
+
+ if (idsToDelete.length > 0) {
+ try {
+ const deleted = await certificateDAL.delete({ $in: { id: idsToDelete } });
+ deletedCount += deleted.length;
+
+ for (const cert of deleted) {
+ deletedCerts.push({
+ serialNumber: cert.serialNumber,
+ commonName: cert.commonName,
+ altNames: cert.altNames ?? null
+ });
+ }
+ } catch (err) {
+ logger.error(err, "CertificateCleanup: batch delete failed");
+ errorMessages.push(`Batch delete failed: ${(err as Error).message}`);
+ skippedCount += idsToDelete.length;
+ }
+ }
+
+ offset += skippedCount;
+
+ if (batch.length < CLEANUP_BATCH_SIZE) {
+ hasMore = false;
+ }
+ }
+
+ const lastRunMessage = errorMessages.length > 0 ? errorMessages.slice(0, 5).join("; ") : null;
+
+ await certificateCleanupConfigDAL.updateById(config.id, {
+ lastRunStatus: errorMessages.length > 0 && deletedCount === 0 ? CleanupRunStatus.Error : CleanupRunStatus.Success,
+ lastRunAt: new Date(),
+ lastRunCertsDeleted: deletedCount,
+ lastRunMessage
+ });
+
+ if (deletedCount > 0) {
+ await auditLogService.createAuditLog({
+ projectId: config.projectId,
+ actor: {
+ type: ActorType.PLATFORM,
+ metadata: {}
+ },
+ event: {
+ type: EventType.CERTIFICATE_CLEANUP_COMPLETED,
+ metadata: {
+ deletedCount,
+ certificates: deletedCerts
+ }
+ }
+ });
+ }
+
+ return { deletedCount, errors: errorMessages.length };
+ };
+
+ const init = async () => {
+ if (appCfg.isSecondaryInstance) {
+ return;
+ }
+
+ queueService.start(QueueName.CertificateCleanup, async () => {
+ logger.info(`${QueueJobs.CertificateCleanup}: started`);
+
+ const configs = await certificateCleanupConfigDAL.find({ isEnabled: true });
+
+ logger.info(`${QueueJobs.CertificateCleanup}: found ${configs.length} projects with cleanup enabled`);
+
+ let totalDeleted = 0;
+ let totalErrors = 0;
+
+ for (const config of configs) {
+ try {
+ const result = await processProjectCleanup(config);
+ totalDeleted += result.deletedCount;
+ totalErrors += result.errors;
+
+ if (result.deletedCount > 0) {
+ logger.info(
+ `${QueueJobs.CertificateCleanup}: project ${config.projectId} — deleted ${result.deletedCount} certificates`
+ );
+ }
+ } catch (err) {
+ totalErrors += 1;
+ logger.error(err, `${QueueJobs.CertificateCleanup}: failed for project ${config.projectId}`);
+
+ await certificateCleanupConfigDAL.updateById(config.id, {
+ lastRunStatus: CleanupRunStatus.Error,
+ lastRunAt: new Date(),
+ lastRunCertsDeleted: 0,
+ lastRunMessage: String((err as Error).message || "Unknown error").slice(0, 500)
+ });
+ }
+ }
+
+ logger.info(`${QueueJobs.CertificateCleanup}: completed — deleted ${totalDeleted} total, ${totalErrors} errors`);
+ });
+
+ await queueService.stopRepeatableJob(
+ QueueName.CertificateCleanup,
+ QueueJobs.CertificateCleanup,
+ { pattern: "0 2 * * *", utc: true },
+ QueueJobs.CertificateCleanup
+ );
+
+ await queueService.queue(QueueName.CertificateCleanup, QueueJobs.CertificateCleanup, undefined, {
+ jobId: QueueJobs.CertificateCleanup,
+ repeat: {
+ pattern: "0 2 * * *",
+ utc: true,
+ key: QueueJobs.CertificateCleanup
+ },
+ removeOnComplete: true,
+ removeOnFail: true
+ });
+
+ queueService.listen(QueueName.CertificateCleanup, "failed", (_, err) => {
+ logger.error(err, `${QueueName.CertificateCleanup}: job failed`);
+ });
+ };
+
+ return { init };
+};
diff --git a/backend/src/services/certificate-cleanup/certificate-cleanup-service.ts b/backend/src/services/certificate-cleanup/certificate-cleanup-service.ts
new file mode 100644
index 0000000000..09ff06ad46
--- /dev/null
+++ b/backend/src/services/certificate-cleanup/certificate-cleanup-service.ts
@@ -0,0 +1,91 @@
+import { ActionProjectType, ProjectMembershipRole } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { ForbiddenRequestError } from "@app/lib/errors";
+
+import { TCertificateCleanupConfigDALFactory } from "./certificate-cleanup-dal";
+import { TGetCertificateCleanupConfigDTO, TUpdateCertificateCleanupConfigDTO } from "./certificate-cleanup-types";
+
+type TCertificateCleanupServiceFactoryDep = {
+ certificateCleanupConfigDAL: TCertificateCleanupConfigDALFactory;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+};
+
+export type TCertificateCleanupServiceFactory = ReturnType<typeof certificateCleanupServiceFactory>;
+
+export const certificateCleanupServiceFactory = ({
+ certificateCleanupConfigDAL,
+ permissionService
+}: TCertificateCleanupServiceFactoryDep) => {
+ const getConfig = async ({
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TGetCertificateCleanupConfigDTO) => {
+ const { hasRole } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+
+ if (!hasRole(ProjectMembershipRole.Admin)) {
+ throw new ForbiddenRequestError({ message: "Only admins can access certificate cleanup configuration" });
+ }
+
+ const config = await certificateCleanupConfigDAL.findOne({ projectId });
+
+ return config || null;
+ };
+
+ const updateConfig = async ({
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ isEnabled,
+ daysBeforeDeletion,
+ includeRevokedCertificates,
+ skipCertsWithActiveSyncs
+ }: TUpdateCertificateCleanupConfigDTO) => {
+ const { hasRole } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+
+ if (!hasRole(ProjectMembershipRole.Admin)) {
+ throw new ForbiddenRequestError({ message: "Only admins can modify certificate cleanup configuration" });
+ }
+
+ const existing = await certificateCleanupConfigDAL.findOne({ projectId });
+
+ if (existing) {
+ const updated = await certificateCleanupConfigDAL.updateById(existing.id, {
+ isEnabled,
+ daysBeforeDeletion,
+ includeRevokedCertificates,
+ skipCertsWithActiveSyncs
+ });
+ return updated;
+ }
+
+ const created = await certificateCleanupConfigDAL.create({
+ projectId,
+ isEnabled: isEnabled ?? false,
+ daysBeforeDeletion: daysBeforeDeletion ?? 3,
+ includeRevokedCertificates: includeRevokedCertificates ?? false,
+ skipCertsWithActiveSyncs: skipCertsWithActiveSyncs ?? true
+ });
+ return created;
+ };
+
+ return { getConfig, updateConfig };
+};
diff --git a/backend/src/services/certificate-cleanup/certificate-cleanup-types.ts b/backend/src/services/certificate-cleanup/certificate-cleanup-types.ts
new file mode 100644
index 0000000000..1921cc4f7b
--- /dev/null
+++ b/backend/src/services/certificate-cleanup/certificate-cleanup-types.ts
@@ -0,0 +1,17 @@
+import { TProjectPermission } from "@app/lib/types";
+
+export type TGetCertificateCleanupConfigDTO = TProjectPermission;
+
+export type TUpdateCertificateCleanupConfigDTO = {
+ isEnabled?: boolean;
+ daysBeforeDeletion?: number;
+ includeRevokedCertificates?: boolean;
+ skipCertsWithActiveSyncs?: boolean;
+} & TProjectPermission;
+
+export enum CleanupRunStatus {
+ Success = "success",
+ Error = "error"
+}
+
+export const CLEANUP_BATCH_SIZE = 500;
diff --git a/docs/docs.json b/docs/docs.json
index 356ea1b3c9..5a9c9a0aa2 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -747,7 +747,13 @@
"documentation/platform/pki/alerting/pagerduty-alerts"
]
},
- "documentation/platform/pki/approvals"
+ "documentation/platform/pki/approvals",
+ {
+ "group": "Settings",
+ "pages": [
+ "documentation/platform/pki/settings/certificate-cleanup"
+ ]
+ }
]
},
{
diff --git a/docs/documentation/platform/pki/settings/certificate-cleanup.mdx b/docs/documentation/platform/pki/settings/certificate-cleanup.mdx
new file mode 100644
index 0000000000..70a6a800d8
--- /dev/null
+++ b/docs/documentation/platform/pki/settings/certificate-cleanup.mdx
@@ -0,0 +1,40 @@
+---
+title: "Certificate Cleanup"
+sidebarTitle: "Certificate Cleanup"
+description: "Learn how to configure automatic cleanup of expired certificates in Infisical"
+---
+
+## Concept
+
+Certificate cleanup is a project-level setting that automatically removes expired certificates on a daily schedule.
+Over time, expired certificates accumulate and add clutter to your certificate inventory. Enabling cleanup keeps your project organized by periodically deleting certificates that have been expired for a configurable number of days.
+
+The cleanup job runs once daily. Each run processes eligible certificates in batches, rebuilds CRLs for any affected CAs, and records the result so you can verify it from the Settings page.
+
+## Configuring Certificate Cleanup
+
+To configure certificate cleanup, head to your Certificate Management Project > Settings > **Certificate Cleanup**.
+
+![certificate cleanup settings](/images/platform/pki/settings/certificate-cleanup.png)
+
+### Fields
+
+- **Enable toggle**: Turns automatic cleanup on or off for the project. When disabled, no certificates are removed.
+- **Delete certificates after N days past expiration**: The number of days a certificate must be expired before it becomes eligible for deletion. For example, setting this to `3` means certificates are removed 3 days after their `notAfter` date. Accepts values between 1 and 30.
+
+### Options
+
+- **Include Revoked Certificates**: When enabled, revoked certificates are also removed even if they have not yet expired. When disabled, revoked certificates are excluded from cleanup until they expire and exceed the configured retention window like any other certificate.
+- **Skip Certificates with Active Syncs**: When enabled, certificates that are synced to external services (e.g. AWS Certificate Manager, Azure Key Vault) are not removed. This prevents breaking active integrations that depend on the certificate.
+
+### Last Execution
+
+After the cleanup job runs, the settings page displays:
+
+- **Status**: Whether the last run succeeded or encountered errors.
+- **Last Run**: The date and time of the last execution.
+- **Certificates Removed**: The number of certificates deleted in the last run.
+
+## Permissions
+
+Only project **Admins** can view and configure certificate cleanup settings.
diff --git a/docs/images/platform/pki/settings/certificate-cleanup.png b/docs/images/platform/pki/settings/certificate-cleanup.png
new file mode 100644
index 0000000000..cde0729974
Binary files /dev/null and b/docs/images/platform/pki/settings/certificate-cleanup.png differ
diff --git a/frontend/src/hooks/api/certificateCleanup/index.tsx b/frontend/src/hooks/api/certificateCleanup/index.tsx
new file mode 100644
index 0000000000..677b893122
--- /dev/null
+++ b/frontend/src/hooks/api/certificateCleanup/index.tsx
@@ -0,0 +1,3 @@
+export { useUpdateCertificateCleanupConfig } from "./mutations";
+export { useGetCertificateCleanupConfig } from "./queries";
+export type { TCertificateCleanupConfig, TUpdateCertificateCleanupConfigDTO } from "./types";
diff --git a/frontend/src/hooks/api/certificateCleanup/mutations.tsx b/frontend/src/hooks/api/certificateCleanup/mutations.tsx
new file mode 100644
index 0000000000..96db5e5704
--- /dev/null
+++ b/frontend/src/hooks/api/certificateCleanup/mutations.tsx
@@ -0,0 +1,25 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { certificateCleanupKeys } from "./queries";
+import { TCertificateCleanupConfig, TUpdateCertificateCleanupConfigDTO } from "./types";
+
+export const useUpdateCertificateCleanupConfig = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: async (dto: TUpdateCertificateCleanupConfigDTO) => {
+ const { data } = await apiRequest.put<{ config: TCertificateCleanupConfig }>(
+ "/api/v1/cert-manager/certificate-cleanup",
+ dto
+ );
+ return data.config;
+ },
+ onSuccess: (_, variables) => {
+ queryClient.invalidateQueries({
+ queryKey: certificateCleanupKeys.getConfig(variables.projectId)
+ });
+ }
+ });
+};
diff --git a/frontend/src/hooks/api/certificateCleanup/queries.tsx b/frontend/src/hooks/api/certificateCleanup/queries.tsx
new file mode 100644
index 0000000000..2df8428fc2
--- /dev/null
+++ b/frontend/src/hooks/api/certificateCleanup/queries.tsx
@@ -0,0 +1,23 @@
+import { useQuery } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { TCertificateCleanupConfig } from "./types";
+
+export const certificateCleanupKeys = {
+ getConfig: (projectId: string) => [{ projectId }, "certificate-cleanup-config"] as const
+};
+
+export const useGetCertificateCleanupConfig = (projectId: string) => {
+ return useQuery({
+ queryKey: certificateCleanupKeys.getConfig(projectId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ config: TCertificateCleanupConfig | null }>(
+ "/api/v1/cert-manager/certificate-cleanup",
+ { params: { projectId } }
+ );
+ return data.config;
+ },
+ enabled: Boolean(projectId)
+ });
+};
diff --git a/frontend/src/hooks/api/certificateCleanup/types.ts b/frontend/src/hooks/api/certificateCleanup/types.ts
new file mode 100644
index 0000000000..d7c6fbf47a
--- /dev/null
+++ b/frontend/src/hooks/api/certificateCleanup/types.ts
@@ -0,0 +1,20 @@
+export type TCertificateCleanupConfig = {
+ projectId: string;
+ isEnabled: boolean;
+ daysBeforeDeletion: number;
+ includeRevokedCertificates: boolean;
+ skipCertsWithActiveSyncs: boolean;
+
+ lastRunStatus: string | null;
+ lastRunAt: string | null;
+ lastRunCertsDeleted: number;
+ lastRunMessage: string | null;
+};
+
+export type TUpdateCertificateCleanupConfigDTO = {
+ projectId: string;
+ isEnabled?: boolean;
+ daysBeforeDeletion?: number;
+ includeRevokedCertificates?: boolean;
+ skipCertsWithActiveSyncs?: boolean;
+};
diff --git a/frontend/src/hooks/api/index.tsx b/frontend/src/hooks/api/index.tsx
index cfc0a399fc..2a25f78a1e 100644
--- a/frontend/src/hooks/api/index.tsx
+++ b/frontend/src/hooks/api/index.tsx
@@ -14,6 +14,7 @@ export * from "./auditLogStreams";
export * from "./auth";
export * from "./bots";
export * from "./ca";
+export * from "./certificateCleanup";
export * from "./certificatePolicies";
export * from "./certificates";
export * from "./certificateTemplates";
diff --git a/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx b/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx
index 0a6111cce3..97ec7fe966 100644
--- a/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx
+++ b/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx
@@ -8,11 +8,18 @@ import { useOrganization } from "@app/context";
import { ProjectType } from "@app/hooks/api/projects/types";
import { ProjectGeneralTab } from "@app/pages/project/SettingsPage/components/ProjectGeneralTab";
+import { CertificateCleanupTab } from "./components/CertificateCleanupTab";
+
const tabs = [
{
name: "General",
key: "tab-project-general",
Component: ProjectGeneralTab
+ },
+ {
+ name: "Certificate Cleanup",
+ key: "tab-certificate-cleanup",
+ Component: CertificateCleanupTab
}
];
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/CertificateCleanupTab.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/CertificateCleanupTab.tsx
new file mode 100644
index 0000000000..a62f9c6bac
--- /dev/null
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/CertificateCleanupTab.tsx
@@ -0,0 +1,216 @@
+import { useEffect } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { format } from "date-fns";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import { Badge, Button, Skeleton, Switch, UnstableInput } from "@app/components/v3";
+import { useProject } from "@app/context";
+import {
+ useGetCertificateCleanupConfig,
+ useUpdateCertificateCleanupConfig
+} from "@app/hooks/api/certificateCleanup";
+
+const formSchema = z.object({
+ isEnabled: z.boolean(),
+ daysBeforeDeletion: z.coerce.number().int().min(1).max(30),
+ includeRevokedCertificates: z.boolean(),
+ skipCertsWithActiveSyncs: z.boolean()
+});
+
+type TFormData = z.infer<typeof formSchema>;
+
+export const CertificateCleanupTab = () => {
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
+
+ const { data: config, isLoading } = useGetCertificateCleanupConfig(projectId);
+ const updateConfig = useUpdateCertificateCleanupConfig();
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ watch,
+ formState: { isSubmitting, isDirty }
+ } = useForm<TFormData>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ isEnabled: false,
+ daysBeforeDeletion: 3,
+ includeRevokedCertificates: false,
+ skipCertsWithActiveSyncs: true
+ }
+ });
+
+ useEffect(() => {
+ if (config) {
+ reset({
+ isEnabled: config.isEnabled,
+ daysBeforeDeletion: config.daysBeforeDeletion,
+ includeRevokedCertificates: config.includeRevokedCertificates,
+ skipCertsWithActiveSyncs: config.skipCertsWithActiveSyncs
+ });
+ }
+ }, [config, reset]);
+
+ const isEnabled = watch("isEnabled");
+
+ const onSubmit = async (data: TFormData) => {
+ try {
+ await updateConfig.mutateAsync({
+ projectId,
+ ...data
+ });
+ createNotification({
+ text: "Certificate cleanup configuration saved",
+ type: "success"
+ });
+ } catch {
+ createNotification({
+ text: "Failed to save certificate cleanup configuration",
+ type: "error"
+ });
+ }
+ };
+
+ if (isLoading) {
+ return (
+ <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-6">
+ <Skeleton className="h-6 w-48" />
+ <Skeleton className="mt-2 h-4 w-80" />
+ <div className="mt-6 flex flex-col gap-4">
+ <Skeleton className="h-10 w-full" />
+ <Skeleton className="h-10 w-full" />
+ <Skeleton className="h-10 w-full" />
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <form onSubmit={handleSubmit(onSubmit)}>
+ <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-6">
+ <div className="flex items-start justify-between">
+ <div>
+ <h2 className="text-xl font-medium text-mineshaft-100">Certificate Cleanup</h2>
+ <p className="mt-1 text-sm text-gray-400">
+ Automatically remove expired certificates to keep your project organized
+ </p>
+ </div>
+ <Controller
+ control={control}
+ name="isEnabled"
+ render={({ field: { value, onChange } }) => (
+ <Switch variant="project" checked={value} onCheckedChange={onChange} />
+ )}
+ />
+ </div>
+
+ {config?.lastRunAt && (
+ <div className="mt-6 rounded-md border border-mineshaft-600 bg-mineshaft-800 px-4 py-3">
+ <p className="mb-2 text-xs font-medium tracking-wide text-gray-400 uppercase">
+ Last Execution
+ </p>
+ <div className="flex items-center gap-6">
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-gray-400">Status:</span>
+ <Badge variant={config.lastRunStatus === "success" ? "success" : "danger"}>
+ {config.lastRunStatus === "success" ? "Success" : "Error"}
+ </Badge>
+ </div>
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-gray-400">Last Run:</span>
+ <span className="text-xs font-medium text-mineshaft-100">
+ {format(new Date(config.lastRunAt), "yyyy-MM-dd, hh:mm a")}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-gray-400">Certificates Removed:</span>
+ <span className="text-xs font-medium text-mineshaft-100">
+ {config.lastRunCertsDeleted}
+ </span>
+ </div>
+ </div>
+ </div>
+ )}
+
+ <div className="mt-6 flex flex-col gap-5">
+ <div className="flex items-center gap-2">
+ <span className="text-sm text-mineshaft-100">Delete certificates after</span>
+ <Controller
+ control={control}
+ name="daysBeforeDeletion"
+ render={({ field }) => (
+ <UnstableInput
+ {...field}
+ type="number"
+ className="w-20"
+ min={1}
+ max={30}
+ disabled={!isEnabled}
+ />
+ )}
+ />
+ <span className="text-sm text-gray-400">days past expiration</span>
+ </div>
+
+ <div className="flex flex-col divide-y divide-mineshaft-600">
+ <Controller
+ control={control}
+ name="includeRevokedCertificates"
+ render={({ field: { value, onChange } }) => (
+ <div className="flex items-center gap-4 py-4">
+ <Switch
+ variant="project"
+ checked={isEnabled && value}
+ onCheckedChange={onChange}
+ disabled={!isEnabled}
+ />
+ <div>
+ <p className="text-sm font-medium text-mineshaft-100">
+ Include Revoked Certificates
+ </p>
+ <p className="mt-0.5 text-xs text-gray-400">
+ Also remove revoked certificates even if they haven&apos;t expired yet
+ </p>
+ </div>
+ </div>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="skipCertsWithActiveSyncs"
+ render={({ field: { value, onChange } }) => (
+ <div className="flex items-center gap-4 py-4">
+ <Switch
+ variant="project"
+ checked={isEnabled && value}
+ onCheckedChange={onChange}
+ disabled={!isEnabled}
+ />
+ <div>
+ <p className="text-sm font-medium text-mineshaft-100">
+ Skip Certificates with Active Syncs
+ </p>
+ <p className="mt-0.5 text-xs text-gray-400">
+ Do not remove certificates that are synced to external services
+ </p>
+ </div>
+ </div>
+ )}
+ />
+ </div>
+
+ {isDirty && (
+ <Button type="submit" variant="project" isPending={isSubmitting}>
+ Save
+ </Button>
+ )}
+ </div>
+ </div>
+ </form>
+ );
+};