Skip to content

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

11.3 KB
Raw Blame
import RE2 from "re2";

import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { isPqcAlgorithm } from "@app/lib/crypto/pqc";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { matchesNormalizedPattern } from "@app/services/certificate-policy/certificate-policy-fns";
import { TSubjectRule } from "@app/services/certificate-policy/certificate-policy-types";
import { TProjectDALFactory } from "@app/services/project/project-dal";

import { CertExtendedKeyUsage, CertKeyUsage } from "../certificate/certificate-types";
import {
  CertExtendedKeyUsageType,
  CertKeyUsageType,
  mapExtendedKeyUsageToLegacy,
  mapKeyUsageToLegacy,
  mapLegacyExtendedKeyUsageToStandard,
  mapLegacyKeyUsageToStandard
} from "./certificate-constants";
import { assertCertificateQuota, TCertificateQuotaDeps } from "./certificate-quota-fns";

export const validatePqcLicense = async ({
  keyAlgorithm,
  projectId,
  projectDAL,
  licenseService
}: {
  keyAlgorithm: string;
  projectId: string;
  projectDAL: Pick<TProjectDALFactory, "findById">;
  licenseService: Pick<TLicenseServiceFactory, "getPlan">;
}) => {
  if (!isPqcAlgorithm(keyAlgorithm)) return;
  const project = await projectDAL.findById(projectId);
  if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
  const plan = await licenseService.getPlan(project.orgId);
  if (!plan.pkiPqc) {
    throw new BadRequestError({
      message:
        "Your license does not include PQC algorithms. Please upgrade to the Enterprise plan to use a PQC algorithm."
    });
  }
};

// Call with the request as it will actually be signed. A PQC algorithm or wildcard that only appears
// in a CSR or a profile default is invisible until applyProfileDefaults has run.
//
// Submit-time gate only; certificate-approval-fns re-checks the caps when it materializes an approval.
export const validateCertificateRequestLicense = async ({
  request,
  altNames,
  projectId,
  projectDAL,
  licenseService,
  quotaDeps,
  isRenewal = false
}: {
  request: {
    keyAlgorithm?: string;
    signatureAlgorithm?: string;
    commonName?: string;
  };
  // The SANs that will actually be issued, comma-joined as the row stores them. Passed by the caller
  // rather than read off the request: a request holds its SANs in altNames or subjectAlternativeNames
  // depending on where it came from, and applyProfileDefaults fills the unused one, so a CSR request
  // against a profile with default SANs would otherwise be keyed on names it never issues.
  altNames?: string | null;
  projectId: string;
  projectDAL: Pick<TProjectDALFactory, "findById">;
  licenseService: Pick<TLicenseServiceFactory, "getPlan">;
  // When absent the caps are skipped, so an issuance entry point that forgets it is silently uncapped.
  quotaDeps?: TCertificateQuotaDeps;
  // Nothing sets this today: renewal does not route through here. Kept because a refused renewal lets
  // a live certificate expire, so the exemption should already exist if that ever changes.
  isRenewal?: boolean;
}) => {
  const pqcAlgorithm = [request.keyAlgorithm, request.signatureAlgorithm].find(
    (algorithm): algorithm is string => !!algorithm && isPqcAlgorithm(algorithm)
  );

  const distinctSanCount = new Set(
    (altNames ?? "")
      .split(",")
      .map((value) => value.trim().toLowerCase())
      .filter(Boolean)
  ).size;

  const project = await projectDAL.findById(projectId);
  if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });

  const plan = await licenseService.getPlan(project.orgId);

  if (pqcAlgorithm && !plan.pkiPqc) {
    throw new BadRequestError({
      message:
        "Your license does not include PQC algorithms. Please upgrade to the Enterprise plan to use a PQC algorithm."
    });
  }

  const { maxSansPerCertificate } = plan;
  if (typeof maxSansPerCertificate === "number" && distinctSanCount > maxSansPerCertificate) {
    throw new BadRequestError({
      message: `This certificate requests ${distinctSanCount} subject alternative names, above the ${maxSansPerCertificate} allowed on your plan. Upgrade plan to issue certificates with more SANs.`
    });
  }

  if (!quotaDeps || isRenewal) return undefined;

  const { isNewQuotaKey, quotaOrgId, isWildcard } = await assertCertificateQuota({
    orgId: project.orgId,
    commonName: request.commonName,
    altNames,
    deps: quotaDeps
  });

  return { orgId: quotaOrgId, isNewQuotaKey, isWildcard };
};

interface CertificateRequestInput {
  keyUsages?: string[];
  extendedKeyUsages?: string[];
}

export const mapEnumsForValidation = <T extends CertificateRequestInput>(request: T): T => {
  const mapKeyUsage = (usage: string): string => {
    try {
      return mapLegacyKeyUsageToStandard(usage);
    } catch {
      return usage;
    }
  };

  const mapExtendedKeyUsage = (usage: string): string => {
    try {
      return mapLegacyExtendedKeyUsageToStandard(usage);
    } catch {
      return usage;
    }
  };

  return {
    ...request,
    keyUsages: request.keyUsages?.map(mapKeyUsage),
    extendedKeyUsages: request.extendedKeyUsages?.map(mapExtendedKeyUsage)
  } as T;
};

export const normalizeDateForApi = (date: Date | string | undefined): string | undefined => {
  if (!date) return undefined;
  return date instanceof Date ? date.toISOString() : date;
};

export const bufferToString = (data: Buffer | string): string => {
  return String(data);
};

export const buildCertificateSubjectFromTemplate = (
  request: Record<string, unknown>,
  templateAttributes?: TSubjectRule[]
): Record<string, string | undefined> => {
  const subject: Record<string, string> = {};
  const attributeMap: Record<string, string> = {
    common_name: "commonName",
    organization: "organization",
    country: "country",
    state: "state",
    locality: "locality",
    organizational_unit: "organizationalUnit"
  };

  if (!templateAttributes || templateAttributes.length === 0) {
    Object.entries(attributeMap).forEach(([attrType, requestKey]) => {
      const value = request[requestKey];
      if (value && typeof value === "string") {
        subject[attrType] = value;
      }
    });
    return subject;
  }

  templateAttributes.forEach((attr) => {
    const requestKey = attributeMap[attr.type];
    const value = request[requestKey];

    if (value && typeof value === "string" && (attr.allowed || attr.required)) {
      subject[attr.type] = value;
    }
  });

  return subject;
};

const validateValueAgainstPatterns = (value: string, patterns: string[]): boolean => {
  if (!patterns || patterns.length === 0) {
    return false;
  }

  const normalizedValue = value.toLowerCase();
  return patterns.some((pattern) => matchesNormalizedPattern(normalizedValue, pattern.toLowerCase()));
};

export const buildSubjectAlternativeNamesFromTemplate = (
  request: { subjectAlternativeNames?: Array<{ type: string; value: string }> },
  templateSans?: Array<{
    type: string;
    allowed?: string[];
    required?: string[];
    denied?: string[];
  }>
): string => {
  if (!request.subjectAlternativeNames || request.subjectAlternativeNames.length === 0) {
    return "";
  }

  if (!templateSans || templateSans.length === 0) {
    return request.subjectAlternativeNames.map((san) => san.value).join(",");
  }

  const allowedSans: string[] = [];

  request.subjectAlternativeNames.forEach((san) => {
    const templateSan = templateSans.find((template) => template.type === san.type);

    if (!templateSan) {
      allowedSans.push(san.value);
      return;
    }

    if (templateSan.denied && validateValueAgainstPatterns(san.value, templateSan.denied)) {
      throw new BadRequestError({ message: `SAN value '${san.value}' is explicitly denied for type '${san.type}'` });
    }

    const isRequired = templateSan.required && validateValueAgainstPatterns(san.value, templateSan.required);
    const isAllowed = templateSan.allowed && validateValueAgainstPatterns(san.value, templateSan.allowed);

    if (isRequired || isAllowed || (!templateSan.allowed && !templateSan.required)) {
      allowedSans.push(san.value);
    } else {
      throw new BadRequestError({ message: `SAN value '${san.value}' is not allowed for type '${san.type}'` });
    }
  });

  return allowedSans.join(",");
};

export const convertLegacyKeyUsage = (usage: CertKeyUsage): CertKeyUsageType => {
  return mapLegacyKeyUsageToStandard(usage);
};

export const convertToLegacyKeyUsage = (usage: CertKeyUsageType): CertKeyUsage => {
  return mapKeyUsageToLegacy(usage) as CertKeyUsage;
};

export const convertLegacyExtendedKeyUsage = (usage: CertExtendedKeyUsage): CertExtendedKeyUsageType => {
  return mapLegacyExtendedKeyUsageToStandard(usage);
};

export const convertToLegacyExtendedKeyUsage = (usage: CertExtendedKeyUsageType): CertExtendedKeyUsage => {
  return mapExtendedKeyUsageToLegacy(usage) as CertExtendedKeyUsage;
};

export const convertKeyUsageArrayFromLegacy = (usages?: CertKeyUsage[]): CertKeyUsageType[] | undefined => {
  return usages?.map(convertLegacyKeyUsage);
};

export const convertKeyUsageArrayToLegacy = (usages?: CertKeyUsageType[]): CertKeyUsage[] | undefined => {
  return usages?.map(convertToLegacyKeyUsage);
};

export const convertExtendedKeyUsageArrayFromLegacy = (
  usages?: CertExtendedKeyUsage[]
): CertExtendedKeyUsageType[] | undefined => {
  return usages?.map(convertLegacyExtendedKeyUsage);
};

export const convertExtendedKeyUsageArrayToLegacy = (
  usages?: CertExtendedKeyUsageType[]
): CertExtendedKeyUsage[] | undefined => {
  return usages?.map(convertToLegacyExtendedKeyUsage);
};

/**
 * Parses a PEM-formatted certificate chain and returns individual certificates
 * @param certificateChain - PEM-formatted certificate chain
 * @returns Array of individual PEM certificates
 */
const parseCertificateChain = (certificateChain: string): string[] => {
  if (!certificateChain || typeof certificateChain !== "string") {
    return [];
  }

  const certRegex = new RE2(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);
  const certificates = certificateChain.match(certRegex);

  return certificates ? certificates.map((cert) => cert.trim()) : [];
};

/**
 * Removes the root CA certificate from a certificate chain, leaving only intermediate certificates.
 * If the chain contains only the root CA certificate, returns an empty string.
 *
 * @param certificateChain - PEM-formatted certificate chain containing leaf + intermediates + root CA
 * @returns PEM-formatted certificate chain with only intermediate certificates (no root CA)
 */
export const removeRootCaFromChain = (certificateChain?: string): string => {
  if (!certificateChain || typeof certificateChain !== "string") {
    return "";
  }

  const certificates = parseCertificateChain(certificateChain);

  if (certificates.length === 0) {
    return "";
  }

  const intermediateCerts = certificates.slice(0, -1);

  return intermediateCerts.join("\n");
};

/**
 * Extracts the root CA certificate from a certificate chain.
 *
 * @param certificateChain - PEM-formatted certificate chain containing leaf + intermediates + root CA
 * @returns PEM-formatted root CA certificate, or empty string if not found
 */
export const extractRootCaFromChain = (certificateChain?: string): string => {
  if (!certificateChain || typeof certificateChain !== "string") {
    return "";
  }

  const certificates = parseCertificateChain(certificateChain);

  if (certificates.length === 0) {
    return "";
  }

  return certificates[certificates.length - 1];
};