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
feat: add new cron jobs for DigiCert order polling and CA CRL rotation
Victor Hugo dos Santos0d011b3a1334
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.tsindex 7ca99ccf70..001099f6d9 100644--- a/backend/src/lib/cron/cron-job.ts+++ b/backend/src/lib/cron/cron-job.ts@@ -27,7 +27,9 @@ export const CronJobName = {SecretRotationV2QueueRotations: "secret-rotation-v2-queue-rotations",AppConnectionCredentialRotationQueueRotations: "app-connection-credential-rotation-queue-rotations",TelemetryInstanceStats: "telemetry-instance-stats",- TelemetryAggregatedEvents: "telemetry-aggregated-events"+ TelemetryAggregatedEvents: "telemetry-aggregated-events",+ DigiCertOrderPolling: "digicert-order-polling",+ CaCrlRotation: "ca-crl-rotation"} as const;// ── tuning constants ──────────────────────────────────────────────────────────diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex ee27bfc648..88e2a2773f 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -67,7 +67,6 @@ export enum QueueName {UpgradeProjectToGhost = "upgrade-project-to-ghost",DynamicSecretRevocation = "dynamic-secret-revocation",DynamicSecretLeaseRevocationFailedEmail = "dynamic-secret-lease-revocation-failed-email",- CaCrlRotation = "ca-crl-rotation",CaLifecycle = "ca-lifecycle", // parent queue to ca-order-certificate-for-subscriberCertificateIssuance = "certificate-issuance",SecretReplication = "secret-replication",@@ -91,8 +90,7 @@ export enum QueueName {AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate",AuditLogClickHouseBatch = "audit-log-clickhouse-batch",PamDiscoveryScan = "pam-discovery-scan",- CaAutoRenewal = "ca-auto-renewal",- DigiCertOrderPolling = "digicert-order-polling"+ CaAutoRenewal = "ca-auto-renewal"}export enum QueueJobs {@@ -277,10 +275,6 @@ export type TQueueJobTypes = {dynamicSecretCfgId: string;};};- [QueueName.CaCrlRotation]: {- name: QueueJobs.CaCrlRotation;- payload: undefined;- };[QueueName.SecretReplication]: {name: QueueJobs.SecretReplication;payload: TSyncSecretsDTO;@@ -482,10 +476,6 @@ export type TQueueJobTypes = {name: QueueJobs.CaAdcsInstall;payload: { caId: string; maxPathLength?: number };};- [QueueName.DigiCertOrderPolling]: {- name: QueueJobs.DigiCertOrderPolling;- payload: undefined;- };};const SECRET_SCANNING_QUEUES = [diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 9d248bfeac..59b1f66374 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2531,6 +2531,7 @@ export const registerRoutes = async (projectDAL,kmsService,queueService,+ cronJob,pkiSubscriberDAL,certificateBodyDAL,certificateSecretDAL,@@ -2760,7 +2761,7 @@ export const registerRoutes = async (});const digicertCaQueue = digicertCertificateAuthorityQueueServiceFactory({- queueService,+ cronJob,certificateRequestDAL,certificateRequestService,certificateAuthorityDAL,@@ -3277,12 +3278,12 @@ export const registerRoutes = async (dailyReminderQueueService.startDailyRemindersJob();secretSyncQueue.startDailySecretSyncRetryJob();dailyExpiringPkiItemAlert.startSendingAlerts();- await certificateAuthorityQueue.startCaCrlRebuildJob();+ certificateAuthorityQueue.startCaCrlRebuildJob();pkiSubscriberQueue.startDailyAutoRenewalJob();pkiAlertV2Queue.init();certificateCleanupQueue.init();certificateV3Queue.init();- await digicertCaQueue.init();+ digicertCaQueue.init();caAutoRenewalQueue.startDailyAutoRenewalJob();await microsoftTeamsService.start();await eventBusService.init();diff --git a/backend/src/services/certificate-authority/certificate-authority-queue.ts b/backend/src/services/certificate-authority/certificate-authority-queue.tsindex 1a633fcd6e..43b79ecb63 100644--- a/backend/src/services/certificate-authority/certificate-authority-queue.ts+++ b/backend/src/services/certificate-authority/certificate-authority-queue.ts@@ -3,11 +3,12 @@ import * as x509 from "@peculiar/x509";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";+import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";import { crypto } from "@app/lib/crypto/cryptography";import { getPqcCrypto, isPqcAlgorithm } from "@app/lib/crypto/pqc";import { BadRequestError } from "@app/lib/errors";import { logger } from "@app/lib/logger";-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";import { CertKeyAlgorithm, CertStatus } from "@app/services/certificate/certificate-types";import { DEFAULT_CRL_VALIDITY_DAYS } from "@app/services/certificate-common/certificate-constants";@@ -51,6 +52,7 @@ type TCertificateAuthorityQueueFactoryDep = {certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;queueService: TQueueServiceFactory;+ cronJob: TCronJobFactory;pkiSubscriberDAL: Pick<TPkiSubscriberDALFactory, "findById" | "updateById">;pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;@@ -67,6 +69,7 @@ export const certificateAuthorityQueueFactory = ({projectDAL,kmsService,queueService,+ cronJob,keyStore,appConnectionDAL,appConnectionService,@@ -108,17 +111,118 @@ export const certificateAuthorityQueueFactory = ({pkiSyncQueue});- const startCaCrlRebuildJob = async () => {+ const startCaCrlRebuildJob = () => {const appCfg = getConfig();// Daily at midnight UTC; only CRLs expiring before next run are rebuiltconst cronPattern = appCfg.NODE_ENV === "development" ? "*/5 * * * *" : "0 0 * * *";- await queueService.upsertJobScheduler(- QueueName.CaCrlRotation,- `${JOB_SCHEDULER_PREFIX}:${QueueJobs.CaCrlRotation}`,- { pattern: cronPattern },- { name: QueueJobs.CaCrlRotation, opts: { delay: 5000 } }- );+ cronJob.register({+ name: CronJobName.CaCrlRotation,+ pattern: cronPattern,+ runHashTtlS: 3 * 24 * 60 * 60,+ enabled: !appCfg.isSecondaryInstance,+ handler: async () => {+ logger.info(`${QueueJobs.CaCrlRotation}: starting CRL rebuild for all internal CAs`);++ const CRL_REBUILD_BATCH_SIZE = 100;+ let offset = 0;+ let totalRebuilt = 0;++ // Rebuild any CRL whose validity expires before the next daily run (~24h from now)+ const nextRunAt = new Date();+ nextRunAt.setDate(nextRunAt.getDate() + 1);++ // eslint-disable-next-line no-constant-condition+ while (true) {+ const internalCas = await internalCertificateAuthorityDAL.find({}, { offset, limit: CRL_REBUILD_BATCH_SIZE });++ if (internalCas.length === 0) break;++ for (const internalCa of internalCas) {+ try {+ const caCrls = await certificateAuthorityCrlDAL.find(+ { caId: internalCa.caId },+ { sort: [["updatedAt", "desc"]], limit: 1 }+ );+ if (caCrls.length === 0) continue;++ // Skip if CRL was recently rebuilt and won't expire before next run+ const crlExpiresAt = new Date(caCrls[0].updatedAt);+ crlExpiresAt.setDate(crlExpiresAt.getDate() + DEFAULT_CRL_VALIDITY_DAYS);+ if (crlExpiresAt > nextRunAt) continue;++ const caSecret = await certificateAuthoritySecretDAL.findOne({ caId: internalCa.caId });+ const alg = keyAlgorithmToAlgCfg(internalCa.keyAlgorithm as CertKeyAlgorithm);++ const ca = await certificateAuthorityDAL.findById(internalCa.caId);++ const keyId = await getProjectKmsCertificateKeyId({+ projectId: ca.projectId,+ projectDAL,+ kmsService+ });++ const kmsDecryptor = await kmsService.decryptWithKmsKey({ kmsId: keyId });+ const privateKey = await kmsDecryptor({ cipherTextBlob: caSecret.encryptedPrivateKey });++ let sk: CryptoKey;+ if (isPqcAlgorithm(internalCa.keyAlgorithm)) {+ sk = await getPqcCrypto().subtle.importKey("pkcs8", privateKey, alg, true, ["sign"]);+ } else {+ const skObj = crypto.nativeCrypto.createPrivateKey({ key: privateKey, format: "der", type: "pkcs8" });+ sk = await crypto.nativeCrypto.subtle.importKey(+ "pkcs8",+ skObj.export({ format: "der", type: "pkcs8" }),+ alg,+ true,+ ["sign"]+ );+ }++ const revokedCerts = await certificateDAL.find({+ caId: internalCa.caId,+ status: CertStatus.REVOKED+ });++ const thisUpdate = new Date();+ const nextUpdate = new Date(thisUpdate);+ nextUpdate.setDate(nextUpdate.getDate() + DEFAULT_CRL_VALIDITY_DAYS);++ const crl = await x509.X509CrlGenerator.create({+ issuer: internalCa.dn,+ thisUpdate,+ nextUpdate,+ entries: revokedCerts.map((revokedCert) => ({+ serialNumber: revokedCert.serialNumber,+ revocationDate: new Date(revokedCert.revokedAt as Date),+ reason: revokedCert.revocationReason as number+ })),+ signingAlgorithm: alg,+ signingKey: sk+ });++ const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: keyId });+ const { cipherTextBlob: encryptedCrl } = await kmsEncryptor({+ plainText: Buffer.from(new Uint8Array(crl.rawData))+ });++ await certificateAuthorityCrlDAL.updateEncryptedCrlAndBumpUpdatedAt(+ { caId: internalCa.caId },+ { encryptedCrl }+ );+ totalRebuilt += 1;+ } catch (err) {+ logger.error(err, `${QueueJobs.CaCrlRotation}: failed to rebuild CRL [caId=${internalCa.caId}]`);+ }+ }++ if (internalCas.length < CRL_REBUILD_BATCH_SIZE) break;+ offset += CRL_REBUILD_BATCH_SIZE;+ }++ logger.info(`${QueueJobs.CaCrlRotation}: CRL rebuild completed, rebuilt ${totalRebuilt} CRLs`);+ }+ });};const orderCertificateForSubscriber = async ({ subscriberId, caType }: TOrderCertificateForSubscriberDTO) => {@@ -189,112 +293,6 @@ export const certificateAuthorityQueueFactory = ({}});- queueService.start(QueueName.CaCrlRotation, async () => {- logger.info(`${QueueName.CaCrlRotation}: starting CRL rebuild for all internal CAs`);-- const CRL_REBUILD_BATCH_SIZE = 100;- let offset = 0;- let totalRebuilt = 0;-- // Rebuild any CRL whose validity expires before the next daily run (~24h from now)- const nextRunAt = new Date();- nextRunAt.setDate(nextRunAt.getDate() + 1);-- // eslint-disable-next-line no-constant-condition- while (true) {- const internalCas = await internalCertificateAuthorityDAL.find({}, { offset, limit: CRL_REBUILD_BATCH_SIZE });-- if (internalCas.length === 0) break;-- for (const internalCa of internalCas) {- try {- const caCrls = await certificateAuthorityCrlDAL.find(- { caId: internalCa.caId },- { sort: [["updatedAt", "desc"]], limit: 1 }- );- if (caCrls.length === 0) continue;-- // Skip if CRL was recently rebuilt and won't expire before next run- const crlExpiresAt = new Date(caCrls[0].updatedAt);- crlExpiresAt.setDate(crlExpiresAt.getDate() + DEFAULT_CRL_VALIDITY_DAYS);- if (crlExpiresAt > nextRunAt) continue;-- const caSecret = await certificateAuthoritySecretDAL.findOne({ caId: internalCa.caId });- const alg = keyAlgorithmToAlgCfg(internalCa.keyAlgorithm as CertKeyAlgorithm);-- const ca = await certificateAuthorityDAL.findById(internalCa.caId);-- const keyId = await getProjectKmsCertificateKeyId({- projectId: ca.projectId,- projectDAL,- kmsService- });-- const kmsDecryptor = await kmsService.decryptWithKmsKey({ kmsId: keyId });- const privateKey = await kmsDecryptor({ cipherTextBlob: caSecret.encryptedPrivateKey });-- let sk: CryptoKey;- if (isPqcAlgorithm(internalCa.keyAlgorithm)) {- sk = await getPqcCrypto().subtle.importKey("pkcs8", privateKey, alg, true, ["sign"]);- } else {- const skObj = crypto.nativeCrypto.createPrivateKey({ key: privateKey, format: "der", type: "pkcs8" });- sk = await crypto.nativeCrypto.subtle.importKey(- "pkcs8",- skObj.export({ format: "der", type: "pkcs8" }),- alg,- true,- ["sign"]- );- }-- const revokedCerts = await certificateDAL.find({- caId: internalCa.caId,- status: CertStatus.REVOKED- });-- const thisUpdate = new Date();- const nextUpdate = new Date(thisUpdate);- nextUpdate.setDate(nextUpdate.getDate() + DEFAULT_CRL_VALIDITY_DAYS);-- const crl = await x509.X509CrlGenerator.create({- issuer: internalCa.dn,- thisUpdate,- nextUpdate,- entries: revokedCerts.map((revokedCert) => ({- serialNumber: revokedCert.serialNumber,- revocationDate: new Date(revokedCert.revokedAt as Date),- reason: revokedCert.revocationReason as number- })),- signingAlgorithm: alg,- signingKey: sk- });-- const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: keyId });- const { cipherTextBlob: encryptedCrl } = await kmsEncryptor({- plainText: Buffer.from(new Uint8Array(crl.rawData))- });-- await certificateAuthorityCrlDAL.updateEncryptedCrlAndBumpUpdatedAt(- { caId: internalCa.caId },- { encryptedCrl }- );- totalRebuilt += 1;- } catch (err) {- logger.error(err, `${QueueName.CaCrlRotation}: failed to rebuild CRL [caId=${internalCa.caId}]`);- }- }-- if (internalCas.length < CRL_REBUILD_BATCH_SIZE) break;- offset += CRL_REBUILD_BATCH_SIZE;- }-- logger.info(`${QueueName.CaCrlRotation}: CRL rebuild completed, rebuilt ${totalRebuilt} CRLs`);- });-- queueService.listen(QueueName.CaCrlRotation, "failed", (job, err) => {- logger.error(err, "Failed to rotate CA CRL %s", job?.id);- });-return {startCaCrlRebuildJob,orderCertificateForSubscriberdiff --git a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-queue.ts b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-queue.tsindex 5dc3858698..192fc589c4 100644--- a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-queue.ts+++ b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-queue.ts@@ -1,7 +1,8 @@/* eslint-disable no-await-in-loop */import { getConfig } from "@app/lib/config/env";+import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";import { logger } from "@app/lib/logger";-import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";+import { QueueJobs } from "@app/queue";import { CertificateRequestStatus } from "../../certificate-common/certificate-constants";import { TCertificateRequestDALFactory } from "../../certificate-request/certificate-request-dal";@@ -19,7 +20,7 @@ type TDigiCertCertificateAuthorityQueueServiceFactoryDep = Omit<TProcessDigiCertRequestDeps,"certificateRequestDAL"> & {- queueService: TQueueServiceFactory;+ cronJob: TCronJobFactory;certificateRequestDAL: Pick<TCertificateRequestDALFactory, "updateById" | "findPendingValidationByCaType">;};@@ -28,18 +29,18 @@ export type TDigiCertCertificateAuthorityQueueServiceFactory = ReturnType<>;export const digicertCertificateAuthorityQueueServiceFactory = ({- queueService,+ cronJob,...processorDeps}: TDigiCertCertificateAuthorityQueueServiceFactoryDep) => {const appCfg = getConfig();- const init = async () => {- if (appCfg.isSecondaryInstance) {- return;- }-- queueService.start(QueueName.DigiCertOrderPolling, async () => {- try {+ const init = () => {+ cronJob.register({+ name: CronJobName.DigiCertOrderPolling,+ pattern: DIGICERT_POLL_CRON_SCHEDULE,+ runHashTtlS: 3 * 24 * 60 * 60,+ enabled: !appCfg.isSecondaryInstance,+ handler: async () => {logger.info(`${QueueJobs.DigiCertOrderPolling}: queue task started`);const clientsByCaId = new Map<string, TDigiCertApiClient>();@@ -75,22 +76,8 @@ export const digicertCertificateAuthorityQueueServiceFactory = ({logger.info(`${QueueJobs.DigiCertOrderPolling}: completed [processed=${processed}] [issued=${issued}] [failed=${failed}]`);- } catch (error) {- logger.error(error, `${QueueJobs.DigiCertOrderPolling}: polling task failed`);- throw error;}});-- await queueService.upsertJobScheduler(- QueueName.DigiCertOrderPolling,- `${JOB_SCHEDULER_PREFIX}:${QueueJobs.DigiCertOrderPolling}`,- { pattern: DIGICERT_POLL_CRON_SCHEDULE },- { name: QueueJobs.DigiCertOrderPolling }- );-- queueService.listen(QueueName.DigiCertOrderPolling, "failed", (_, err) => {- logger.error(err, `${QueueName.DigiCertOrderPolling}: failed`);- });};return {