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
Greptile fix
Carlos Monastyrskicfd9e9442e01
diff --git a/backend/src/services/certificate/certificate-fns.test.ts b/backend/src/services/certificate/certificate-fns.test.tsindex 41d45aeb8e..bb2dde4088 100644--- a/backend/src/services/certificate/certificate-fns.test.ts+++ b/backend/src/services/certificate/certificate-fns.test.ts@@ -13,6 +13,7 @@ import {normalizePemText,normalizeThumbprint,parseCertificateBody,+ parsePemCertificateChain,resolveCertificateDeletionEligibility} from "./certificate-fns";import { CertExtendedKeyUsage, CertificateDeletionEligibility, CertKeyUsage, CertStatus } from "./certificate-types";@@ -393,4 +394,43 @@ describe("normalizePemText", () => {test("returns trimmed input when no PEM block is found", () => {expect(normalizePemText(" not a pem ")).toBe("not a pem");});++ test("returns the input untouched when any block cannot be rebuilt", () => {+ const damagedSecond = `${pkcs8Pem}\n${pkcs1Pem.replace("END RSA PRIVATE KEY", "END PRIVATE KEY")}`;+ expect(normalizePemText(` ${damagedSecond} `)).toBe(damagedSecond);+ });+});++describe("parsePemCertificateChain", () => {+ beforeAll(() => {+ x509.cryptoProvider.set(webcrypto as unknown as Crypto);+ });++ const makeCertPem = async (commonName: string) => {+ const keys = await webcrypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]);+ const cert = await x509.X509CertificateGenerator.createSelfSigned({+ name: `CN=${commonName}`,+ keys: keys as CryptoKeyPair,+ signingAlgorithm: { name: "ECDSA", hash: "SHA-256" },+ notBefore: new Date(),+ notAfter: new Date(Date.now() + 86_400_000)+ });+ return cert.toString("pem");+ };++ test("parses every certificate in the chain", async () => {+ const chain = `${await makeCertPem("Intermediate")}\n${await makeCertPem("Root")}`;+ expect(parsePemCertificateChain(chain)?.map((cert) => cert.subject)).toEqual(["CN=Intermediate", "CN=Root"]);+ });++ test("rejects a chain with a block that does not split out", async () => {+ const root = (await makeCertPem("Root")).replace("END CERTIFICATE", "END X509 CERTIFICATE");+ expect(parsePemCertificateChain(`${await makeCertPem("Intermediate")}\n${root}`)).toBeNull();+ });++ test("rejects a chain with a block that does not parse", async () => {+ const rootLines = (await makeCertPem("Root")).split("\n");+ rootLines[2] = `${rootLines[2].slice(0, 5)}!${rootLines[2].slice(6)}`;+ expect(parsePemCertificateChain(`${await makeCertPem("Intermediate")}\n${rootLines.join("\n")}`)).toBeNull();+ });});diff --git a/backend/src/services/certificate/certificate-fns.ts b/backend/src/services/certificate/certificate-fns.tsindex 6d36e18b28..613d356d01 100644--- a/backend/src/services/certificate/certificate-fns.ts+++ b/backend/src/services/certificate/certificate-fns.ts@@ -125,7 +125,8 @@ export const normalizePemText = (pemText: string) => {match = blockPattern.exec(cleaned);}- return blocks.length ? blocks.join("\n") : pemText.trim();+ const beginMarkerCount = (cleaned.match(/-----BEGIN /g) ?? []).length;+ return blocks.length && blocks.length === beginMarkerCount ? blocks.join("\n") : pemText.trim();};export const splitPemChain = (pemText: string) => {@@ -134,6 +135,17 @@ export const splitPemChain = (pemText: string) => {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 stringsdiff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.tsindex cd4292bb87..6a619d4ce2 100644--- a/backend/src/services/certificate/certificate-service.ts+++ b/backend/src/services/certificate/certificate-service.ts@@ -96,9 +96,9 @@ import {normalizePemText,normalizeThumbprint,parseCertificateBody,+ parsePemCertificateChain,resolveCertificateDeletionEligibility,- revocationReasonToCrlCode,- splitPemChain+ revocationReasonToCrlCode} from "./certificate-fns";import { TCertificateSecretDALFactory } from "./certificate-secret-dal";import {@@ -1237,7 +1237,13 @@ export const certificateServiceFactory = ({// Verify the certificate chain when one is providedif (chainPem) {- const chainCerts = splitPemChain(chainPem).map((pem) => new x509.X509Certificate(pem));+ const chainCerts = parsePemCertificateChain(chainPem);+ if (!chainCerts) {+ throw new BadRequestError({+ message:+ "The certificate chain contains a block that is not a valid certificate. Paste each certificate in full, including its BEGIN and END lines."+ });+ }// Remove leaf cert from the chain if it's presentif (chainCerts[0]?.equal(leafCert)) {diff --git a/frontend/src/helpers/certificatePem.ts b/frontend/src/helpers/certificatePem.tsindex 5253fa92df..f8816fa02b 100644--- a/frontend/src/helpers/certificatePem.ts+++ b/frontend/src/helpers/certificatePem.ts@@ -53,7 +53,8 @@ const normalizePemText = (pemText: string) => {return [`-----BEGIN ${label}-----`, ...lines, `-----END ${label}-----`].join("\n");});- return blocks.length ? blocks.join("\n") : pemText.trim();+ const beginMarkerCount = (cleaned.match(/-----BEGIN /g) ?? []).length;+ return blocks.length && blocks.length === beginMarkerCount ? blocks.join("\n") : pemText.trim();};export const summarizeCertificatePem = (pem: string): TCertificatePemSummary | null => {