Skip to content

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

22.7 KB
Raw Blame
import * as x509 from "@peculiar/x509";
import { Knex } from "knex";
import forge from "node-forge";
import RE2 from "re2";

import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { SUPPORTED_GENERAL_NAME_TYPES } from "@app/services/certificate-common/certificate-constants";
import {
  parseExternallyIssuedCustomExtensions,
  parseIssuedCustomExtensions,
  TResolvedCustomExtension
} from "@app/services/certificate-common/certificate-extension-fns";
import { TCertificateSource, toX509Certificate } from "@app/services/certificate-common/certificate-parse-utils";

import { extractDnParts } from "../certificate-authority/certificate-authority-fns";
import type { TCertificateRequestDALFactory } from "../certificate-request/certificate-request-dal";
import type { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";
import type { TPkiCollectionItemDALFactory } from "../pki-collection/pki-collection-item-dal";
import { getProjectKmsCertificateKeyId } from "../project/project-fns";
import type { TCertificateBodyDALFactory } from "./certificate-body-dal";
import type { TCertificateDALFactory } from "./certificate-dal";
import type { TCertificateSecretDALFactory } from "./certificate-secret-dal";
import {
  CertExtendedKeyUsage,
  CertExtendedKeyUsageOIDToName,
  CertKeyAlgorithm,
  CertKeyUsage,
  CertSignatureAlgorithm,
  CertStatus,
  CrlReason,
  TCertificateFingerprints,
  TCertificateSubject,
  TGetCertificateCredentialsDTO,
  TParsedCertificateBody
} from "./certificate-types";

export const keySizeToAlgorithms = (keySize: number): string[] => {
  const map: Record<number, string[]> = {
    2048: [CertKeyAlgorithm.RSA_2048],
    3072: [CertKeyAlgorithm.RSA_3072],
    4096: [CertKeyAlgorithm.RSA_4096],
    256: [CertKeyAlgorithm.ECDSA_P256],
    384: [CertKeyAlgorithm.ECDSA_P384],
    521: [CertKeyAlgorithm.ECDSA_P521]
  };
  return map[keySize] ?? [];
};

export const revocationReasonToCrlCode = (crlReason: CrlReason) => {
  switch (crlReason) {
    case CrlReason.KEY_COMPROMISE:
      return x509.X509CrlReason.keyCompromise;
    case CrlReason.CA_COMPROMISE:
      return x509.X509CrlReason.cACompromise;
    case CrlReason.AFFILIATION_CHANGED:
      return x509.X509CrlReason.affiliationChanged;
    case CrlReason.SUPERSEDED:
      return x509.X509CrlReason.superseded;
    case CrlReason.CESSATION_OF_OPERATION:
      return x509.X509CrlReason.cessationOfOperation;
    case CrlReason.CERTIFICATE_HOLD:
      return x509.X509CrlReason.certificateHold;
    case CrlReason.PRIVILEGE_WITHDRAWN:
      return x509.X509CrlReason.privilegeWithdrawn;
    case CrlReason.A_A_COMPROMISE:
      return x509.X509CrlReason.aACompromise;
    default:
      return x509.X509CrlReason.unspecified;
  }
};

export const isCertChainValid = async (certificates: x509.X509Certificate[]) => {
  if (certificates.length === 1) {
    return true;
  }

  const leafCert = certificates[0];
  const chain = new x509.X509ChainBuilder({
    certificates: certificates.slice(1)
  });

  const chainItems = await chain.build(leafCert);

  // chain.build() implicitly verifies the chain
  return chainItems.length === certificates.length;
};

export const constructPemChainFromCerts = (certificates: x509.X509Certificate[]) =>
  certificates
    .map((cert) => cert.toString("pem"))
    .join("\n")
    .trim();

export const prependCertToPemChain = (cert: x509.X509Certificate, pemChain: string) =>
  `${cert.toString("pem")}\n${pemChain}`;

// Concatenates a certificate, its chain, and its private key into a single PEM bundle. Used by sync
// destinations that upload the full certificate as one file.
export const buildCertificateBundle = (cert: string, privateKey: string, certificateChain?: string): string => {
  const parts = [cert.trim()];
  if (certificateChain) {
    parts.push(certificateChain.trim());
  }
  parts.push(privateKey.trim());
  return `${parts.join("\n")}\n`;
};

export const normalizePemText = (pemText: string) => {
  const cleaned = pemText
    .replace(new RE2("\\\\r\\\\n|\\\\n|\\\\r", "g"), "\n")
    .replace(new RE2("[\\x{2010}-\\x{2015}\\x{2212}]", "g"), "-")
    .replace(new RE2("[\\x{00A0}\\x{2007}\\x{202F}]", "g"), " ")
    .replace(new RE2("[\\x{200B}-\\x{200D}\\x{2060}\\x{FEFF}]", "g"), "");

  const blockPattern = new RE2("-----BEGIN ([A-Z0-9 ]+)-----([A-Za-z0-9+/=\\s]*)-----END ([A-Z0-9 ]+)-----", "g");
  const whitespace = new RE2("\\s", "g");
  const blocks: string[] = [];
  let match = blockPattern.exec(cleaned);
  while (match) {
    const [, beginLabel, body, endLabel] = match;
    if (beginLabel === endLabel) {
      const base64Body = body.replace(whitespace, "");
      const lines = base64Body.match(/.{1,64}/g) ?? [];
      blocks.push([`-----BEGIN ${beginLabel}-----`, ...lines, `-----END ${endLabel}-----`].join("\n"));
    }
    match = blockPattern.exec(cleaned);
  }

  const beginMarkerCount = (cleaned.match(/-----BEGIN /g) ?? []).length;
  return blocks.length && blocks.length === beginMarkerCount ? blocks.join("\n") : pemText.trim();
};

export const splitPemChain = (pemText: string) => {
  const re2Pattern = new RE2("-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----", "g");

  return re2Pattern.match(pemText) || [];
};

export const parsePemCertificateChain = (chainPem: string): x509.X509Certificate[] | null => {
  const chainBlocks = splitPemChain(chainPem);
  if (chainBlocks.length !== (chainPem.match(/-----BEGIN /g) ?? []).length) return null;

  try {
    return chainBlocks.map((pem) => new x509.X509Certificate(pem));
  } catch {
    return null;
  }
};

/**
 * Return the public and private key of certificate
 * Note: credentials are returned as PEM strings
 */
export const getCertificateCredentials = async ({
  certId,
  projectId,
  certificateSecretDAL,
  projectDAL,
  kmsService
}: TGetCertificateCredentialsDTO) => {
  const certificateSecret = await certificateSecretDAL.findOne({ certId });
  if (!certificateSecret)
    throw new NotFoundError({ message: `Certificate secret for certificate with ID '${certId}' not found` });

  const keyId = await getProjectKmsCertificateKeyId({
    projectId,
    projectDAL,
    kmsService
  });
  const kmsDecryptor = await kmsService.decryptWithKmsKey({
    kmsId: keyId
  });
  const decryptedPrivateKey = await kmsDecryptor({
    cipherTextBlob: certificateSecret.encryptedPrivateKey
  });

  const certPrivateKey = decryptedPrivateKey.toString("utf-8");

  let certPublicKey = "";
  try {
    const skObj = crypto.nativeCrypto.createPrivateKey({ key: decryptedPrivateKey, format: "pem", type: "pkcs8" });
    const pkObj = crypto.nativeCrypto.createPublicKey(skObj);
    certPublicKey = pkObj.export({ format: "pem", type: "spki" }).toString();
  } catch {
    // Key type not supported by the current OpenSSL version
  }

  return {
    certificateSecret,
    certPrivateKey,
    certPublicKey
  };
};

export const generatePkcs12FromCertificate = async ({
  certificate,
  certificateChain,
  privateKey,
  password,
  alias
}: {
  certificate: string;
  certificateChain: string;
  privateKey: string;
  password: string;
  alias: string;
}): Promise<Buffer> => {
  try {
    if (!password || password.trim() === "") {
      throw new BadRequestError({ message: "Password is required for PKCS12 keystore generation" });
    }

    // node-forge only builds keystores from RSA keys, and cannot read PQC keys at all
    let keyType: string | undefined;
    try {
      keyType = crypto.nativeCrypto.createPrivateKey({
        key: privateKey,
        format: "pem",
        type: "pkcs8"
      }).asymmetricKeyType;
    } catch {
      keyType = undefined;
    }

    if (keyType !== "rsa") {
      throw new BadRequestError({
        message: "PKCS#12 export is not supported for this key type. Use PEM format instead."
      });
    }

    const cert = forge.pki.certificateFromPem(certificate);
    const key = forge.pki.privateKeyFromPem(privateKey);

    const chainCerts = [];
    if (certificateChain) {
      const chainPems = splitPemChain(certificateChain);
      for (const chainPem of chainPems) {
        try {
          const chainCert = forge.pki.certificateFromPem(chainPem);
          chainCerts.push(chainCert);
        } catch (error) {
          // Skip invalid certificates in chain
        }
      }
    }

    // Generate PKCS12 file
    const p12Asn1 = forge.pkcs12.toPkcs12Asn1(key, [cert, ...chainCerts], password, {
      algorithm: "aes256", // Modern AES-256 encryption
      friendlyName: alias
    });

    const p12Der = forge.asn1.toDer(p12Asn1).getBytes();

    return Buffer.from(p12Der, "binary");
  } catch (error) {
    if (error instanceof BadRequestError) throw error;
    throw new BadRequestError({
      message: `Failed to generate PKCS12 keystore: ${error instanceof Error ? error.message : "Unknown error"}`
    });
  }
};

/**
 * Format a raw hex digest as an upper-cased, colon-delimited fingerprint (e.g., "1A:2F:73:...").
 */
export const formatFingerprint = (hash: string) =>
  new RE2(".{2}", "g").match(hash.toUpperCase())?.join(":") ?? hash.toUpperCase();

export enum CertificateThumbprintAlgorithm {
  SHA1 = "sha1",
  SHA256 = "sha256"
}

/**
 * Normalize a user-supplied certificate thumbprint into the colon-delimited fingerprint format
 * stored on the certificate (e.g., "1A:2F:..."). Accepts thumbprints with or without colons,
 * whitespace, or other separators, in any case. Returns the matching algorithm based on digest
 * length (40 hex chars => SHA-1, 64 hex chars => SHA-256).
 */
export const normalizeThumbprint = (thumbprint: string) => {
  const hex = thumbprint.replace(new RE2("[^a-fA-F0-9]", "g"), "");

  let algorithm: CertificateThumbprintAlgorithm;
  if (hex.length === 40) {
    algorithm = CertificateThumbprintAlgorithm.SHA1;
  } else if (hex.length === 64) {
    algorithm = CertificateThumbprintAlgorithm.SHA256;
  } else {
    throw new BadRequestError({
      message: "Invalid thumbprint. Expected a SHA-1 (40 hex characters) or SHA-256 (64 hex characters) digest"
    });
  }

  return { algorithm, fingerprint: formatFingerprint(hex) };
};

/**
 * Parse and extract subject, fingerprints, and basicConstraints from a decrypted certificate.
 * Returns empty object on failure (graceful degradation).
 */
export const parseCertificateBody = (source: TCertificateSource): TParsedCertificateBody => {
  try {
    const certObj = toX509Certificate(source);

    // Extract subject DN attributes directly from the x509 Name object
    const parsedDn = extractDnParts(certObj.subjectName);
    const subject: TCertificateSubject = {
      commonName: parsedDn.commonName,
      organization: parsedDn.organization,
      organizationalUnit: parsedDn.ou,
      country: parsedDn.country,
      state: parsedDn.province,
      locality: parsedDn.locality
    };
    if (parsedDn.domainComponents?.length) subject.domainComponents = parsedDn.domainComponents;

    // Calculate fingerprints and format with colons (e.g., "1A:2F:73:...")
    const rawData = Buffer.from(certObj.rawData);
    const fingerprints: TCertificateFingerprints = {
      sha256: formatFingerprint(crypto.nativeCrypto.createHash("sha256").update(rawData).digest("hex")),
      sha1: formatFingerprint(crypto.nativeCrypto.createHash("sha1").update(rawData).digest("hex"))
    };

    // Extract basicConstraints extension
    let basicConstraints: { isCA: boolean; pathLength?: number } | undefined;
    const basicConstraintsExt = certObj.getExtension(x509.BasicConstraintsExtension);
    if (basicConstraintsExt) {
      basicConstraints = {
        isCA: basicConstraintsExt.ca,
        pathLength: basicConstraintsExt.pathLength
      };
    }

    let keyUsages: CertKeyUsage[] | undefined;
    const keyUsagesExt = certObj.getExtension(x509.KeyUsagesExtension);
    if (keyUsagesExt) {
      keyUsages = Object.values(CertKeyUsage).filter(
        // eslint-disable-next-line no-bitwise
        (keyUsage) => (x509.KeyUsageFlags[keyUsage] & keyUsagesExt.usages) !== 0
      );
    }

    let extendedKeyUsages: CertExtendedKeyUsage[] | undefined;
    const extendedKeyUsagesExt = certObj.getExtension(x509.ExtendedKeyUsageExtension);
    if (extendedKeyUsagesExt) {
      extendedKeyUsages = extendedKeyUsagesExt.usages
        .map((oid) => CertExtendedKeyUsageOIDToName[oid as string])
        .filter(Boolean);
    }

    return { subject, fingerprints, basicConstraints, keyUsages, extendedKeyUsages };
  } catch {
    // If we can't parse the certificate, return empty object (graceful degradation)
    return {};
  }
};

const KEY_ALGORITHM_VALUES = new Set<string>(Object.values(CertKeyAlgorithm));
const SIGNATURE_ALGORITHM_VALUES = new Set<string>(Object.values(CertSignatureAlgorithm));

const EC_CURVE_KEY_ALGORITHMS: Record<string, CertKeyAlgorithm> = {
  "P-256": CertKeyAlgorithm.ECDSA_P256,
  "P-384": CertKeyAlgorithm.ECDSA_P384,
  "P-521": CertKeyAlgorithm.ECDSA_P521
};

const RSA_KEY_ALGORITHMS: Record<number, CertKeyAlgorithm> = {
  2048: CertKeyAlgorithm.RSA_2048,
  3072: CertKeyAlgorithm.RSA_3072,
  4096: CertKeyAlgorithm.RSA_4096
};

const RSA_SIGNATURE_ALGORITHMS: Record<string, CertSignatureAlgorithm> = {
  "SHA-256": CertSignatureAlgorithm.RSA_SHA256,
  "SHA-384": CertSignatureAlgorithm.RSA_SHA384,
  "SHA-512": CertSignatureAlgorithm.RSA_SHA512
};

export const ECDSA_SIGNATURE_ALGORITHMS: Record<string, CertSignatureAlgorithm> = {
  "SHA-256": CertSignatureAlgorithm.ECDSA_SHA256,
  "SHA-384": CertSignatureAlgorithm.ECDSA_SHA384,
  "SHA-512": CertSignatureAlgorithm.ECDSA_SHA512
};

// Import accepts certificates the issuance enums do not cover, such as Ed25519 and secp256k1, so an
// unrecognised algorithm is recorded under its own name rather than rejected. The UI falls back to
// the raw value when it is not one it has a label for.
export const extractCertificateAlgorithms = (source: TCertificateSource) => {
  let certObj: x509.X509Certificate;
  try {
    certObj = toX509Certificate(source);
  } catch {
    return {};
  }

  const publicKeyAlgorithm = certObj.publicKey.algorithm as {
    name: string;
    modulusLength?: number;
    namedCurve?: string;
  };
  const signature = certObj.signatureAlgorithm as unknown as { name: string; hash?: { name: string } };
  const hashName = signature.hash?.name ?? "";

  let keyAlgorithm: string = publicKeyAlgorithm.name;
  if (publicKeyAlgorithm.name.startsWith("RSA")) {
    const bits = publicKeyAlgorithm.modulusLength;
    keyAlgorithm = (bits && RSA_KEY_ALGORITHMS[bits]) || (bits ? `RSA_${bits}` : "RSA");
  } else if (publicKeyAlgorithm.name === "ECDSA") {
    const curve = publicKeyAlgorithm.namedCurve ?? "";
    keyAlgorithm = EC_CURVE_KEY_ALGORITHMS[curve] ?? (curve ? `EC_${curve}` : "EC");
  }

  let signatureAlgorithm: string = signature.name;
  if (signature.name === "RSASSA-PKCS1-v1_5") {
    signatureAlgorithm = RSA_SIGNATURE_ALGORITHMS[hashName] ?? `RSA-${hashName || "UNKNOWN"}`;
  } else if (signature.name === "ECDSA") {
    signatureAlgorithm = ECDSA_SIGNATURE_ALGORITHMS[hashName] ?? `ECDSA-${hashName || "UNKNOWN"}`;
  }

  return { keyAlgorithm, signatureAlgorithm };
};

/**
 * Extract certificate fields including subject attributes, fingerprints, and basic constraints.
 * Returns all parsed fields as separate properties.
 */
export const extractCertificateFields = (source: TCertificateSource, resolved?: TResolvedCustomExtension[]) => {
  const parsed = parseCertificateBody(source);

  const issuedCustomExtensions = parseIssuedCustomExtensions(source, resolved);

  return {
    // Subject attributes
    subjectOrganization: parsed.subject?.organization ?? null,
    subjectOrganizationalUnit: parsed.subject?.organizationalUnit ?? null,
    subjectCountry: parsed.subject?.country ?? null,
    subjectState: parsed.subject?.state ?? null,
    subjectLocality: parsed.subject?.locality ?? null,
    // DC labels contain no commas, so a comma-joined string round-trips cleanly.
    subjectDomainComponents: parsed.subject?.domainComponents?.length
      ? parsed.subject.domainComponents.join(",")
      : null,

    // Fingerprints
    fingerprintSha256: parsed.fingerprints?.sha256 ?? null,
    fingerprintSha1: parsed.fingerprints?.sha1 ?? null,

    // Basic constraints
    isCA: parsed.basicConstraints?.isCA ?? null,
    pathLength: parsed.basicConstraints?.pathLength ?? null,

    customExtensions: issuedCustomExtensions.length ? JSON.stringify(issuedCustomExtensions) : null,

    // Callers spread these last so the issued values win over the requested ones. Absent when the
    // certificate does not carry them, leaving the requested values in place.
    ...(parsed.subject?.commonName && { commonName: parsed.subject.commonName }),
    ...(parsed.keyUsages && { keyUsages: parsed.keyUsages }),
    ...(parsed.extendedKeyUsages && { extendedKeyUsages: parsed.extendedKeyUsages })
  };
};

const extractIssuedAltNames = (issued: x509.X509Certificate): string | null => {
  try {
    const sanExtension = issued.getExtension("2.5.29.17");
    if (!sanExtension) return null;

    const { items } = new x509.GeneralNames(sanExtension.value);
    const values = [
      ...new Set(items.filter((item) => SUPPORTED_GENERAL_NAME_TYPES.has(item.type)).map((item) => item.value))
    ];

    if (items.length > values.length) {
      logger?.warn(
        `Issued certificate carries ${items.length - values.length} subject alternative name(s) of a kind this column cannot hold, so they were not recorded [serialNumber=${issued.serialNumber}]`
      );
    }

    return values.length ? values.join(",") : null;
  } catch (err) {
    logger?.warn(
      err,
      `Could not read the subject alternative names off an issued certificate [serialNumber=${issued.serialNumber}]`
    );
    return null;
  }
};

const safeExtractCertificateAlgorithms = (issued: x509.X509Certificate) => {
  try {
    const algorithms = extractCertificateAlgorithms(issued);

    const offEnum = [
      !!algorithms.keyAlgorithm && !KEY_ALGORITHM_VALUES.has(algorithms.keyAlgorithm) && algorithms.keyAlgorithm,
      !!algorithms.signatureAlgorithm &&
        !SIGNATURE_ALGORITHM_VALUES.has(algorithms.signatureAlgorithm) &&
        algorithms.signatureAlgorithm
    ].filter(Boolean);

    if (offEnum.length) {
      logger?.warn(
        `Issued certificate uses ${offEnum.join(" and ")}, which is outside the algorithms this platform can request, so a renewal cannot ask for it again [serialNumber=${issued.serialNumber}]`
      );
    }

    return algorithms;
  } catch (err) {
    logger?.warn(
      err,
      `Could not name the algorithms on an issued certificate, so the requested ones stand [serialNumber=${issued.serialNumber}]`
    );
    return {};
  }
};

export const extractExternallyIssuedCertificateFields = (
  issued: x509.X509Certificate,
  requestedCustomExtensions?: TResolvedCustomExtension[]
) => {
  const issuedCustomExtensions = parseExternallyIssuedCustomExtensions(issued, requestedCustomExtensions);
  const altNames = extractIssuedAltNames(issued);

  return {
    ...extractCertificateFields(issued),
    ...safeExtractCertificateAlgorithms(issued),
    ...(altNames !== null && { altNames }),
    serialNumber: issued.serialNumber,
    notBefore: issued.notBefore,
    notAfter: issued.notAfter,
    customExtensions: issuedCustomExtensions.length ? JSON.stringify(issuedCustomExtensions) : null
  };
};

export const resolveCertificateStatus = (certificate: {
  status: string;
  notAfter: Date;
  renewedByCertificateId?: string | null;
}): CertStatus => {
  if (certificate.status === CertStatus.REVOKED) return CertStatus.REVOKED;
  if (new Date(certificate.notAfter).getTime() <= Date.now()) return CertStatus.EXPIRED;
  if (certificate.renewedByCertificateId) return CertStatus.RENEWED;
  return CertStatus.ACTIVE;
};

type TDeletableCertificate = {
  friendlyName?: string | null;
  commonName?: string | null;
  serialNumber: string;
  deletedAt?: Date | null;
};

export const getCertificateDisplayName = (certificate: Omit<TDeletableCertificate, "deletedAt">) =>
  certificate.friendlyName || certificate.commonName || certificate.serialNumber;

export const assertCertificateNotDeleted = (
  certificate: TDeletableCertificate,
  consequence = "It can no longer be renewed or changed."
) => {
  if (!certificate.deletedAt) return;

  throw new BadRequestError({
    message: `Certificate '${getCertificateDisplayName(certificate)}' was deleted on ${new Date(certificate.deletedAt).toISOString()}. ${consequence}`
  });
};

export const assertCertificateMaterialAvailable = (certificate: TDeletableCertificate) =>
  assertCertificateNotDeleted(certificate, "Its certificate and private key are no longer available.");

export const softDeleteCertificates = async (
  { certificateIds, actorType, actorId }: { certificateIds: string[]; actorType: string; actorId?: string | null },
  {
    certificateDAL,
    certificateBodyDAL,
    certificateSecretDAL,
    certificateRequestDAL,
    pkiCollectionItemDAL,
    certificateSyncDAL
  }: {
    certificateDAL: Pick<TCertificateDALFactory, "update">;
    certificateBodyDAL: Pick<TCertificateBodyDALFactory, "delete">;
    certificateSecretDAL: Pick<TCertificateSecretDALFactory, "delete">;
    certificateRequestDAL: Pick<TCertificateRequestDALFactory, "update">;
    pkiCollectionItemDAL: Pick<TPkiCollectionItemDALFactory, "delete">;
    certificateSyncDAL: Pick<TCertificateSyncDALFactory, "find">;
  },
  tx: Knex
) => {
  if (certificateIds.length === 0) return { deletedCertificates: [], pkiSyncIdsHoldingCertificates: [] };

  const deletedCertificates = await certificateDAL.update(
    { $in: { id: certificateIds }, deletedAt: null },
    { deletedAt: new Date(), deletedByActorType: actorType, deletedByActorId: actorId ?? null },
    tx
  );
  const deletedIds = deletedCertificates.map((cert) => cert.id);
  if (deletedIds.length === 0) return { deletedCertificates, pkiSyncIdsHoldingCertificates: [] };

  await certificateBodyDAL.delete({ $in: { certId: deletedIds } }, tx);
  await certificateSecretDAL.delete({ $in: { certId: deletedIds } }, tx);
  await certificateRequestDAL.update({ $in: { certificateId: deletedIds } }, { encryptedPrivateKey: null }, tx);
  await pkiCollectionItemDAL.delete({ $in: { certId: deletedIds } }, tx);
  const syncLinks = await certificateSyncDAL.find({ $in: { certificateId: deletedIds } }, { tx });

  return {
    deletedCertificates,
    pkiSyncIdsHoldingCertificates: [...new Set(syncLinks.map((link) => link.pkiSyncId))]
  };
};

export const linkRenewedCertificate = async (
  certificateDAL: Pick<TCertificateDALFactory, "findById" | "updateById">,
  originalCertificateId: string,
  renewedCertificateId: string,
  tx?: Knex
) => {
  const originalCertificate = await certificateDAL.findById(originalCertificateId, tx);

  if (originalCertificate?.orderId) {
    await certificateDAL.updateById(renewedCertificateId, { orderId: originalCertificate.orderId }, tx);
  }

  await certificateDAL.updateById(originalCertificateId, { renewedByCertificateId: renewedCertificateId }, tx);
};