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
Address greptile comments
Carlos Monastyrski414e4593e6fd
diff --git a/backend/src/ee/services/pki-acme/pki-acme-service.ts b/backend/src/ee/services/pki-acme/pki-acme-service.tsindex 744708d483..705d57bb55 100644--- a/backend/src/ee/services/pki-acme/pki-acme-service.ts+++ b/backend/src/ee/services/pki-acme/pki-acme-service.ts@@ -128,6 +128,14 @@ import {*/const STALE_PROCESSING_ORDER_TIMEOUT_MS = 60 * 60 * 1000;+const assertAcmeCaSupportsCustomExtensions = (caType: CaType, count: number): void => {+ if (!count || caSupportsCapability(caType, CaCapability.CUSTOM_EXTENSIONS)) return;++ throw new AcmeBadCSRError({+ message: `Invalid CSR: ${CERTIFICATE_AUTHORITIES_TYPE_MAP[caType] ?? caType} certificate authorities cannot carry custom extensions, but this request resolved ${count} of them.`+ });+};+type TPkiAcmeServiceFactoryDep = {projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction" | "findById">;certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;@@ -1090,14 +1098,7 @@ export const pkiAcmeServiceFactory = ({if (!validationResult.isValid) {throw new AcmeBadCSRError({ message: `Invalid CSR: ${validationResult.errors.join(", ")}` });}- if (- validationResult.resolvedCustomExtensions?.length &&- !caSupportsCapability(caType, CaCapability.CUSTOM_EXTENSIONS)- ) {- throw new AcmeBadCSRError({- message: `Invalid CSR: ${CERTIFICATE_AUTHORITIES_TYPE_MAP[caType] ?? caType} certificate authorities cannot carry custom extensions, but this request resolved ${validationResult.resolvedCustomExtensions.length} of them.`- });- }+ assertAcmeCaSupportsCustomExtensions(caType, validationResult.resolvedCustomExtensions?.length ?? 0);const certRequest = await certificateRequestService.createCertificateRequest({actor: ActorType.ACME_ACCOUNT,@@ -1249,6 +1250,8 @@ export const pkiAcmeServiceFactory = ({assertCaInProfileProject(ca, profile);+ const finalizeCaType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL;+const finalizeAccount = await acmeAccountDAL.findByProjectIdAndAccountId(profile.id, accountId);const accountApplicationProfileId = (finalizeAccount as { applicationProfileId?: string | null } | null)?.applicationProfileId;@@ -1285,6 +1288,10 @@ export const pkiAcmeServiceFactory = ({if (!validationResult.isValid) {throw new AcmeBadCSRError({ message: `Invalid CSR: ${validationResult.errors.join(", ")}` });}+ assertAcmeCaSupportsCustomExtensions(+ finalizeCaType,+ validationResult.resolvedCustomExtensions?.length ?? 0+ );return {approvalPolicy: matchedApprovalPolicy,@@ -1451,7 +1458,7 @@ export const pkiAcmeServiceFactory = ({return claimedOrder;});- const caType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL;+ const caType = finalizeCaType;// Set once the certificate and its order-linked request are durably committed, which happens// inside processCertificateIssuanceForOrder rather than here. Anything that fails after that// point must not invalidate the order, or a real certificate is stranded.diff --git a/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-fns.ts b/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-fns.tsindex 07c4d35401..91b0fecd02 100644--- a/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-fns.ts+++ b/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-fns.ts@@ -33,8 +33,10 @@ import {} from "@app/services/certificate/certificate-types";import { generateLeafKeypairAndCsr } from "@app/services/certificate-common/certificate-csr-utils";import {+ findCsrCustomExtensionMismatch,findUnsatisfiedCustomExtensionOids,parseIssuedCustomExtensions,+ TCsrCustomExtensionMismatch,TResolvedCustomExtension} from "@app/services/certificate-common/certificate-extension-fns";import { calculateFinalRenewBeforeDays } from "@app/services/certificate-common/certificate-issuance-utils";@@ -504,23 +506,20 @@ export const ADCSCertificateAuthorityFns = ({let skLeaf: string | undefined;let csrDerBase64: string;if (csr) {- const csrExtensionValues = new Map(- new x509.Pkcs10CertificateRequest(csr).extensions.map((entry) => [- entry.type,- Buffer.from(new Uint8Array(entry.value)).toString("base64")- ])- );- const mismatched = (customExtensions ?? []).find(- (extension) => csrExtensionValues.get(extension.oid) !== extension.value- );- if (mismatched) {+ const parsedCsr = new x509.Pkcs10CertificateRequest(csr);+ const mismatch = findCsrCustomExtensionMismatch(parsedCsr, customExtensions);+ if (mismatch) {+ const resolvedCritical = customExtensions?.find((extension) => extension.oid === mismatch.oid)?.critical;+ const reasons: Record<TCsrCustomExtensionMismatch["reason"], string> = {+ missing: `Custom extension '${mismatch.oid}' must be present in the certificate signing request you supply`,+ value: `Custom extension '${mismatch.oid}' in the certificate signing request does not carry the value this policy resolved`,+ criticality: `Custom extension '${mismatch.oid}' in the certificate signing request must be marked ${resolvedCritical ? "critical" : "non-critical"} to match this policy`+ };throw new BadRequestError({- message: csrExtensionValues.has(mismatched.oid)- ? `Custom extension '${mismatched.oid}' in the certificate signing request does not carry the value this policy resolved, and Active Directory Certificate Services is given that request unchanged. Correct the request, or let Infisical generate the key.`- : `Custom extension '${mismatched.oid}' must be present in the certificate signing request you supply, because Active Directory Certificate Services is given that request unchanged. Include it, or let Infisical generate the key.`+ message: `${reasons[mismatch.reason]}, because Active Directory Certificate Services is given that request unchanged. Correct the request, or let Infisical generate the key.`});}- csrDerBase64 = Buffer.from(new Uint8Array(new x509.Pkcs10CertificateRequest(csr).rawData)).toString("base64");+ csrDerBase64 = Buffer.from(new Uint8Array(parsedCsr.rawData)).toString("base64");} else {const generated = await generateLeafKeypairAndCsr({subjectName: buildSubjectDN(commonName),diff --git a/backend/src/services/certificate-common/certificate-extension-fns.test.ts b/backend/src/services/certificate-common/certificate-extension-fns.test.tsindex 50ee492255..931d1e0a13 100644--- a/backend/src/services/certificate-common/certificate-extension-fns.test.ts+++ b/backend/src/services/certificate-common/certificate-extension-fns.test.ts@@ -1,4 +1,5 @@import * as x509 from "@peculiar/x509";+import * as asn1js from "asn1js";import { describe, expect, it } from "vitest";import {@@ -11,6 +12,7 @@ import {CUSTOM_EXTENSION_PRESETS_BY_OID,describeCustomExtensionValue,encodeCustomExtensionValue,+ findCsrCustomExtensionMismatch,findUnsatisfiedCustomExtensionOids,isReservedExtensionOid,parseCustomExtensionsFromCertificate,@@ -456,6 +458,67 @@ describe("parseCustomExtensionsFromCertificate", () => {});});+describe("findCsrCustomExtensionMismatch", () => {+ const CSR_OID = "1.3.6.1.4.1.77777.99";+ const der = Buffer.from(new asn1js.Utf8String({ value: "v1" }).toBER(false));+ const value = der.toString("base64");++ const csrWith = async (extensions: x509.Extension[]) => {+ const keys = await crypto.subtle.generateKey(+ { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },+ true,+ ["sign", "verify"]+ );+ return x509.Pkcs10CertificateRequestGenerator.create({+ name: "CN=mismatch-test",+ keys,+ signingAlgorithm: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },+ extensions+ });+ };++ it("accepts a request carrying the resolved value and criticality", async () => {+ const csr = await csrWith([new x509.Extension(CSR_OID, false, der)]);++ expect(findCsrCustomExtensionMismatch(csr, [{ oid: CSR_OID, value, critical: false }])).toBeNull();+ });++ it("reports an extension the request omits", async () => {+ const csr = await csrWith([]);++ expect(findCsrCustomExtensionMismatch(csr, [{ oid: CSR_OID, value, critical: false }])).toEqual({+ oid: CSR_OID,+ reason: "missing"+ });+ });++ it("reports a request whose value differs from the resolved one", async () => {+ const other = Buffer.from(new asn1js.Utf8String({ value: "v2" }).toBER(false));+ const csr = await csrWith([new x509.Extension(CSR_OID, false, other)]);++ expect(findCsrCustomExtensionMismatch(csr, [{ oid: CSR_OID, value, critical: false }])).toEqual({+ oid: CSR_OID,+ reason: "value"+ });+ });++ it("reports a request whose criticality contradicts the resolved one, since the CA gets it unchanged", async () => {+ const csr = await csrWith([new x509.Extension(CSR_OID, false, der)]);++ expect(findCsrCustomExtensionMismatch(csr, [{ oid: CSR_OID, value, critical: true }])).toEqual({+ oid: CSR_OID,+ reason: "criticality"+ });+ });++ it("accepts anything when the policy resolved no extensions", async () => {+ const csr = await csrWith([new x509.Extension(CSR_OID, true, der)]);++ expect(findCsrCustomExtensionMismatch(csr, [])).toBeNull();+ expect(findCsrCustomExtensionMismatch(csr, undefined)).toBeNull();+ });+});+describe("findUnsatisfiedCustomExtensionOids", () => {const certificateWith = async (oids: string[]) => {const keys = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]);diff --git a/backend/src/services/certificate-common/certificate-extension-fns.ts b/backend/src/services/certificate-common/certificate-extension-fns.tsindex d5ee3344f6..70ed170d7e 100644--- a/backend/src/services/certificate-common/certificate-extension-fns.ts+++ b/backend/src/services/certificate-common/certificate-extension-fns.ts@@ -270,6 +270,31 @@ export const parseIssuedCustomExtensions = (}));};+export type TCsrCustomExtensionMismatch = { oid: string; reason: "missing" | "value" | "criticality" };++export const findCsrCustomExtensionMismatch = (+ csr: x509.Pkcs10CertificateRequest,+ resolved?: TResolvedCustomExtension[]+): TCsrCustomExtensionMismatch | null => {+ if (!resolved?.length) return null;++ const inCsr = new Map(+ csr.extensions.map((entry) => [+ entry.type,+ { value: Buffer.from(new Uint8Array(entry.value)).toString("base64"), critical: entry.critical }+ ])+ );++ for (const extension of resolved) {+ const found = inCsr.get(extension.oid);+ if (!found) return { oid: extension.oid, reason: "missing" };+ if (found.value !== extension.value) return { oid: extension.oid, reason: "value" };+ if (found.critical !== extension.critical) return { oid: extension.oid, reason: "criticality" };+ }++ return null;+};+export const findUnsatisfiedCustomExtensionOids = (certificateDer: Buffer,resolved?: TResolvedCustomExtension[]