Skip to content

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

19.1 KB
Raw Blame
import * as x509 from "@peculiar/x509";

import { AuditLogInfo, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { extractX509CertFromChain } from "@app/lib/certificates/extract-certificate";
import { BadRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
import { ActorType } from "@app/services/auth/auth-type";
import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";
import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";
import {
  assertCaInProfileProject,
  getCaCertChain,
  getCaCertChains
} from "@app/services/certificate-authority/certificate-authority-fns";
import { CertificateIssuanceOperation } from "@app/services/certificate-common/certificate-constants";
import { extractCertificateRequestFromCSR } from "@app/services/certificate-common/certificate-csr-utils";
import { recordCertificateIssuanceFailure } from "@app/services/certificate-common/certificate-issuance-audit-fns";
import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
import { EnrollmentType } from "@app/services/certificate-profile/certificate-profile-types";
import { CertificateRequestStatus } from "@app/services/certificate-request/certificate-request-types";
import { resolveEffectiveTtl } from "@app/services/certificate-v3/certificate-v3-fns";
import { TCertificateV3ServiceFactory } from "@app/services/certificate-v3/certificate-v3-service";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { isCertChainValid } from "@app/services/certificate/certificate-fns";
import { CertStatus } from "@app/services/certificate/certificate-types";
import { TEstEnrollmentConfigDALFactory } from "@app/services/enrollment-config/est-enrollment-config-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TPkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";
import { TPkiApplicationProfileDALFactory } from "@app/services/pki-application/pki-application-profile-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";

import { convertRawCertsToPkcs7 } from "../../ee/services/certificate-est/certificate-est-fns";
import { TLicenseServiceFactory } from "../../ee/services/license/license-service";
import { TCertificatePolicyDALFactory } from "../certificate-policy/certificate-policy-dal";

type TCertificateEstV3ServiceFactoryDep = {
  certificateV3Service: Pick<TCertificateV3ServiceFactory, "signCertificateFromProfile">;
  certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;
  certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "find" | "findById">;
  certificateDAL: Pick<TCertificateDALFactory, "findOne" | "transaction">;
  projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
  kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;
  licenseService: Pick<TLicenseServiceFactory, "getPlan">;
  certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs">;
  estEnrollmentConfigDAL: Pick<TEstEnrollmentConfigDALFactory, "findById">;
  certificatePolicyDAL: Pick<TCertificatePolicyDALFactory, "findById">;
  pkiApplicationProfileDAL?: Pick<TPkiApplicationProfileDALFactory, "findOneByApplicationAndProfile">;
  pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;
  auditLogService: Pick<TAuditLogServiceFactory, "createCollapsedAuditLog">;
};

export type TCertificateEstV3ServiceFactory = ReturnType<typeof certificateEstV3ServiceFactory>;

export const certificateEstV3ServiceFactory = ({
  certificateV3Service,
  certificateAuthorityCertDAL,
  certificateAuthorityDAL,
  certificateDAL,
  projectDAL,
  kmsService,
  licenseService,
  certificateProfileDAL,
  estEnrollmentConfigDAL,
  certificatePolicyDAL,
  pkiApplicationProfileDAL,
  pkiApplicationDAL,
  auditLogService
}: TCertificateEstV3ServiceFactoryDep) => {
  const $recordEstFailure = async ({
    error,
    profile,
    csr,
    applicationId,
    auditLogInfo,
    operation,
    originalCertificateId
  }: {
    error: unknown;
    profile: { id: string; projectId: string; slug: string; caId?: string | null };
    csr: string;
    applicationId?: string;
    auditLogInfo?: AuditLogInfo;
    operation: CertificateIssuanceOperation;
    originalCertificateId?: string;
  }) => {
    if (!auditLogInfo) return;
    let commonName: string | undefined;
    try {
      commonName = extractCertificateRequestFromCSR(csr).commonName;
    } catch {
      commonName = undefined;
    }
    await recordCertificateIssuanceFailure(
      { auditLogService, certificateAuthorityDAL, pkiApplicationDAL },
      {
        auditLogInfo: { ...auditLogInfo, actor: { type: ActorType.EST_ACCOUNT, metadata: { profileId: profile.id } } },
        projectId: profile.projectId,
        error,
        metadata: {
          operation,
          enrollmentType: EnrollmentType.EST,
          certificateProfileId: profile.id,
          profileName: profile.slug,
          caId: profile.caId,
          commonName,
          originalCertificateId,
          applicationId
        }
      }
    );
  };

  const $resolveEstTtl = async (profile: {
    certificatePolicyId: string;
    defaults?: { ttlDays?: number | null } | null;
  }) => {
    const policy = await certificatePolicyDAL.findById(profile.certificatePolicyId);
    return resolveEffectiveTtl({
      requestTtl: undefined, // EST doesn't accept TTL in request
      profileDefaultTtlDays: profile.defaults?.ttlDays,
      policyMaxValidity: policy?.validity?.max,
      flowDefaultTtl: "90d"
    });
  };

  const resolveEstConfigId = async (
    profile: { estConfigId?: string | null },
    profileId: string,
    applicationId?: string
  ): Promise<string | null> => {
    if (applicationId && pkiApplicationProfileDAL) {
      const junction = await pkiApplicationProfileDAL.findOneByApplicationAndProfile(applicationId, profileId);
      if (!junction) {
        throw new NotFoundError({
          message: `Profile '${profileId}' is not attached to application '${applicationId}'.`
        });
      }
      return junction.estConfigId ?? null;
    }
    return profile.estConfigId ?? null;
  };
  const validateEstClientCertificate = async (
    estConfig: { disableBootstrapCaValidation?: boolean | null; encryptedCaChain?: Buffer | null },
    projectId: string,
    sslClientCert: string
  ) => {
    if (estConfig.disableBootstrapCaValidation) {
      return;
    }

    const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
      projectId,
      projectDAL,
      kmsService
    });

    const kmsDecryptor = await kmsService.decryptWithKmsKey({
      kmsId: certificateManagerKmsId
    });

    const decryptedCaChain = estConfig.encryptedCaChain
      ? (
          await kmsDecryptor({
            cipherTextBlob: estConfig.encryptedCaChain
          })
        ).toString()
      : "";

    const caCerts = extractX509CertFromChain(decryptedCaChain)?.map((cert) => {
      return new x509.X509Certificate(cert);
    });

    if (!caCerts) {
      throw new BadRequestError({ message: "Failed to parse certificate chain" });
    }

    const leafCertificate = extractX509CertFromChain(decodeURIComponent(sslClientCert))?.[0];

    if (!leafCertificate) {
      throw new UnauthorizedError({ message: "Missing client certificate" });
    }

    const certObj = new x509.X509Certificate(leafCertificate);
    if (!(await isCertChainValid([certObj, ...caCerts]))) {
      throw new BadRequestError({ message: "Invalid certificate chain" });
    }
  };

  const simpleEnrollByProfile = async ({
    csr,
    profileId,
    sslClientCert,
    applicationId,
    auditLogInfo
  }: {
    csr: string;
    profileId: string;
    sslClientCert: string;
    applicationId?: string;
    auditLogInfo?: AuditLogInfo;
  }) => {
    const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
    if (!profile) {
      throw new NotFoundError({ message: "Certificate profile not found" });
    }

    if (!applicationId && profile.enrollmentType !== EnrollmentType.EST) {
      throw new BadRequestError({ message: "Profile is not configured for EST enrollment" });
    }

    const estConfigId = await resolveEstConfigId(profile, profileId, applicationId);
    if (!estConfigId) {
      throw new BadRequestError({ message: "EST enrollment not configured for this profile" });
    }

    if (!profile.caId) {
      throw new BadRequestError({
        message: "Self-signed certificates are not supported for EST enrollment"
      });
    }

    const estConfig = await estEnrollmentConfigDAL.findById(estConfigId);
    if (!estConfig) {
      throw new NotFoundError({ message: "EST configuration not found" });
    }

    const project = await projectDAL.findOne({ id: profile.projectId });
    if (!project) {
      throw new NotFoundError({ message: "Project not found" });
    }

    const plan = await licenseService.getPlan(project.orgId);
    if (!plan.pkiEst) {
      throw new BadRequestError({
        message:
          "Failed to perform EST operation - simpleEnroll due to plan restriction. Upgrade to the Enterprise plan."
      });
    }

    await validateEstClientCertificate(estConfig, profile.projectId, sslClientCert);
    const ttl = await $resolveEstTtl(profile).catch(async (error: unknown) => {
      await $recordEstFailure({
        error,
        profile,
        csr,
        applicationId,
        auditLogInfo,
        operation: CertificateIssuanceOperation.SIGN
      });
      throw error;
    });

    const result = await certificateV3Service.signCertificateFromProfile({
      actor: ActorType.EST_ACCOUNT,
      actorId: profileId,
      actorAuthMethod: null,
      actorOrgId: project.orgId,
      profileId,
      csr,
      validity: { ttl },
      enrollmentType: EnrollmentType.EST,
      applicationId,
      auditLogInfo: auditLogInfo && {
        ...auditLogInfo,
        actor: { type: ActorType.EST_ACCOUNT, metadata: { profileId } }
      }
    });

    if (result.status === CertificateRequestStatus.PENDING_APPROVAL) {
      throw new BadRequestError({
        message: `Certificate request requires approval. Certificate Request ID: ${result.certificateRequestId}. Manage the approval request in the Infisical UI.`
      });
    }

    if (!result.certificate) {
      throw new BadRequestError({ message: "There was an error issuing the certificate" });
    }

    const certObj = new x509.X509Certificate(result.certificate);
    return convertRawCertsToPkcs7([certObj.rawData]);
  };

  const simpleReenrollByProfile = async ({
    csr,
    profileId,
    sslClientCert,
    applicationId,
    auditLogInfo
  }: {
    csr: string;
    profileId: string;
    sslClientCert: string;
    applicationId?: string;
    auditLogInfo?: AuditLogInfo;
  }) => {
    const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
    if (!profile) {
      throw new NotFoundError({ message: "Certificate profile not found" });
    }

    if (!applicationId && profile.enrollmentType !== EnrollmentType.EST) {
      throw new BadRequestError({ message: "Profile is not configured for EST enrollment" });
    }

    const estConfigId = await resolveEstConfigId(profile, profileId, applicationId);
    if (!estConfigId) {
      throw new BadRequestError({ message: "EST enrollment not configured for this profile" });
    }

    if (!profile.caId) {
      throw new BadRequestError({
        message: "Self-signed certificates are not supported for EST enrollment"
      });
    }

    const estConfig = await estEnrollmentConfigDAL.findById(estConfigId);
    if (!estConfig) {
      throw new NotFoundError({ message: "EST configuration not found" });
    }

    const project = await projectDAL.findOne({ id: profile.projectId });
    if (!project) {
      throw new NotFoundError({ message: "Project not found" });
    }

    const plan = await licenseService.getPlan(project.orgId);
    if (!plan.pkiEst) {
      throw new BadRequestError({
        message:
          "Failed to perform EST operation - simpleReenroll due to plan restriction. Upgrade to the Enterprise plan."
      });
    }

    const leafCertificate = extractX509CertFromChain(decodeURIComponent(sslClientCert))?.[0];

    if (!leafCertificate) {
      throw new UnauthorizedError({ message: "Missing client certificate" });
    }

    const cert = new x509.X509Certificate(leafCertificate);
    const caCertChains = await getCaCertChains({
      caId: profile.caId,
      certificateAuthorityCertDAL,
      certificateAuthorityDAL,
      projectDAL,
      kmsService
    });

    const verifiedChains = await Promise.all(
      caCertChains.map((chain) => {
        const caCert = new x509.X509Certificate(chain.certificate);
        const caChain = extractX509CertFromChain(chain.certificateChain)?.map((c) => new x509.X509Certificate(c)) || [];

        return isCertChainValid([cert, caCert, ...caChain]);
      })
    );

    if (!verifiedChains.some(Boolean)) {
      throw new BadRequestError({
        message: "Invalid client certificate: unable to build a valid certificate chain"
      });
    }

    // Transaction forces primary (not replica) so a just-revoked cert cannot slip through replica lag.
    const storedCert = await certificateDAL.transaction(async (tx) =>
      certificateDAL.findOne({ serialNumber: cert.serialNumber, caId: profile.caId }, tx)
    );

    if (storedCert?.status === CertStatus.REVOKED) {
      throw new UnauthorizedError({ message: "Client certificate has been revoked" });
    }

    if (storedCert?.deletedAt) {
      throw new UnauthorizedError({
        message: `Client certificate with serial number '${cert.serialNumber}' was deleted and can no longer be re-enrolled. Enroll a new certificate instead.`
      });
    }

    const $rejectReenrollCsr = async (message: string) => {
      const error = new BadRequestError({ message });
      await $recordEstFailure({
        error,
        profile,
        csr,
        applicationId,
        auditLogInfo,
        operation: CertificateIssuanceOperation.RENEW,
        originalCertificateId: storedCert?.id
      });
      return error;
    };

    const csrObj = new x509.Pkcs10CertificateRequest(csr);
    if (csrObj.subject !== cert.subject) {
      throw await $rejectReenrollCsr("Subject mismatch");
    }

    let csrSanSet: Set<string> = new Set();
    const csrSanExtension = csrObj.extensions.find((ext) => ext.type === "2.5.29.17");
    if (csrSanExtension) {
      const sanNames = new x509.GeneralNames(csrSanExtension.value);
      csrSanSet = new Set([...sanNames.items.map((name) => `${name.type}-${name.value}`)]);
    }

    let certSanSet: Set<string> = new Set();
    const certSanExtension = cert.extensions.find((ext) => ext.type === "2.5.29.17");
    if (certSanExtension) {
      const sanNames = new x509.GeneralNames(certSanExtension.value);
      certSanSet = new Set([...sanNames.items.map((name) => `${name.type}-${name.value}`)]);
    }

    if (csrSanSet.size !== certSanSet.size || ![...csrSanSet].every((element) => certSanSet.has(element))) {
      throw await $rejectReenrollCsr("Subject alternative names mismatch");
    }

    const ttl = await $resolveEstTtl(profile).catch(async (error: unknown) => {
      await $recordEstFailure({
        error,
        profile,
        csr,
        applicationId,
        auditLogInfo,
        operation: CertificateIssuanceOperation.RENEW,
        originalCertificateId: storedCert?.id
      });
      throw error;
    });

    const result = await certificateV3Service.signCertificateFromProfile({
      actor: ActorType.EST_ACCOUNT,
      actorId: profileId,
      actorAuthMethod: null,
      actorOrgId: project.orgId,
      profileId,
      csr,
      validity: { ttl },
      enrollmentType: EnrollmentType.EST,
      applicationId,
      issuanceOperation: CertificateIssuanceOperation.RENEW,
      originalCertificateId: storedCert?.id,
      auditLogInfo: auditLogInfo && {
        ...auditLogInfo,
        actor: { type: ActorType.EST_ACCOUNT, metadata: { profileId } }
      }
    });

    if (result.status === CertificateRequestStatus.PENDING_APPROVAL) {
      throw new BadRequestError({
        message: `Certificate re-enrollment request requires approval. Certificate Request ID: ${result.certificateRequestId}. Manage the approval request in the Infisical UI.`
      });
    }

    if (!result.certificate) {
      throw new BadRequestError({ message: "Certificate was not returned from issuance" });
    }

    const certObj = new x509.X509Certificate(result.certificate);
    return convertRawCertsToPkcs7([certObj.rawData]);
  };

  const getCaCertsByProfile = async ({ profileId, applicationId }: { profileId: string; applicationId?: string }) => {
    const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
    if (!profile) {
      throw new NotFoundError({ message: "Certificate profile not found" });
    }

    if (!applicationId && profile.enrollmentType !== EnrollmentType.EST) {
      throw new BadRequestError({ message: "Profile is not configured for EST enrollment" });
    }

    const estConfigId = await resolveEstConfigId(profile, profileId, applicationId);
    if (!estConfigId) {
      throw new BadRequestError({ message: "EST enrollment not configured for this profile" });
    }

    if (!profile.caId) {
      throw new BadRequestError({
        message: "Self-signed certificates are not supported for EST enrollment"
      });
    }

    const estConfig = await estEnrollmentConfigDAL.findById(estConfigId);
    if (!estConfig) {
      throw new NotFoundError({ message: "EST configuration not found" });
    }

    const project = await projectDAL.findOne({ id: profile.projectId });
    if (!project) {
      throw new NotFoundError({ message: "Project not found" });
    }

    const plan = await licenseService.getPlan(project.orgId);
    if (!plan.pkiEst) {
      throw new BadRequestError({
        message: "Failed to perform EST operation - caCerts due to plan restriction. Upgrade to the Enterprise plan."
      });
    }

    const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(profile.caId);
    if (!ca?.internalCa?.id) {
      throw new NotFoundError({
        message: `Internal Certificate Authority with ID '${profile.caId}' not found`
      });
    }

    assertCaInProfileProject(ca, profile);

    const { caCert, caCertChain } = await getCaCertChain({
      caCertId: ca.internalCa.activeCaCertId as string,
      certificateAuthorityDAL,
      certificateAuthorityCertDAL,
      projectDAL,
      kmsService
    });

    let certificates: x509.X509Certificate[] = [];
    if (caCertChain && caCertChain.trim()) {
      try {
        certificates = extractX509CertFromChain(caCertChain).map((cert) => new x509.X509Certificate(cert));
      } catch (error) {
        certificates = [];
      }
    }

    const caCertificate = new x509.X509Certificate(caCert);

    return convertRawCertsToPkcs7([caCertificate.rawData, ...certificates.map((cert) => cert.rawData)]);
  };

  return {
    simpleEnrollByProfile,
    simpleReenrollByProfile,
    getCaCertsByProfile
  };
};