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
merging PKI PRs
x0322054efa4ad8dfc2
diff --cc backend/src/lib/api-docs/constants.tsindex fb5cca9e15,ae6bbbcab0..6ecb748c86--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@@ -1619,20 -1619,8 +1619,21 @@@ export const CERTIFICATES =serialNumber: "The serial number of the certificate to get the certificate body and certificate chain for.",certificate: "The certificate body of the certificate.",certificateChain: "The certificate chain of the certificate.",- serialNumberRes: "The serial number of the certificate."+ serialNumberRes: "The serial number of the certificate.",+ privateKey: "The private key of the certificate."+ },+ IMPORT: {+ projectSlug: "Slug of the project to import the certificate into.",+ certificatePem: "The PEM-encoded leaf certificate.",+ privateKeyPem: "The PEM-encoded private key corresponding to the certificate.",+ chainPem: "The PEM-encoded chain of intermediate certificates.",+ friendlyName: "A friendly name for the certificate.",+ pkiCollectionId: "The ID of the PKI collection to add the certificate to.",++ certificate: "The issued certificate.",+ certificateChain: "The certificate chain of the issued certificate.",+ privateKey: "The private key of the issued certificate.",+ serialNumber: "The serial number of the issued certificate."}};diff --cc backend/src/server/routes/v1/certificate-router.tsindex 271e0f7762,dad1d9a805..9a527d99dd--- a/backend/src/server/routes/v1/certificate-router.ts+++ b/backend/src/server/routes/v1/certificate-router.ts@@@ -64,6 -66,111 +66,111 @@@ export const registerCertRouter = asyn}});+ // TODO: In the future add support for other formats outside of PEM (such as DER). Adding a "format" query param may be best.+ server.route({+ method: "GET",+ url: "/:serialNumber/private-key",+ config: {+ rateLimit: readLimit+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ schema: {+ hide: false,+ tags: [ApiDocsTags.PkiCertificates],+ description: "Get certificate private key",+ params: z.object({+ serialNumber: z.string().trim().describe(CERTIFICATES.GET.serialNumber)+ }),+ response: {+ 200: z.string().trim()+ }+ },+ handler: async (req, reply) => {- const { ca, cert, certPrivateKey } = await server.services.certificate.getCertPrivateKey({++ const { cert, certPrivateKey } = await server.services.certificate.getCertPrivateKey({+ serialNumber: req.params.serialNumber,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,- projectId: ca.projectId,++ projectId: cert.projectId,+ event: {+ type: EventType.GET_CERT_PRIVATE_KEY,+ metadata: {+ certId: cert.id,+ cn: cert.commonName,+ serialNumber: cert.serialNumber+ }+ }+ });++ addNoCacheHeaders(reply);++ return certPrivateKey;+ }+ });++ // TODO: In the future add support for other formats outside of PEM (such as DER). Adding a "format" query param may be best.+ server.route({+ method: "GET",+ url: "/:serialNumber/bundle",+ config: {+ rateLimit: readLimit+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ schema: {+ hide: false,+ tags: [ApiDocsTags.PkiCertificates],+ description: "Get certificate bundle including the certificate, chain, and private key.",+ params: z.object({+ serialNumber: z.string().trim().describe(CERTIFICATES.GET_CERT.serialNumber)+ }),+ response: {+ 200: z.object({+ certificate: z.string().trim().describe(CERTIFICATES.GET_CERT.certificate),- certificateChain: z.string().trim().nullish().describe(CERTIFICATES.GET_CERT.certificateChain),++ certificateChain: z.string().trim().nullable().describe(CERTIFICATES.GET_CERT.certificateChain),+ privateKey: z.string().trim().describe(CERTIFICATES.GET_CERT.privateKey),+ serialNumber: z.string().trim().describe(CERTIFICATES.GET_CERT.serialNumberRes)+ })+ }+ },+ handler: async (req, reply) => {- const { certificate, certificateChain, serialNumber, cert, ca, privateKey } =++ const { certificate, certificateChain, serialNumber, cert, privateKey } =+ await server.services.certificate.getCertBundle({+ serialNumber: req.params.serialNumber,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,- projectId: ca.projectId,++ projectId: cert.projectId,+ event: {+ type: EventType.GET_CERT_BUNDLE,+ metadata: {+ certId: cert.id,+ cn: cert.commonName,+ serialNumber: cert.serialNumber+ }+ }+ });++ addNoCacheHeaders(reply);++ return {+ certificate,+ certificateChain,+ serialNumber,+ privateKey+ };+ }+ });+server.route({method: "POST",url: "/issue-certificate",diff --cc backend/src/services/certificate-authority/certificate-authority-service.tsindex 67903b265c,e1d7ce5cba..aa1ed07d8f--- a/backend/src/services/certificate-authority/certificate-authority-service.ts+++ b/backend/src/services/certificate-authority/certificate-authority-service.ts@@@ -1766,6 -1793,6 +1794,20 @@@ export const certificateAuthorityServicplainText: Buffer.from(new Uint8Array(leafCert.rawData))});++ const { caCert: issuingCaCertificate, caCertChain } = await getCaCertChain({++ caCertId: ca.activeCaCertId,++ certificateAuthorityDAL,++ certificateAuthorityCertDAL,++ projectDAL,++ kmsService++ });++++ const certificateChainPem = `${issuingCaCertificate}\n${caCertChain}`.trim();++++ const { cipherTextBlob: encryptedCertificateChain } = await kmsEncryptor({++ plainText: Buffer.from(certificateChainPem)++ });++await certificateDAL.transaction(async (tx) => {const cert = await certificateDAL.create({@@@ -1789,7 -1815,7 +1831,8 @@@await certificateBodyDAL.create({certId: cert.id,-- encryptedCertificate++ encryptedCertificate,++ encryptedCertificateChain},tx);@@@ -1807,17 -1833,17 +1850,9 @@@return cert;});-- const { caCert: issuingCaCertificate, caCertChain } = await getCaCertChain({-- caCertId: ca.activeCaCertId,-- certificateAuthorityDAL,-- certificateAuthorityCertDAL,-- projectDAL,-- kmsService-- });--return {certificate: leafCert,-- certificateChain: `${issuingCaCertificate}\n${caCertChain}`.trim(),++ certificateChain: certificateChainPem,issuingCaCertificate,serialNumber,ca,diff --cc backend/src/services/certificate/certificate-fns.tsindex ff4e4394aa,961fb27ff4..9fe77de218--- a/backend/src/services/certificate/certificate-fns.ts+++ b/backend/src/services/certificate/certificate-fns.ts@@@ -1,6 -1,11 +1,11 @@@+ import crypto from "node:crypto";+import * as x509 from "@peculiar/x509";- import { CrlReason } from "./certificate-types";+ import { BadRequestError, NotFoundError } from "@app/lib/errors";++ import { getProjectKmsCertificateKeyId } from "../project/project-fns";-import { CrlReason, TBuildCertificateChainDTO, TGetCertificateCredentialsDTO } from "./certificate-types";++import { CrlReason, TGetCertificateCredentialsDTO } from "./certificate-types";export const revocationReasonToCrlCode = (crlReason: CrlReason) => {switch (crlReason) {@@@ -47,5 -52,72 +52,49 @@@ export const constructPemChainFromCert.join("\n").trim();+export const splitPemChain = (pemText: string) =>+ pemText.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g) || [];+++ /**+ * Return the public and private key of certificate+ * Note: credentials are returned as PEM strings+ */+ export const getCertificateCredentials = async ({+ certId,+ projectId,+ certificateSecretDAL,+ projectDAL,+ kmsService+ }: TGetCertificateCredentialsDTO) => {+ const certificateSecret = await certificateSecretDAL.findOne({ certId });+ if (!certificateSecret)+ throw new NotFoundError({ message: `Certificate secret for certificate with ID '${certId}' not found` });++ const keyId = await getProjectKmsCertificateKeyId({+ projectId,+ projectDAL,+ kmsService+ });+ const kmsDecryptor = await kmsService.decryptWithKmsKey({+ kmsId: keyId+ });+ const decryptedPrivateKey = await kmsDecryptor({+ cipherTextBlob: certificateSecret.encryptedPrivateKey+ });++ try {+ const skObj = crypto.createPrivateKey({ key: decryptedPrivateKey, format: "pem", type: "pkcs8" });+ const certPrivateKey = skObj.export({ format: "pem", type: "pkcs8" }).toString();++ const pkObj = crypto.createPublicKey(skObj);+ const certPublicKey = pkObj.export({ format: "pem", type: "spki" }).toString();++ return {+ certificateSecret,+ certPrivateKey,+ certPublicKey+ };+ } catch (error) {+ throw new BadRequestError({ message: `Failed to process private key for certificate with ID '${certId}'` });+ }+ };--// If the certificate was generated after ~05/01/25 it will have a encryptedCertificateChain attached to it's body-// Otherwise we'll fallback to manually building the chain-export const buildCertificateChain = async ({- caCert,- caCertChain,- encryptedCertificateChain,- kmsService,- kmsId-}: TBuildCertificateChainDTO) => {- if (!encryptedCertificateChain && (!caCert || !caCertChain)) {- return null;- }-- let certificateChain = `${caCert}\n${caCertChain}`.trim();-- if (encryptedCertificateChain) {- const kmsDecryptor = await kmsService.decryptWithKmsKey({ kmsId });- const decryptedCertChain = await kmsDecryptor({- cipherTextBlob: encryptedCertificateChain- });- certificateChain = decryptedCertChain.toString();- }-- return certificateChain;-};diff --cc backend/src/services/certificate/certificate-service.tsindex aa24563493,73a8caed7a..634fe791bf--- a/backend/src/services/certificate/certificate-service.ts+++ b/backend/src/services/certificate/certificate-service.ts@@@ -1,12 -1,13 +1,15 @@@import { ForbiddenError } from "@casl/ability";import * as x509 from "@peculiar/x509";+import { createPrivateKey, createPublicKey, sign, verify } from "crypto";-import { ActionProjectType } from "@app/db/schemas";+import { ActionProjectType, ProjectType } from "@app/db/schemas";import { TCertificateAuthorityCrlDALFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-dal";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";- import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";+ import {+ ProjectPermissionCertificateActions,+ ProjectPermissionSub+ } from "@app/ee/services/permission/project-permission";+import { BadRequestError, NotFoundError } from "@app/lib/errors";import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";@@@ -19,22 -18,22 +22,26 @@@ import { TProjectDALFactory } from "@apimport { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";import { getCaCertChain, rebuildCaCrl } from "../certificate-authority/certificate-authority-fns";- import { revocationReasonToCrlCode, splitPemChain } from "./certificate-fns";-import { buildCertificateChain, getCertificateCredentials, revocationReasonToCrlCode } from "./certificate-fns";++import { getCertificateCredentials, revocationReasonToCrlCode, splitPemChain } from "./certificate-fns";+ import { TCertificateSecretDALFactory } from "./certificate-secret-dal";import {+ CertExtendedKeyUsage,+ CertExtendedKeyUsageOIDToName,+ CertKeyUsage,CertStatus,TDeleteCertDTO,TGetCertBodyDTO,+ TGetCertBundleDTO,TGetCertDTO,+ TGetCertPrivateKeyDTO,+ TImportCertDTO,TRevokeCertDTO} from "./certificate-types";type TCertificateServiceFactoryDep = {- certificateDAL: Pick<TCertificateDALFactory, "findOne" | "deleteById" | "update" | "find">;- certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne">;- certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;+ certificateDAL: Pick<TCertificateDALFactory, "findOne" | "deleteById" | "update" | "find" | "transaction" | "create">;++ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create">;+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne" | "create">;certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById">;certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findById">;certificateAuthorityCrlDAL: Pick<TCertificateAuthorityCrlDALFactory, "update">;@@@ -79,13 -73,59 +87,56 @@@ export const certificateServiceFactoryactionProjectType: ActionProjectType.CertificateManager});- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Certificates);+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionCertificateActions.Read,+ ProjectPermissionSub.Certificates+ );return {- cert,- ca+ cert};};+ /**+ * Get certificate private key.+ */+ const getCertPrivateKey = async ({+ serialNumber,+ actorId,+ actorAuthMethod,+ actor,+ actorOrgId+ }: TGetCertPrivateKeyDTO) => {+ const cert = await certificateDAL.findOne({ serialNumber });- const ca = await certificateAuthorityDAL.findById(cert.caId);++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,- projectId: ca.projectId,++ projectId: cert.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.CertificateManager+ });++ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionCertificateActions.ReadPrivateKey,+ ProjectPermissionSub.Certificates+ );++ const { certPrivateKey } = await getCertificateCredentials({+ certId: cert.id,- projectId: ca.projectId,++ projectId: cert.projectId,+ certificateSecretDAL,+ projectDAL,+ kmsService+ });++ return {- ca,+ cert,+ certPrivateKey+ };+ };+/*** Delete certificate with serial number [serialNumber]*/@@@ -205,225 -252,20 +265,251 @@@const certObj = new x509.X509Certificate(decryptedCert);- const { caCert, caCertChain } = await getCaCertChain({- caCertId: cert.caCertId,- certificateAuthorityDAL,- certificateAuthorityCertDAL,+ let certificateChain = null;+- // TODO(andrey): Update this to get certificateChain straight from the certificate body after the "store cert chain on cert body" PR gets merged- if (cert.caCertId) {++ // On newer certs the certBody.encryptedCertificateChain column will always exist.++ // Older certs will have a caCertId which will be used as a fallback mechanism for structuring the chain.++ if (certBody.encryptedCertificateChain) {++ const decryptedCertChain = await kmsDecryptor({++ cipherTextBlob: certBody.encryptedCertificateChain++ });++ certificateChain = decryptedCertChain.toString();++ } else if (cert.caCertId) {+ const { caCert, caCertChain } = await getCaCertChain({+ caCertId: cert.caCertId,+ certificateAuthorityDAL,+ certificateAuthorityCertDAL,+ projectDAL,+ kmsService+ });++ certificateChain = `${caCert}\n${caCertChain}`.trim();+ }++ return {+ certificate: certObj.toString("pem"),+ certificateChain,+ serialNumber: certObj.serialNumber,+ cert+ };+ };++ /**+ * Import certificate+ */+ const importCert = async ({+ projectSlug,+ pkiCollectionId,+ actorId,+ actorAuthMethod,+ actor,+ actorOrgId,+ friendlyName,+ certificatePem,+ chainPem,+ privateKeyPem+ }: TImportCertDTO) => {+ const collectionId = pkiCollectionId;++ const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);+ if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });+ let projectId = project.id;++ const certManagerProjectFromSplit = await projectDAL.getProjectFromSplitId(+ projectId,+ ProjectType.CertificateManager+ );+ if (certManagerProjectFromSplit) {+ projectId = certManagerProjectFromSplit.id;+ }++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.CertificateManager+ });+- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.Certificates);++ ForbiddenError.from(permission).throwUnlessCan(++ ProjectPermissionCertificateActions.Create,++ ProjectPermissionSub.Certificates++ );++ // Check PKI collection+ if (collectionId) {+ const pkiCollection = await pkiCollectionDAL.findById(collectionId);+ if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" });+ if (pkiCollection.projectId !== projectId) throw new BadRequestError({ message: "Invalid PKI collection" });+ }++ const leafCert = new x509.X509Certificate(certificatePem);++ // Verify the certificate chain+ const chainCerts = splitPemChain(chainPem).map((pem) => new x509.X509Certificate(pem));++ // Remove leaf cert from the chain if it's present+ if (chainCerts[0].equal(leafCert)) {+ chainCerts.splice(0, 1);+ }++ if (chainCerts.length === 0) {+ throw new BadRequestError({+ message: "Certificate chain must contain at least one issuer certificate"+ });+ }++ // Verify leaf certificate is signed by the first certificate in the chain+ const isLeafVerified = await leafCert.verify({ publicKey: chainCerts[0].publicKey }).catch(() => false);+ if (!isLeafVerified) {+ throw new BadRequestError({ message: "Leaf certificate verification against chain failed" });+ }++ // Verify the entire chain of trust+ const verificationPromises = chainCerts.slice(0, -1).map(async (currentCert, index) => {+ const issuerCert = chainCerts[index + 1];+ return currentCert.verify({ publicKey: issuerCert.publicKey }).catch(() => false);+ });++ const verificationResults = await Promise.all(verificationPromises);++ if (verificationResults.some((result) => !result)) {+ throw new BadRequestError({+ message: "Certificate chain verification failed: broken trust chain"+ });+ }++ // Verify private key matches the certificate+ let privateKey;+ try {+ privateKey = createPrivateKey(privateKeyPem);+ } catch (err) {+ throw new BadRequestError({ message: "Invalid private key format" });+ }++ try {+ const message = Buffer.from(Buffer.alloc(32));+ const publicKey = createPublicKey(certificatePem);+ const signature = sign(null, message, privateKey);+ const isValid = verify(null, message, publicKey, signature);++ if (!isValid) {+ throw new BadRequestError({ message: "Private key does not match certificate" });+ }+ } catch (err) {+ if (err instanceof BadRequestError) {+ throw err;+ }+ throw new BadRequestError({ message: "Error verifying private key against certificate" });+ }++ // Get certificate attributes+ const commonName = Array.from(leafCert.subjectName.getField("CN")?.values() || [])[0] || "";++ let altNames: undefined | string;+ const sanExtension = leafCert.extensions.find((ext) => ext.type === "2.5.29.17");+ if (sanExtension) {+ const sanNames = new x509.GeneralNames(sanExtension.value);+ altNames = sanNames.items.map((name) => name.value).join(", ");+ }++ const { serialNumber, notBefore, notAfter } = leafCert;++ // Encrypt certificate for storage+ const certificateManagerKeyId = await getProjectKmsCertificateKeyId({+ projectId,projectDAL,kmsService});+ const kmsEncryptor = await kmsService.encryptWithKmsKey({+ kmsId: certificateManagerKeyId+ });- const certificateChain = await buildCertificateChain({- caCert,- caCertChain,- kmsId: certificateManagerKeyId,- kmsService,- encryptedCertificateChain: certBody.encryptedCertificateChain || undefined+ const { cipherTextBlob: encryptedCertificate } = await kmsEncryptor({+ plainText: Buffer.from(certificatePem)+ });+++ const { cipherTextBlob: encryptedPrivateKey } = await kmsEncryptor({++ plainText: Buffer.from(privateKeyPem)++ });+++ // Extract Key Usage+ const keyUsagesExt = leafCert.getExtension("2.5.29.15") as x509.KeyUsagesExtension;++ let keyUsages: CertKeyUsage[] = [];+ if (keyUsagesExt) {+ keyUsages = Object.values(CertKeyUsage).filter(+ // eslint-disable-next-line no-bitwise+ (keyUsage) => (x509.KeyUsageFlags[keyUsage] & keyUsagesExt.usages) !== 0+ );+ }++ // Extract Extended Key Usage+ const extKeyUsageExt = leafCert.getExtension("2.5.29.37") as x509.ExtendedKeyUsageExtension;+ let extendedKeyUsages: CertExtendedKeyUsage[] = [];+ if (extKeyUsageExt) {+ extendedKeyUsages = extKeyUsageExt.usages.map((ekuOid) => CertExtendedKeyUsageOIDToName[ekuOid as string]);+ }+++ const { cipherTextBlob: encryptedCertificateChain } = await kmsEncryptor({++ plainText: Buffer.from(chainPem)++ });+++ const cert = await certificateDAL.transaction(async (tx) => {+ try {+ const txCert = await certificateDAL.create(+ {+ status: CertStatus.ACTIVE,+ friendlyName: friendlyName || commonName,+ commonName,+ altNames,+ serialNumber,+ notBefore,+ notAfter,+ projectId,+ keyUsages,+ extendedKeyUsages+ },+ tx+ );++ await certificateBodyDAL.create(+ {+ certId: txCert.id,- encryptedCertificate++ encryptedCertificate,++ encryptedCertificateChain++ },++ tx++ );++++ await certificateSecretDAL.create(++ {++ certId: cert.id,++ encryptedPrivateKey+ },+ tx+ );++ if (collectionId) {+ await pkiCollectionItemDAL.create(+ {+ pkiCollectionId: collectionId,+ certId: txCert.id+ },+ tx+ );+ }++ return txCert;+ } catch (error: unknown) {+ // @ts-expect-error We're expecting a database error+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ if (error?.error?.code === "23505") {+ throw new BadRequestError({ message: "Certificate serial already exists in your project" });+ }+ throw error;+ }});return {@@@ -435,11 -277,90 +521,94 @@@};};+ /**+ * Return certificate body and certificate chain for certificate with+ * serial number [serialNumber]+ */+ const getCertBundle = async ({ serialNumber, actorId, actorAuthMethod, actor, actorOrgId }: TGetCertBundleDTO) => {+ const cert = await certificateDAL.findOne({ serialNumber });- const ca = await certificateAuthorityDAL.findById(cert.caId);++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,- projectId: ca.projectId,++ projectId: cert.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.CertificateManager+ });++ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionCertificateActions.Read,+ ProjectPermissionSub.Certificates+ );+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionCertificateActions.ReadPrivateKey,+ ProjectPermissionSub.Certificates+ );++ const certBody = await certificateBodyDAL.findOne({ certId: cert.id });++ const certificateManagerKeyId = await getProjectKmsCertificateKeyId({- projectId: ca.projectId,++ projectId: cert.projectId,+ projectDAL,+ kmsService+ });++ const kmsDecryptor = await kmsService.decryptWithKmsKey({+ kmsId: certificateManagerKeyId+ });+ const decryptedCert = await kmsDecryptor({+ cipherTextBlob: certBody.encryptedCertificate+ });++ const certObj = new x509.X509Certificate(decryptedCert);+ const certificate = certObj.toString("pem");+- const { caCert, caCertChain } = await getCaCertChain({- caCertId: cert.caCertId,- certificateAuthorityDAL,- certificateAuthorityCertDAL,- projectDAL,- kmsService- });-- const certificateChain = await buildCertificateChain({- caCert,- caCertChain,- kmsId: certificateManagerKeyId,- kmsService,- encryptedCertificateChain: certBody.encryptedCertificateChain || undefined- });++ let certificateChain = null;++++ // On newer certs the certBody.encryptedCertificateChain column will always exist.++ // Older certs will have a caCertId which will be used as a fallback mechanism for structuring the chain.++ if (certBody.encryptedCertificateChain) {++ const decryptedCertChain = await kmsDecryptor({++ cipherTextBlob: certBody.encryptedCertificateChain++ });++ certificateChain = decryptedCertChain.toString();++ } else if (cert.caCertId) {++ const { caCert, caCertChain } = await getCaCertChain({++ caCertId: cert.caCertId,++ certificateAuthorityDAL,++ certificateAuthorityCertDAL,++ projectDAL,++ kmsService++ });++++ certificateChain = `${caCert}\n${caCertChain}`.trim();++ }++ const { certPrivateKey } = await getCertificateCredentials({+ certId: cert.id,- projectId: ca.projectId,++ projectId: cert.projectId,+ certificateSecretDAL,+ projectDAL,+ kmsService+ });++ return {+ certificate,+ certificateChain,+ privateKey: certPrivateKey,+ serialNumber,- cert,- ca++ cert+ };+ };+return {getCert,+ getCertPrivateKey,deleteCert,revokeCert,getCertBody,- importCert++ importCert,+ getCertBundle};};diff --cc backend/src/services/certificate/certificate-types.tsindex 79c2cc538a,ae04eae6b7..f1c79a36f1--- a/backend/src/services/certificate/certificate-types.ts+++ b/backend/src/services/certificate/certificate-types.ts@@@ -74,13 -78,26 +78,29 @@@ export type TGetCertBodyDTO =serialNumber: string;} & Omit<TProjectPermission, "projectId">;+export type TImportCertDTO = {+ projectSlug: string;++ friendlyName?: string;+ pkiCollectionId?: string;++ certificatePem: string;+ privateKeyPem: string;+ chainPem: string;+} & Omit<TProjectPermission, "projectId">;+++ export type TGetCertPrivateKeyDTO = {+ serialNumber: string;+ } & Omit<TProjectPermission, "projectId">;++ export type TGetCertBundleDTO = {+ serialNumber: string;+ } & Omit<TProjectPermission, "projectId">;++ export type TGetCertificateCredentialsDTO = {+ certId: string;+ projectId: string;+ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne">;+ projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;+ kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;+ };--export type TBuildCertificateChainDTO = {- caCert?: string;- caCertChain?: string;- encryptedCertificateChain?: Buffer;- kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey">;- kmsId: string;-};diff --cc backend/src/services/project/project-service.tsindex 66dee53310,ecc8c5a367..6e17bf489c--- a/backend/src/services/project/project-service.ts+++ b/backend/src/services/project/project-service.ts@@@ -948,11 -949,18 +949,14 @@@ export const projectServiceFactory = (actionProjectType: ActionProjectType.CertificateManager});- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Certificates);+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionCertificateActions.Read,+ ProjectPermissionSub.Certificates+ );- const cas = await certificateAuthorityDAL.find({ projectId });-const certificates = await certificateDAL.find({- $in: {- caId: cas.map((ca) => ca.id)- },+ projectId,...(friendlyName && { friendlyName }),...(commonName && { commonName })},