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
fix(cert-manager): normalize damaged PEM input on certificate import
Carlos Monastyrskiea6c71501a75
diff --git a/backend/src/services/certificate/certificate-fns.test.ts b/backend/src/services/certificate/certificate-fns.test.tsindex 1afc082e63..41d45aeb8e 100644--- a/backend/src/services/certificate/certificate-fns.test.ts+++ b/backend/src/services/certificate/certificate-fns.test.ts@@ -1,4 +1,4 @@-import { webcrypto } from "node:crypto";+import { createPrivateKey, generateKeyPairSync, webcrypto } from "node:crypto";import * as x509 from "@peculiar/x509";@@ -10,6 +10,7 @@ import {CertificateThumbprintAlgorithm,extractCertificateFields,extractExternallyIssuedCertificateFields,+ normalizePemText,normalizeThumbprint,parseCertificateBody,resolveCertificateDeletionEligibility@@ -350,3 +351,46 @@ describe("resolveCertificateDeletionEligibility", () => {);});});++describe("normalizePemText", () => {+ const { privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });+ const pkcs8Pem = privateKey.export({ type: "pkcs8", format: "pem" }).toString().trim();+ const pkcs1Pem = privateKey.export({ type: "pkcs1", format: "pem" }).toString().trim();+ const lines = pkcs8Pem.split("\n");++ const damagedVariants: Record<string, string> = {+ "newlines removed": lines.join(""),+ "newlines replaced with spaces": lines.join(" "),+ "double-escaped newlines": lines.join("\\n"),+ "indented lines": lines.map((line) => ` ${line}`).join("\n"),+ "non-breaking spaces": lines.join("\n\u00a0"),+ "zero-width spaces": lines.join("\n\u200b"),+ "en dashes in the armor": pkcs8Pem.replace(/-----/g, "\u2013\u2013\u2013\u2013\u2013"),+ "blank line in the body": [...lines.slice(0, 3), "", ...lines.slice(3)].join("\n")+ };++ test.each(Object.entries(damagedVariants))("repairs a private key with %s", (_, damaged) => {+ expect(() => createPrivateKey(damaged)).toThrow();+ expect(normalizePemText(damaged)).toBe(pkcs8Pem);+ expect(() => createPrivateKey(normalizePemText(damaged))).not.toThrow();+ });++ test("canonicalizes parseable variants", () => {+ expect(normalizePemText(lines.join("\r\n"))).toBe(pkcs8Pem);+ expect(normalizePemText(`Bag Attributes\n localKeyID: 01 02\n${pkcs8Pem}`)).toBe(pkcs8Pem);+ });++ test("leaves well-formed PEM unchanged", () => {+ expect(normalizePemText(pkcs8Pem)).toBe(pkcs8Pem);+ expect(normalizePemText(pkcs1Pem)).toBe(pkcs1Pem);+ });++ test("keeps every block of a multi-block bundle in order", () => {+ const bundle = `${pkcs8Pem}\n${pkcs1Pem}`;+ expect(normalizePemText(bundle.replace(/\n/g, ""))).toBe(bundle);+ });++ test("returns trimmed input when no PEM block is found", () => {+ expect(normalizePemText(" not a pem ")).toBe("not a pem");+ });+});diff --git a/backend/src/services/certificate/certificate-fns.ts b/backend/src/services/certificate/certificate-fns.tsindex ad0ed1073f..6d36e18b28 100644--- a/backend/src/services/certificate/certificate-fns.ts+++ b/backend/src/services/certificate/certificate-fns.ts@@ -104,6 +104,30 @@ export const buildCertificateBundle = (cert: string, privateKey: string, certifireturn `${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);+ }++ return blocks.length ? blocks.join("\n") : pemText.trim();+};+export const splitPemChain = (pemText: string) => {const re2Pattern = new RE2("-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----", "g");diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.tsindex d79fa8f7e5..cd4292bb87 100644--- a/backend/src/services/certificate/certificate-service.ts+++ b/backend/src/services/certificate/certificate-service.ts@@ -93,6 +93,7 @@ import {extractCertificateFields,generatePkcs12FromCertificate,getCertificateCredentials,+ normalizePemText,normalizeThumbprint,parseCertificateBody,resolveCertificateDeletionEligibility,@@ -1148,13 +1149,16 @@ export const certificateServiceFactory = ({actor,actorOrgId,friendlyName,- certificatePem,- chainPem,- privateKeyPem,+ certificatePem: rawCertificatePem,+ chainPem: rawChainPem,+ privateKeyPem: rawPrivateKeyPem,profileId,externalMetadata}: TImportCertDTO) => {const collectionId = pkiCollectionId;+ const certificatePem = normalizePemText(rawCertificatePem);+ const chainPem = rawChainPem ? normalizePemText(rawChainPem) : rawChainPem;+ const privateKeyPem = rawPrivateKeyPem ? normalizePemText(rawPrivateKeyPem) : rawPrivateKeyPem;const resolveProjectId = async (): Promise<string> => {if (projectIdInput) return projectIdInput;@@ -1273,7 +1277,9 @@ export const certificateServiceFactory = ({try {privateKey = crypto.nativeCrypto.createPrivateKey(privateKeyPem);} catch (err) {- throw new BadRequestError({ message: "Invalid private key format" });+ throw new BadRequestError({+ message: "Invalid private key. Provide an unencrypted private key in PEM format."+ });}try {diff --git a/frontend/src/helpers/certificatePem.ts b/frontend/src/helpers/certificatePem.tsindex 761d5c56c6..5253fa92df 100644--- a/frontend/src/helpers/certificatePem.ts+++ b/frontend/src/helpers/certificatePem.ts@@ -37,9 +37,28 @@ const readAltNames = (cert: x509.X509Certificate) => {}};+const normalizePemText = (pemText: string) => {+ const cleaned = pemText+ .replace(/\\r\\n|\\n|\\r/g, "\n")+ .replace(/[\u2010-\u2015\u2212]/g, "-")+ .replace(/[\u00a0\u2007\u202f]/g, " ")+ .replace(/[\u200b-\u200d\u2060\ufeff]/g, "");++ const blocks = Array.from(+ cleaned.matchAll(/-----BEGIN ([A-Z0-9 ]+)-----([A-Za-z0-9+/=\s]*)-----END ([A-Z0-9 ]+)-----/g)+ )+ .filter(([, beginLabel, , endLabel]) => beginLabel === endLabel)+ .map(([, label, body]) => {+ const lines = body.replace(/\s/g, "").match(/.{1,64}/g) ?? [];+ return [`-----BEGIN ${label}-----`, ...lines, `-----END ${label}-----`].join("\n");+ });++ return blocks.length ? blocks.join("\n") : pemText.trim();+};+export const summarizeCertificatePem = (pem: string): TCertificatePemSummary | null => {try {- const cert = new x509.X509Certificate(pem.trim());+ const cert = new x509.X509Certificate(normalizePemText(pem));return {subject: cert.subject.slice(0, MAX_SUBJECT_LENGTH),commonName: cert.subjectName.getField("CN")[0]?.slice(0, MAX_SUBJECT_LENGTH) ?? null,