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
import * as x509 from "@peculiar/x509";
import RE2 from "re2";
import { crypto } from "@app/lib/crypto/cryptography";
import { exportPqcKeyToPem, getPqcCrypto, isPqcAlgorithm, isPqcCryptoKey } from "@app/lib/crypto/pqc";
import { BadRequestError } from "@app/lib/errors";
import { ms } from "@app/lib/ms";
import { TCertificateAuthorityWithAssociatedCa } from "@app/services/certificate-authority/certificate-authority-dal";
import { CaType } from "@app/services/certificate-authority/certificate-authority-enums";
import {
createDistinguishedName,
createSerialNumber,
keyAlgorithmToAlgCfg,
signatureAlgorithmToAlgCfg
} from "@app/services/certificate-authority/certificate-authority-fns";
import { TSubjectRule } from "@app/services/certificate-policy/certificate-policy-types";
import {
CertExtendedKeyUsageNameToOID,
CertKeyAlgorithm,
CertKeyType,
CertSignatureAlgorithm
} from "@app/services/certificate/certificate-types";
import {
CERT_SUBJECT_ALTERNATIVE_NAMES,
CertExtendedKeyUsageType,
CertKeyUsageType,
CertSubjectAlternativeNameType
} from "./certificate-constants";
import { appendCustomExtensions, TResolvedCustomExtension } from "./certificate-extension-fns";
import {
bufferToString,
buildCertificateSubjectFromTemplate,
buildSubjectAlternativeNamesFromTemplate,
convertExtendedKeyUsageArrayToLegacy,
convertKeyUsageArrayToLegacy
} from "./certificate-utils";
export const parseTtlToDays = (ttl: string): number => {
const durationMs = ms(ttl);
if (!durationMs || durationMs <= 0) {
throw new BadRequestError({ message: `Invalid TTL '${ttl}'. Use a duration such as '30d', '12h', or '1y'.` });
}
return Math.ceil(durationMs / (24 * 60 * 60 * 1000));
};
/**
* Calculates the renewal threshold in days, ensuring it doesn't exceed the certificate TTL
*/
export const calculateRenewalThreshold = (
profileRenewBeforeDays: number | undefined,
certificateTtlInDays: number
): number | undefined => {
if (!profileRenewBeforeDays) {
return undefined;
}
if (certificateTtlInDays > profileRenewBeforeDays) {
return profileRenewBeforeDays;
}
return Math.max(1, certificateTtlInDays - 1);
};
/**
* Checks if the renewal timing is valid (renewal date must be at least tomorrow)
*/
export const isValidRenewalTiming = (renewBeforeDays: number, certificateExpiryDate: Date): boolean => {
const renewalDate = new Date(certificateExpiryDate.getTime() - renewBeforeDays * 24 * 60 * 60 * 1000);
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(0, 0, 0, 0);
return renewalDate >= tomorrow;
};
/**
* Calculates the final renewBeforeDays value based on profile config and certificate TTL
*/
export const calculateFinalRenewBeforeDays = (
profile: { apiConfig?: { autoRenew?: boolean; renewBeforeDays?: number } },
ttl: string,
certificateExpiryDate: Date
): number | undefined => {
if (!profile.apiConfig?.autoRenew || !profile.apiConfig.renewBeforeDays) {
return undefined;
}
const certificateTtlInDays = parseTtlToDays(ttl);
const renewBeforeDays = calculateRenewalThreshold(profile.apiConfig.renewBeforeDays, certificateTtlInDays);
if (!renewBeforeDays) {
return undefined;
}
return isValidRenewalTiming(renewBeforeDays, certificateExpiryDate) ? renewBeforeDays : undefined;
};
export const resolveRenewedCertificateRenewBeforeDays = ({
apiConfig,
previousRenewBeforeDays,
ttl,
notAfter
}: {
apiConfig?: { autoRenew?: boolean; renewBeforeDays?: number };
previousRenewBeforeDays?: number | null;
ttl: string;
notAfter: Date;
}): number | undefined => {
const desiredRenewBeforeDays =
(apiConfig?.autoRenew ? apiConfig.renewBeforeDays : undefined) ?? previousRenewBeforeDays ?? undefined;
if (!desiredRenewBeforeDays) {
return undefined;
}
const renewBeforeDays = calculateRenewalThreshold(desiredRenewBeforeDays, parseTtlToDays(ttl));
if (!renewBeforeDays) {
return undefined;
}
return isValidRenewalTiming(renewBeforeDays, notAfter) ? renewBeforeDays : undefined;
};
/**
* Resolves the effective API enrollment config for auto-renew.
* When an applicationId is present, the application-profile junction's config takes
* precedence over the profile-level config.
*/
export const resolveEffectiveApiConfig = async ({
applicationId,
profileId,
profileApiConfig,
pkiApplicationProfileDAL,
apiEnrollmentConfigDAL
}: {
applicationId?: string;
profileId: string;
profileApiConfig?: { autoRenew?: boolean; renewBeforeDays?: number };
pkiApplicationProfileDAL?: {
findOneByApplicationAndProfile: (
appId: string,
profId: string
) => Promise<{ apiConfigId?: string | null } | undefined>;
};
apiEnrollmentConfigDAL?: {
findById: (id: string) => Promise<{ autoRenew?: boolean | null; renewBeforeDays?: number | null } | undefined>;
};
}): Promise<{ autoRenew?: boolean; renewBeforeDays?: number } | undefined> => {
if (applicationId && pkiApplicationProfileDAL && apiEnrollmentConfigDAL) {
const junction = await pkiApplicationProfileDAL.findOneByApplicationAndProfile(applicationId, profileId);
if (junction?.apiConfigId) {
const appApiConfig = await apiEnrollmentConfigDAL.findById(junction.apiConfigId);
if (appApiConfig) {
return {
autoRenew: Boolean(appApiConfig.autoRenew),
renewBeforeDays: appApiConfig.renewBeforeDays ?? undefined
};
}
}
}
return profileApiConfig;
};
/**
* Validates that the CA supports the requested operation (only internal CAs support direct operations)
*/
export const validateCaSupport = (ca: TCertificateAuthorityWithAssociatedCa, operation: string): CaType => {
const caType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL;
if (caType !== CaType.INTERNAL) {
throw new BadRequestError({ message: `Only internal CAs support ${operation}` });
}
return caType;
};
/**
* A CA signs with its own key, so it can only produce signatures of that key's family. PQC keys are
* their own signature algorithm and require an exact match.
*/
export const isSignatureAlgorithmCompatibleWithCaKey = (
signatureAlgorithm: string,
caKeyAlgorithm: string
): boolean => {
if (signatureAlgorithm.startsWith("ML-DSA") || signatureAlgorithm.startsWith("SLH-DSA")) {
return signatureAlgorithm === caKeyAlgorithm;
}
const parts = signatureAlgorithm.split("-");
if (caKeyAlgorithm.startsWith("RSA")) {
return parts.includes(CertKeyType.RSA);
}
if (caKeyAlgorithm.startsWith("EC")) {
return parts.includes(CertKeyType.ECDSA);
}
return false;
};
/**
* Validates that the CA's key algorithm is compatible with the template's signature algorithms
*/
export const validateAlgorithmCompatibility = (
ca: TCertificateAuthorityWithAssociatedCa,
template: {
algorithms?: {
signature?: string[];
};
}
): void => {
if (!template.algorithms?.signature || template.algorithms.signature.length === 0) {
return;
}
const caKeyAlgorithm = ca.internalCa?.keyAlgorithm;
if (!caKeyAlgorithm) {
throw new BadRequestError({ message: "CA key algorithm not found" });
}
const compatibleAlgorithms =
template.algorithms?.signature?.filter((sigAlg: string) =>
isSignatureAlgorithmCompatibleWithCaKey(sigAlg, caKeyAlgorithm)
) || [];
if (compatibleAlgorithms.length === 0) {
throw new BadRequestError({
message: `Signature algorithms (${template.algorithms?.signature?.join(", ") || "none"}) are not compatible with CA key algorithm (${caKeyAlgorithm})`
});
}
};
/**
* Gets the effective algorithms with fallbacks
*/
export const getEffectiveAlgorithms = (
requestSignatureAlgorithm?: CertSignatureAlgorithm,
requestKeyAlgorithm?: CertKeyAlgorithm,
originalSignatureAlgorithm?: CertSignatureAlgorithm,
originalKeyAlgorithm?: CertKeyAlgorithm
): { signatureAlgorithm: CertSignatureAlgorithm; keyAlgorithm: CertKeyAlgorithm } => {
return {
signatureAlgorithm: requestSignatureAlgorithm || originalSignatureAlgorithm || CertSignatureAlgorithm.RSA_SHA256,
keyAlgorithm: requestKeyAlgorithm || originalKeyAlgorithm || CertKeyAlgorithm.RSA_2048
};
};
/**
* Combines key usage flags into a single number
*/
export const combineKeyUsageFlags = (keyUsages: string[]): number => {
return keyUsages.reduce((acc: number, usage) => {
const flag = x509.KeyUsageFlags[usage as keyof typeof x509.KeyUsageFlags];
// eslint-disable-next-line no-bitwise
return typeof flag === "number" ? acc | flag : acc;
}, 0);
};
/**
* Extracts certificate PEM string from various buffer formats
*/
export const extractCertificateFromBuffer = (certData: Buffer | { rawData: Buffer } | string): string => {
if (typeof certData === "string") return certData;
if (Buffer.isBuffer(certData)) return bufferToString(certData);
if (certData && typeof certData === "object" && "rawData" in certData && Buffer.isBuffer(certData.rawData)) {
return bufferToString(certData.rawData);
}
return bufferToString(certData as unknown as Buffer);
};
/**
* Detects the SAN type based on the value format
*/
export const detectSanType = (value: string): { type: CertSubjectAlternativeNameType; value: string } => {
const isIpv4 = new RE2("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$").test(value);
const isIpv6 = new RE2("^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$").test(value);
if (isIpv4 || isIpv6) {
return {
type: CertSubjectAlternativeNameType.IP_ADDRESS,
value
};
}
if (new RE2("^[^@]+@[^@]+\\.[^@]+$").test(value)) {
return {
type: CertSubjectAlternativeNameType.EMAIL,
value
};
}
if (new RE2("^[a-zA-Z][a-zA-Z0-9+.-]*:").test(value)) {
return {
type: CertSubjectAlternativeNameType.URI,
value
};
}
return {
type: CertSubjectAlternativeNameType.DNS_NAME,
value
};
};
export type TSelfSignedCertificateRequest = {
commonName?: string;
organization?: string;
organizationalUnit?: string;
country?: string;
state?: string;
locality?: string;
domainComponents?: string[];
keyUsages?: CertKeyUsageType[];
extendedKeyUsages?: CertExtendedKeyUsageType[];
altNames?: Array<{
type: CertSubjectAlternativeNameType;
value: string;
}>;
validity: { ttl: string };
notBefore?: Date;
notAfter?: Date;
};
export type TCertificatePolicy = {
subject?: TSubjectRule[];
sans?: Array<{
type: string;
allowed?: string[];
required?: string[];
denied?: string[];
}>;
};
export type TSelfSignedCertificateResult = {
certificate: Buffer;
privateKey: Buffer;
serialNumber: string;
notBefore: Date;
notAfter: Date;
certificateSubject: Record<string, unknown>;
subjectAlternativeNames: Array<{
type: CertSubjectAlternativeNameType;
value: string;
}>;
};
/**
* Generates a self-signed certificate
*/
export const generateSelfSignedCertificate = async ({
certificateRequest,
policy,
effectiveSignatureAlgorithm,
effectiveKeyAlgorithm,
existingKeyPair,
customExtensions
}: {
certificateRequest: TSelfSignedCertificateRequest;
policy?: TCertificatePolicy | null;
effectiveSignatureAlgorithm: CertSignatureAlgorithm;
effectiveKeyAlgorithm: CertKeyAlgorithm;
existingKeyPair?: CryptoKeyPair;
customExtensions?: TResolvedCustomExtension[];
}): Promise<TSelfSignedCertificateResult> => {
const certificateSubject = buildCertificateSubjectFromTemplate(certificateRequest, policy?.subject);
const subjectAlternativeNames = buildSubjectAlternativeNamesFromTemplate(
{ subjectAlternativeNames: certificateRequest.altNames },
policy?.sans
);
if (isPqcAlgorithm(effectiveKeyAlgorithm) && certificateRequest.keyUsages?.length) {
const invalidForPqc = [
CertKeyUsageType.KEY_ENCIPHERMENT,
CertKeyUsageType.KEY_AGREEMENT,
CertKeyUsageType.DATA_ENCIPHERMENT
];
const requested = certificateRequest.keyUsages.filter((ku) => invalidForPqc.includes(ku));
if (requested.length > 0) {
throw new BadRequestError({
message: `Key usages ${requested.join(", ")} are not valid for PQC signature-only algorithms`
});
}
}
const keyGenAlg = keyAlgorithmToAlgCfg(effectiveKeyAlgorithm);
const keyGenCrypto = isPqcAlgorithm(effectiveKeyAlgorithm) ? getPqcCrypto() : crypto.nativeCrypto;
const keyPair =
existingKeyPair ??
(await keyGenCrypto.subtle.generateKey(keyGenAlg as RsaHashedKeyGenParams, true, ["sign", "verify"]));
const signatureAlgorithmConfig = signatureAlgorithmToAlgCfg(effectiveSignatureAlgorithm, effectiveKeyAlgorithm);
const notBeforeDate = certificateRequest.notBefore ? new Date(certificateRequest.notBefore) : new Date();
let notAfterDate: Date;
if (certificateRequest.notAfter) {
notAfterDate = new Date(certificateRequest.notAfter);
} else if (certificateRequest.validity.ttl) {
notAfterDate = new Date(new Date().getTime() + ms(certificateRequest.validity.ttl));
} else {
throw new BadRequestError({
message: "Either notAfter date or TTL must be provided for certificate validity"
});
}
const serialNumber = createSerialNumber();
const dn = createDistinguishedName({
commonName: certificateRequest.commonName,
organization: certificateRequest.organization,
ou: certificateRequest.organizationalUnit,
country: certificateRequest.country,
province: certificateRequest.state,
locality: certificateRequest.locality,
domainComponents: certificateRequest.domainComponents
});
const selfSignedExtensions: x509.Extension[] = [
new x509.BasicConstraintsExtension(false, undefined, false),
...(certificateRequest.keyUsages?.length
? [
new x509.KeyUsagesExtension(
combineKeyUsageFlags(convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || []),
false
)
]
: []),
...(certificateRequest.extendedKeyUsages?.length
? [
new x509.ExtendedKeyUsageExtension(
(convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || []).map(
(eku) => CertExtendedKeyUsageNameToOID[eku]
),
false
)
]
: []),
...(subjectAlternativeNames
? [
new x509.SubjectAlternativeNameExtension(
certificateRequest.altNames?.map((san) => {
const generalNameType = CERT_SUBJECT_ALTERNATIVE_NAMES[san.type]?.generalNameType;
if (!generalNameType) {
throw new BadRequestError({
message: `Unsupported Subject Alternative Name type: ${san.type as string}`
});
}
return { type: generalNameType, value: san.value };
}) || [],
false
)
]
: [])
];
appendCustomExtensions(selfSignedExtensions, customExtensions);
const cert = await x509.X509CertificateGenerator.createSelfSigned({
name: dn,
serialNumber,
notBefore: notBeforeDate,
notAfter: notAfterDate,
signingAlgorithm: signatureAlgorithmConfig,
keys: keyPair,
extensions: selfSignedExtensions
});
const certificatePem = cert.toString("pem");
let privateKeyPem: string;
if (isPqcCryptoKey(keyPair.privateKey)) {
privateKeyPem = await exportPqcKeyToPem(keyPair.privateKey);
} else {
const privateKeyObj = crypto.nativeCrypto.KeyObject.from(keyPair.privateKey);
privateKeyPem = privateKeyObj.export({ format: "pem", type: "pkcs8" }) as string;
}
return {
certificate: Buffer.from(certificatePem),
privateKey: Buffer.from(privateKeyPem),
serialNumber,
notBefore: notBeforeDate,
notAfter: notAfterDate,
certificateSubject,
subjectAlternativeNames: certificateRequest.altNames || []
};
};
// Strip hyphens from a UUID to produce a 32-char token that
// satisfies AWS's IdempotencyToken constraints (max 32 chars, alphanumeric).
export const buildIdempotencyToken = (id: string) => id.split("-").join("").slice(0, 32);