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
Add automated job to rebuild CA CRL
Carlos Monastyrskic0bffdfb9259
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex c67162342f..21342b8eab 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -303,9 +303,7 @@ export type TQueueJobTypes = {};[QueueName.CaCrlRotation]: {name: QueueJobs.CaCrlRotation;- payload: {- caId: string;- };+ payload: undefined;};[QueueName.SecretReplication]: {name: QueueJobs.SecretReplication;diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex ede9548aba..17ede98aab 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2272,7 +2272,8 @@ export const registerRoutes = async (appConnectionDAL,appConnectionService,pkiSyncDAL,- pkiSyncQueue+ pkiSyncQueue,+ internalCertificateAuthorityDAL});const internalCertificateAuthorityService = internalCertificateAuthorityServiceFactory({@@ -2779,6 +2780,7 @@ export const registerRoutes = async (await dailyReminderQueueService.startDailyRemindersJob();await dailyReminderQueueService.startSecretReminderMigrationJob();await dailyExpiringPkiItemAlert.startSendingAlerts();+ await certificateAuthorityQueue.startCaCrlRebuildJob();await pkiSubscriberQueue.startDailyAutoRenewalJob();await pkiAlertV2Queue.init();await certificateV3Queue.init();diff --git a/backend/src/services/certificate-authority/certificate-authority-queue.ts b/backend/src/services/certificate-authority/certificate-authority-queue.tsindex 50e29b23a0..ca75b5b3f9 100644--- a/backend/src/services/certificate-authority/certificate-authority-queue.ts+++ b/backend/src/services/certificate-authority/certificate-authority-queue.ts@@ -3,8 +3,7 @@ import * as x509 from "@peculiar/x509";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { crypto } from "@app/lib/crypto/cryptography";-import { daysToMillisecond, secondsToMillis } from "@app/lib/dates";-import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { BadRequestError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";@@ -30,10 +29,8 @@ import { CaType } from "./certificate-authority-enums";import { keyAlgorithmToAlgCfg } from "./certificate-authority-fns";import { TCertificateAuthoritySecretDALFactory } from "./certificate-authority-secret-dal";import { TExternalCertificateAuthorityDALFactory } from "./external-certificate-authority-dal";-import {- TOrderCertificateForSubscriberDTO,- TRotateCaCrlTriggerDTO-} from "./internal/internal-certificate-authority-types";+import { TInternalCertificateAuthorityDALFactory } from "./internal/internal-certificate-authority-dal";+import { TOrderCertificateForSubscriberDTO } from "./internal/internal-certificate-authority-types";type TCertificateAuthorityQueueFactoryDep = {certificateAuthorityDAL: TCertificateAuthorityDALFactory;@@ -55,6 +52,7 @@ type TCertificateAuthorityQueueFactoryDep = {pkiSubscriberDAL: Pick<TPkiSubscriberDALFactory, "findById" | "updateById">;pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;+ internalCertificateAuthorityDAL: Pick<TInternalCertificateAuthorityDALFactory, "find">;};export type TCertificateAuthorityQueueFactory = ReturnType<typeof certificateAuthorityQueueFactory>;@@ -75,7 +73,8 @@ export const certificateAuthorityQueueFactory = ({certificateSecretDAL,pkiSubscriberDAL,pkiSyncDAL,- pkiSyncQueue+ pkiSyncQueue,+ internalCertificateAuthorityDAL}: TCertificateAuthorityQueueFactoryDep) => {const acmeFns = AcmeCertificateAuthorityFns({appConnectionDAL,@@ -107,37 +106,24 @@ export const certificateAuthorityQueueFactory = ({pkiSyncQueue});- // TODO 1: auto-periodic rotation- // TODO 2: manual rotation-- const setCaCrlRotationInterval = async ({ caId, rotationIntervalDays }: TRotateCaCrlTriggerDTO) => {+ const startCaCrlRebuildJob = async () => {const appCfg = getConfig();+ // Every Sunday at midnight UTC (weekly, matching 7-day CRL validity)+ const cronPattern = appCfg.NODE_ENV === "development" ? "*/5 * * * *" : "0 0 * * 0";- // query for config- // const caCrl = await certificateAuthorityCrlDAL.findOne({- // caId- // });-- await queueService.queue(- // TODO: clarify queue + job naming+ // clear previous repeatable job+ await queueService.stopRepeatableJob(QueueName.CaCrlRotation,QueueJobs.CaCrlRotation,- {- caId- },- {- jobId: `ca-crl-rotation-${caId}`,- repeat: {- // on prod it this will be in days, in development this will be second- every:- appCfg.NODE_ENV === "development"- ? secondsToMillis(rotationIntervalDays)- : daysToMillisecond(rotationIntervalDays),- immediately: true,- key: `ca-crl-rotation-${caId}`- }- }+ { pattern: cronPattern, utc: true },+ QueueJobs.CaCrlRotation);++ await queueService.queue(QueueName.CaCrlRotation, QueueJobs.CaCrlRotation, undefined, {+ delay: 5000,+ jobId: QueueJobs.CaCrlRotation,+ repeat: { pattern: cronPattern, utc: true, key: QueueJobs.CaCrlRotation }+ });};const orderCertificateForSubscriber = async ({ subscriberId, caType }: TOrderCertificateForSubscriberDTO) => {@@ -208,80 +194,85 @@ export const certificateAuthorityQueueFactory = ({}});- queueService.start(QueueName.CaCrlRotation, async (job) => {- const { caId } = job.data;- logger.info(`secretReminderQueue.process: [secretDocument=${caId}]`);+ queueService.start(QueueName.CaCrlRotation, async () => {+ logger.info(`${QueueName.CaCrlRotation}: starting CRL rebuild for all internal CAs`);- const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);- if (!ca.internalCa) throw new NotFoundError({ message: `CA with ID '${caId}' not found` });+ const CRL_REBUILD_BATCH_SIZE = 100;+ let offset = 0;+ let totalRebuilt = 0;+ let hasMore = true;- const caSecret = await certificateAuthoritySecretDAL.findOne({ caId: ca.id });+ while (hasMore) {+ const internalCas = await internalCertificateAuthorityDAL.find({}, { offset, limit: CRL_REBUILD_BATCH_SIZE });- const alg = keyAlgorithmToAlgCfg(ca.internalCa.keyAlgorithm as CertKeyAlgorithm);+ if (internalCas.length === 0) {+ hasMore = false;+ break;+ }- const keyId = await getProjectKmsCertificateKeyId({- projectId: ca.projectId,- projectDAL,- kmsService- });+ for (const internalCa of internalCas) {+ try {+ const caSecret = await certificateAuthoritySecretDAL.findOne({ caId: internalCa.caId });+ const alg = keyAlgorithmToAlgCfg(internalCa.keyAlgorithm as CertKeyAlgorithm);- const kmsDecryptor = await kmsService.decryptWithKmsKey({- kmsId: keyId- });- const privateKey = await kmsDecryptor({- cipherTextBlob: caSecret.encryptedPrivateKey- });+ const ca = await certificateAuthorityDAL.findById(internalCa.caId);- const skObj = crypto.nativeCrypto.createPrivateKey({ key: privateKey, format: "der", type: "pkcs8" });- const sk = await crypto.nativeCrypto.subtle.importKey(- "pkcs8",- skObj.export({ format: "der", type: "pkcs8" }),- alg,- true,- ["sign"]- );+ const keyId = await getProjectKmsCertificateKeyId({+ projectId: ca.projectId,+ projectDAL,+ kmsService+ });- const revokedCerts = await certificateDAL.find({- caId: ca.id,- status: CertStatus.REVOKED- });+ const kmsDecryptor = await kmsService.decryptWithKmsKey({ kmsId: keyId });+ const privateKey = await kmsDecryptor({ cipherTextBlob: caSecret.encryptedPrivateKey });- const thisUpdate = new Date();- const nextUpdate = new Date(thisUpdate);- nextUpdate.setDate(nextUpdate.getDate() + DEFAULT_CRL_VALIDITY_DAYS);-- const crl = await x509.X509CrlGenerator.create({- issuer: ca.internalCa.dn,- thisUpdate,- nextUpdate,- entries: revokedCerts.map((revokedCert) => {- return {- serialNumber: revokedCert.serialNumber,- revocationDate: new Date(revokedCert.revokedAt as Date),- reason: revokedCert.revocationReason as number,- invalidity: new Date("2022/01/01"),- issuer: ca.internalCa?.dn- };- }),- signingAlgorithm: alg,- signingKey: sk- });+ const skObj = crypto.nativeCrypto.createPrivateKey({ key: privateKey, format: "der", type: "pkcs8" });+ const sk = await crypto.nativeCrypto.subtle.importKey(+ "pkcs8",+ skObj.export({ format: "der", type: "pkcs8" }),+ alg,+ true,+ ["sign"]+ );- const kmsEncryptor = await kmsService.encryptWithKmsKey({- kmsId: keyId- });- const { cipherTextBlob: encryptedCrl } = await kmsEncryptor({- plainText: Buffer.from(new Uint8Array(crl.rawData))- });+ const revokedCerts = await certificateDAL.find({+ caId: internalCa.caId,+ status: CertStatus.REVOKED+ });- await certificateAuthorityCrlDAL.update(- {- caId: ca.id- },- {- encryptedCrl+ 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.update({ caId: internalCa.caId }, { encryptedCrl });+ totalRebuilt += 1;+ } catch (err) {+ logger.error(err, `${QueueName.CaCrlRotation}: failed to rebuild CRL for CA ${internalCa.caId}`);+ }}- );++ offset += CRL_REBUILD_BATCH_SIZE;+ }++ logger.info(`${QueueName.CaCrlRotation}: CRL rebuild completed, rebuilt ${totalRebuilt} CRLs`);});queueService.listen(QueueName.CaCrlRotation, "failed", (job, err) => {@@ -289,7 +280,7 @@ export const certificateAuthorityQueueFactory = ({});return {- setCaCrlRotationInterval,+ startCaCrlRebuildJob,orderCertificateForSubscriber};};