Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Address PR comments
Carlos Monastyrski3356c4f017d1
diff --git a/backend/src/db/migrations/20260316124623_certificate-cleanup.ts b/backend/src/db/migrations/20260316124623_certificate-cleanup.tsindex 002ed8ed3d..1249536c74 100644--- a/backend/src/db/migrations/20260316124623_certificate-cleanup.ts+++ b/backend/src/db/migrations/20260316124623_certificate-cleanup.ts@@ -10,8 +10,7 @@ export async function up(knex: Knex): Promise<void> {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.integer("postExpiryRetentionDays").notNullable().defaultTo(3);tb.boolean("skipCertsWithActiveSyncs").notNullable().defaultTo(true);tb.string("lastRunStatus");tb.datetime("lastRunAt");@@ -25,11 +24,11 @@ export async function up(knex: Knex): Promise<void> {const indexExists = await knex.raw(`SELECT 1 FROM pg_indexes WHERE tablename = ? AND indexname = ?`, [TableName.Certificate,- "idx_certificates_status_not_after"+ "idx_certificates_not_after"]);if (indexExists.rows.length === 0) {await knex.schema.alterTable(TableName.Certificate, (tb) => {- tb.index(["status", "notAfter"], "idx_certificates_status_not_after");+ tb.index(["notAfter"], "idx_certificates_not_after");});}}@@ -41,11 +40,11 @@ export async function down(knex: Knex): Promise<void> {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"+ "idx_certificates_not_after"]);if (indexExists.rows.length > 0) {await knex.schema.alterTable(TableName.Certificate, (tb) => {- tb.dropIndex(["status", "notAfter"], "idx_certificates_status_not_after");+ tb.dropIndex(["notAfter"], "idx_certificates_not_after");});}}diff --git a/backend/src/db/schemas/certificate-cleanup-configs.ts b/backend/src/db/schemas/certificate-cleanup-configs.tsindex ce9914cea7..c8b5d67174 100644--- a/backend/src/db/schemas/certificate-cleanup-configs.ts+++ b/backend/src/db/schemas/certificate-cleanup-configs.ts@@ -11,8 +11,7 @@ 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),+ postExpiryRetentionDays: z.number().default(3),skipCertsWithActiveSyncs: z.boolean().default(true),lastRunStatus: z.string().nullable().optional(),lastRunAt: z.date().nullable().optional(),diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 4b2c12cbe9..0cfde72dc5 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -4761,8 +4761,7 @@ interface UpdateCertificateCleanupConfigEvent {metadata: {projectId: string;isEnabled: boolean;- daysBeforeDeletion: number;- includeRevokedCertificates: boolean;+ postExpiryRetentionDays: number;skipCertsWithActiveSyncs: boolean;};}@@ -4771,11 +4770,7 @@ interface CertificateCleanupCompletedEvent {type: EventType.CERTIFICATE_CLEANUP_COMPLETED;metadata: {deletedCount: number;- certificates: {- serialNumber: string;- commonName: string;- altNames: string | null;- }[];+ certificateSerialNumbers: string[];};}diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex e10cafa0a3..ffa99dd3a3 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2041,6 +2041,7 @@ export const registerRoutes = async (queueService,certificateCleanupConfigDAL,certificateDAL,+ certificateRequestDAL,auditLogService});diff --git a/backend/src/server/routes/v1/certificate-cleanup-router.ts b/backend/src/server/routes/v1/certificate-cleanup-router.tsindex 264915f4a1..513c0198d0 100644--- a/backend/src/server/routes/v1/certificate-cleanup-router.ts+++ b/backend/src/server/routes/v1/certificate-cleanup-router.ts@@ -55,12 +55,14 @@ export const registerCertificateCleanupRouter = async (server: FastifyZodProvidetags: [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()+ isEnabled: z.boolean().optional().describe("Enable cleanup"),+ postExpiryRetentionDays: z+ .number()+ .int()+ .min(1)+ .max(30).optional()- .describe("Also remove revoked certificates even if not yet expired"),+ .describe("Days after expiration before deletion"),skipCertsWithActiveSyncs: z.boolean().optional().describe("Skip certificates with active syncs")}),response: {@@ -73,8 +75,7 @@ export const registerCertificateCleanupRouter = async (server: FastifyZodProvideconst config = await server.services.certificateCleanup.updateConfig({projectId: req.body.projectId,isEnabled: req.body.isEnabled,- daysBeforeDeletion: req.body.daysBeforeDeletion,- includeRevokedCertificates: req.body.includeRevokedCertificates,+ postExpiryRetentionDays: req.body.postExpiryRetentionDays,skipCertsWithActiveSyncs: req.body.skipCertsWithActiveSyncs,actor: req.permission.type,actorId: req.permission.id,@@ -90,8 +91,7 @@ export const registerCertificateCleanupRouter = async (server: FastifyZodProvidemetadata: {projectId: req.body.projectId,isEnabled: config.isEnabled,- daysBeforeDeletion: config.daysBeforeDeletion,- includeRevokedCertificates: config.includeRevokedCertificates,+ postExpiryRetentionDays: config.postExpiryRetentionDays,skipCertsWithActiveSyncs: config.skipCertsWithActiveSyncs}}diff --git a/backend/src/services/certificate-cleanup/certificate-cleanup-queue.ts b/backend/src/services/certificate-cleanup/certificate-cleanup-queue.tsindex 6b9b240e89..ba4b6e0748 100644--- a/backend/src/services/certificate-cleanup/certificate-cleanup-queue.ts+++ b/backend/src/services/certificate-cleanup/certificate-cleanup-queue.ts@@ -9,15 +9,16 @@ 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 { TCertificateRequestDALFactory } from "../certificate-request/certificate-request-dal";import { TCertificateCleanupConfigDALFactory } from "./certificate-cleanup-dal";-import { CLEANUP_AUDIT_LOG_CAP, CLEANUP_BATCH_SIZE, CleanupRunStatus } from "./certificate-cleanup-types";+import { CLEANUP_BATCH_SIZE, CleanupRunStatus } from "./certificate-cleanup-types";type TCertificateCleanupQueueFactoryDep = {db: TDbClient;queueService: TQueueServiceFactory;certificateCleanupConfigDAL: TCertificateCleanupConfigDALFactory;certificateDAL: Pick<TCertificateDALFactory, "delete">;+ certificateRequestDAL: Pick<TCertificateRequestDALFactory, "delete">;auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;};@@ -28,6 +29,7 @@ export const certificateCleanupQueueFactory = ({queueService,certificateCleanupConfigDAL,certificateDAL,+ certificateRequestDAL,auditLogService}: TCertificateCleanupQueueFactoryDep) => {const appCfg = getConfig();@@ -35,17 +37,16 @@ export const certificateCleanupQueueFactory = ({const processProjectCleanup = async (config: {id: string;projectId: string;- daysBeforeDeletion: number;- includeRevokedCertificates: boolean;+ postExpiryRetentionDays: number;skipCertsWithActiveSyncs: boolean;}) => {let deletedCount = 0;let offset = 0;const errorMessages: string[] = [];- let pendingAuditCerts: { serialNumber: string; commonName: string; altNames: string | null }[] = [];+ let pendingAuditSerials: string[] = [];const flushAuditLog = async () => {- if (pendingAuditCerts.length === 0) return;+ if (pendingAuditSerials.length === 0) return;await auditLogService.createAuditLog({projectId: config.projectId,actor: {@@ -56,15 +57,15 @@ export const certificateCleanupQueueFactory = ({type: EventType.CERTIFICATE_CLEANUP_COMPLETED,metadata: {deletedCount,- certificates: pendingAuditCerts+ certificateSerialNumbers: pendingAuditSerials}}});- pendingAuditCerts = [];+ pendingAuditSerials = [];};const cutoffDate = new Date();- cutoffDate.setDate(cutoffDate.getDate() - config.daysBeforeDeletion);+ cutoffDate.setDate(cutoffDate.getDate() - config.postExpiryRetentionDays);let hasMore = true;@@ -72,17 +73,10 @@ export const certificateCleanupQueueFactory = ({let query = db.replicaNode()(TableName.Certificate).where("projectId", config.projectId)+ .where("notAfter", "<", cutoffDate).orderBy("id", "asc").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;@@ -115,17 +109,16 @@ export const certificateCleanupQueueFactory = ({if (idsToDelete.length > 0) {try {- const deleted = await certificateDAL.delete({ $in: { id: idsToDelete } });+ const deleted = await certificateCleanupConfigDAL.transaction(async (tx) => {+ await certificateRequestDAL.delete({ $in: { certificateId: idsToDelete } }, tx);+ return certificateDAL.delete({ $in: { id: idsToDelete } }, tx);+ });deletedCount += deleted.length;for (const cert of deleted) {- pendingAuditCerts.push({- serialNumber: cert.serialNumber,- commonName: cert.commonName,- altNames: cert.altNames ?? null- });+ pendingAuditSerials.push(cert.serialNumber);- if (pendingAuditCerts.length >= CLEANUP_AUDIT_LOG_CAP) {+ if (pendingAuditSerials.length >= CLEANUP_BATCH_SIZE) {await flushAuditLog();}}@@ -190,7 +183,6 @@ export const certificateCleanupQueueFactory = ({await certificateCleanupConfigDAL.updateById(config.id, {lastRunStatus: CleanupRunStatus.Error,lastRunAt: new Date(),- lastRunCertsDeleted: 0,lastRunMessage: String((err as Error).message || "Unknown error").slice(0, 500)});}diff --git a/backend/src/services/certificate-cleanup/certificate-cleanup-service.ts b/backend/src/services/certificate-cleanup/certificate-cleanup-service.tsindex 09ff06ad46..87aa7149bb 100644--- a/backend/src/services/certificate-cleanup/certificate-cleanup-service.ts+++ b/backend/src/services/certificate-cleanup/certificate-cleanup-service.ts@@ -48,8 +48,7 @@ export const certificateCleanupServiceFactory = ({actorAuthMethod,actorOrgId,isEnabled,- daysBeforeDeletion,- includeRevokedCertificates,+ postExpiryRetentionDays,skipCertsWithActiveSyncs}: TUpdateCertificateCleanupConfigDTO) => {const { hasRole } = await permissionService.getProjectPermission({@@ -65,26 +64,33 @@ export const certificateCleanupServiceFactory = ({throw new ForbiddenRequestError({ message: "Only admins can modify certificate cleanup configuration" });}- const existing = await certificateCleanupConfigDAL.findOne({ projectId });+ const config = await certificateCleanupConfigDAL.transaction(async (tx) => {+ const existing = await certificateCleanupConfigDAL.findOne({ projectId }, tx);- if (existing) {- const updated = await certificateCleanupConfigDAL.updateById(existing.id, {- isEnabled,- daysBeforeDeletion,- includeRevokedCertificates,- skipCertsWithActiveSyncs- });- return updated;- }+ if (existing) {+ return certificateCleanupConfigDAL.updateById(+ existing.id,+ {+ isEnabled,+ postExpiryRetentionDays,+ skipCertsWithActiveSyncs+ },+ tx+ );+ }- const created = await certificateCleanupConfigDAL.create({- projectId,- isEnabled: isEnabled ?? false,- daysBeforeDeletion: daysBeforeDeletion ?? 3,- includeRevokedCertificates: includeRevokedCertificates ?? false,- skipCertsWithActiveSyncs: skipCertsWithActiveSyncs ?? true+ return certificateCleanupConfigDAL.create(+ {+ projectId,+ isEnabled: isEnabled ?? false,+ postExpiryRetentionDays: postExpiryRetentionDays ?? 3,+ skipCertsWithActiveSyncs: skipCertsWithActiveSyncs ?? true+ },+ tx+ );});- return created;++ return config;};return { getConfig, updateConfig };diff --git a/backend/src/services/certificate-cleanup/certificate-cleanup-types.ts b/backend/src/services/certificate-cleanup/certificate-cleanup-types.tsindex 34a038c701..5cf56fe9b9 100644--- a/backend/src/services/certificate-cleanup/certificate-cleanup-types.ts+++ b/backend/src/services/certificate-cleanup/certificate-cleanup-types.ts@@ -4,8 +4,7 @@ export type TGetCertificateCleanupConfigDTO = TProjectPermission;export type TUpdateCertificateCleanupConfigDTO = {isEnabled?: boolean;- daysBeforeDeletion?: number;- includeRevokedCertificates?: boolean;+ postExpiryRetentionDays?: number;skipCertsWithActiveSyncs?: boolean;} & TProjectPermission;@@ -15,4 +14,3 @@ export enum CleanupRunStatus {}export const CLEANUP_BATCH_SIZE = 500;-export const CLEANUP_AUDIT_LOG_CAP = 1000;diff --git a/docs/documentation/platform/pki/settings/certificate-cleanup.mdx b/docs/documentation/platform/pki/settings/certificate-cleanup.mdxindex 70a6a800d8..5f5d7d7468 100644--- a/docs/documentation/platform/pki/settings/certificate-cleanup.mdx+++ b/docs/documentation/platform/pki/settings/certificate-cleanup.mdx@@ -9,8 +9,6 @@ description: "Learn how to configure automatic cleanup of expired certificates iCertificate 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 CleanupTo configure certificate cleanup, head to your Certificate Management Project > Settings > **Certificate Cleanup**.@@ -20,11 +18,10 @@ To configure certificate cleanup, head to your Certificate Management Project >### 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.+- **Delete certificates N days after 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 Executiondiff --git a/docs/images/platform/pki/settings/certificate-cleanup.png b/docs/images/platform/pki/settings/certificate-cleanup.pngindex cde0729974..02b4f6e2dd 100644Binary files a/docs/images/platform/pki/settings/certificate-cleanup.png and b/docs/images/platform/pki/settings/certificate-cleanup.png differdiff --git a/frontend/src/hooks/api/certificateCleanup/types.ts b/frontend/src/hooks/api/certificateCleanup/types.tsindex d7c6fbf47a..eb4f288c78 100644--- a/frontend/src/hooks/api/certificateCleanup/types.ts+++ b/frontend/src/hooks/api/certificateCleanup/types.ts@@ -1,8 +1,7 @@export type TCertificateCleanupConfig = {projectId: string;isEnabled: boolean;- daysBeforeDeletion: number;- includeRevokedCertificates: boolean;+ postExpiryRetentionDays: number;skipCertsWithActiveSyncs: boolean;lastRunStatus: string | null;@@ -14,7 +13,6 @@ export type TCertificateCleanupConfig = {export type TUpdateCertificateCleanupConfigDTO = {projectId: string;isEnabled?: boolean;- daysBeforeDeletion?: number;- includeRevokedCertificates?: boolean;+ postExpiryRetentionDays?: number;skipCertsWithActiveSyncs?: boolean;};diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/CertificateCleanupTab.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/CertificateCleanupTab.tsxindex a62f9c6bac..d14751028c 100644--- a/frontend/src/pages/cert-manager/SettingsPage/components/CertificateCleanupTab.tsx+++ b/frontend/src/pages/cert-manager/SettingsPage/components/CertificateCleanupTab.tsx@@ -14,8 +14,7 @@ import {const formSchema = z.object({isEnabled: z.boolean(),- daysBeforeDeletion: z.coerce.number().int().min(1).max(30),- includeRevokedCertificates: z.boolean(),+ postExpiryRetentionDays: z.coerce.number().int().min(1).max(30),skipCertsWithActiveSyncs: z.boolean()});@@ -38,8 +37,7 @@ export const CertificateCleanupTab = () => {resolver: zodResolver(formSchema),defaultValues: {isEnabled: false,- daysBeforeDeletion: 3,- includeRevokedCertificates: false,+ postExpiryRetentionDays: 3,skipCertsWithActiveSyncs: true}});@@ -48,8 +46,7 @@ export const CertificateCleanupTab = () => {if (config) {reset({isEnabled: config.isEnabled,- daysBeforeDeletion: config.daysBeforeDeletion,- includeRevokedCertificates: config.includeRevokedCertificates,+ postExpiryRetentionDays: config.postExpiryRetentionDays,skipCertsWithActiveSyncs: config.skipCertsWithActiveSyncs});}@@ -138,10 +135,10 @@ export const CertificateCleanupTab = () => {<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>+ <span className="text-sm text-mineshaft-100">Delete certificates</span><Controllercontrol={control}- name="daysBeforeDeletion"+ name="postExpiryRetentionDays"render={({ field }) => (<UnstableInput{...field}@@ -153,33 +150,10 @@ export const CertificateCleanupTab = () => {/>)}/>- <span className="text-sm text-gray-400">days past expiration</span>+ <span className="text-sm text-gray-400">days after 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't expired yet- </p>- </div>- </div>- )}- />-<Controllercontrol={control}name="skipCertsWithActiveSyncs"