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
get certificate private key endpoint + migrations
xe81c49500bca
diff --git a/backend/src/db/migrations/20250429232917_store-cert-secret-key-and-chain.ts b/backend/src/db/migrations/20250429232917_store-cert-secret-key-and-chain.tsnew file mode 100644index 0000000000..2062f9a38d--- /dev/null+++ b/backend/src/db/migrations/20250429232917_store-cert-secret-key-and-chain.ts@@ -0,0 +1,33 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ if (await knex.schema.hasTable(TableName.CertificateBody)) {+ await knex.schema.alterTable(TableName.CertificateBody, (t) => {+ t.binary("encryptedCertificateChain").nullable();+ });+ }++ if (!(await knex.schema.hasTable(TableName.CertificateSecret))) {+ await knex.schema.createTable(TableName.CertificateSecret, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.timestamps(true, true, true);+ t.uuid("certId").notNullable().unique();+ t.foreign("certId").references("id").inTable(TableName.Certificate).onDelete("CASCADE");+ t.binary("encryptedPrivateKey").notNullable();+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ if (await knex.schema.hasTable(TableName.Certificate)) {+ await knex.schema.dropTable(TableName.CertificateSecret);+ }++ if (await knex.schema.hasTable(TableName.CertificateBody)) {+ await knex.schema.alterTable(TableName.CertificateBody, (t) => {+ t.dropColumn("encryptedCertificateChain");+ });+ }+}diff --git a/backend/src/db/schemas/certificate-bodies.ts b/backend/src/db/schemas/certificate-bodies.tsindex 75afbddbdb..10171e3837 100644--- a/backend/src/db/schemas/certificate-bodies.ts+++ b/backend/src/db/schemas/certificate-bodies.ts@@ -14,7 +14,8 @@ export const CertificateBodiesSchema = z.object({createdAt: z.date(),updatedAt: z.date(),certId: z.string().uuid(),- encryptedCertificate: zodBuffer+ encryptedCertificate: zodBuffer,+ encryptedCertificateChain: zodBuffer.nullable().optional()});export type TCertificateBodies = z.infer<typeof CertificateBodiesSchema>;diff --git a/backend/src/db/schemas/certificate-secrets.ts b/backend/src/db/schemas/certificate-secrets.tsindex f8cad74f14..75e6377b29 100644--- a/backend/src/db/schemas/certificate-secrets.ts+++ b/backend/src/db/schemas/certificate-secrets.ts@@ -5,6 +5,8 @@import { z } from "zod";+import { zodBuffer } from "@app/lib/zod";+import { TImmutableDBKeys } from "./models";export const CertificateSecretsSchema = z.object({@@ -12,8 +14,7 @@ export const CertificateSecretsSchema = z.object({createdAt: z.date(),updatedAt: z.date(),certId: z.string().uuid(),- pk: z.string(),- sk: z.string()+ encryptedPrivateKey: zodBuffer});export type TCertificateSecrets = z.infer<typeof CertificateSecretsSchema>;diff --git a/backend/src/db/schemas/organizations.ts b/backend/src/db/schemas/organizations.tsindex 902c564a7e..eea1808e06 100644--- a/backend/src/db/schemas/organizations.ts+++ b/backend/src/db/schemas/organizations.ts@@ -23,7 +23,6 @@ export const OrganizationsSchema = z.object({defaultMembershipRole: z.string().default("member"),enforceMfa: z.boolean().default(false),selectedMfaMethod: z.string().nullable().optional(),- secretShareSendToAnyone: z.boolean().default(true).nullable().optional(),allowSecretSharingOutsideOrganization: z.boolean().default(true).nullable().optional(),shouldUseNewPrivilegeSystem: z.boolean().default(true),privilegeUpgradeInitiatedByUsername: z.string().nullable().optional(),diff --git a/backend/src/db/schemas/projects.ts b/backend/src/db/schemas/projects.tsindex 2403d6cf49..297601fd06 100644--- a/backend/src/db/schemas/projects.ts+++ b/backend/src/db/schemas/projects.ts@@ -27,7 +27,7 @@ export const ProjectsSchema = z.object({description: z.string().nullable().optional(),type: z.string(),enforceCapitalization: z.boolean().default(false),- hasDeleteProtection: z.boolean().default(true).nullable().optional()+ hasDeleteProtection: z.boolean().default(false).nullable().optional()});export type TProjects = z.infer<typeof ProjectsSchema>;diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.tsindex ea33e948f6..42c5157952 100644--- a/backend/src/server/routes/v1/certificate-router.ts+++ b/backend/src/server/routes/v1/certificate-router.ts@@ -64,6 +64,51 @@ export const registerCertRouter = async (server: FastifyZodProvider) => {}});+ // TODO(andrey): In the future add support for other formats outside of PEM. 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) => {+ const { ca, 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,+ event: {+ type: EventType.GET_CERT,+ metadata: {+ certId: cert.id,+ cn: cert.commonName,+ serialNumber: cert.serialNumber+ }+ }+ });++ return certPrivateKey;+ }+ });+server.route({method: "POST",url: "/issue-certificate",diff --git a/backend/src/services/certificate/certificate-fns.ts b/backend/src/services/certificate/certificate-fns.tsindex 45ad5963c8..55b731bd77 100644--- a/backend/src/services/certificate/certificate-fns.ts+++ b/backend/src/services/certificate/certificate-fns.ts@@ -1,6 +1,11 @@+import crypto from "node:crypto";+import * as x509 from "@peculiar/x509";-import { CrlReason } from "./certificate-types";+import { NotFoundError } from "@app/lib/errors";++import { getProjectKmsCertificateKeyId } from "../project/project-fns";+import { CrlReason, TGetCertificateCredentialsDTO } from "./certificate-types";export const revocationReasonToCrlCode = (crlReason: CrlReason) => {switch (crlReason) {@@ -46,3 +51,44 @@ export const constructPemChainFromCerts = (certificates: x509.X509Certificate[]).map((cert) => cert.toString("pem")).join("\n").trim();++/**+ * 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+ });++ const skObj = crypto.createPrivateKey({ key: decryptedPrivateKey, format: "der", 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+ };+};diff --git a/backend/src/services/certificate/certificate-secret-dal.ts b/backend/src/services/certificate/certificate-secret-dal.tsnew file mode 100644index 0000000000..d7f3e43aea--- /dev/null+++ b/backend/src/services/certificate/certificate-secret-dal.ts@@ -0,0 +1,10 @@+import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { ormify } from "@app/lib/knex";++export type TCertificateSecretDALFactory = ReturnType<typeof certificateSecretDALFactory>;++export const certificateSecretDALFactory = (db: TDbClient) => {+ const caSecretOrm = ormify(db, TableName.CertificateSecret);+ return caSecretOrm;+};diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.tsindex 0ca0d64c61..d72235781f 100644--- a/backend/src/services/certificate/certificate-service.ts+++ b/backend/src/services/certificate/certificate-service.ts@@ -15,11 +15,13 @@ import { TProjectDALFactory } from "@app/services/project/project-dal";import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";import { getCaCertChain, rebuildCaCrl } from "../certificate-authority/certificate-authority-fns";-import { revocationReasonToCrlCode } from "./certificate-fns";+import { getCertificateCredentials, revocationReasonToCrlCode } from "./certificate-fns";+import { TCertificateSecretDALFactory } from "./certificate-secret-dal";import { CertStatus, TDeleteCertDTO, TGetCertBodyDTO, TGetCertDTO, TRevokeCertDTO } from "./certificate-types";type TCertificateServiceFactoryDep = {certificateDAL: Pick<TCertificateDALFactory, "findOne" | "deleteById" | "update" | "find">;+ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne">;certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById">;certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findById">;@@ -34,6 +36,7 @@ export type TCertificateServiceFactory = ReturnType<typeof certificateServiceFacexport const certificateServiceFactory = ({certificateDAL,+ certificateSecretDAL,certificateBodyDAL,certificateAuthorityDAL,certificateAuthorityCertDAL,@@ -67,6 +70,40 @@ export const certificateServiceFactory = ({};};+ /**+ * Get certificate private key.+ */+ const getCertPrivateKey = async ({ serialNumber, actorId, actorAuthMethod, actor, actorOrgId }: TGetCertDTO) => {+ const cert = await certificateDAL.findOne({ serialNumber });+ const ca = await certificateAuthorityDAL.findById(cert.caId);++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: ca.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.CertificateManager+ });++ // TODO(andrey): Update permission for privateKey fetching. Should be very strict.+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Certificates);++ const { certPrivateKey } = await getCertificateCredentials({+ certId: ca.id,+ projectId: ca.projectId,+ certificateSecretDAL,+ projectDAL,+ kmsService+ });++ return {+ ca,+ cert,+ certPrivateKey+ };+ };+/*** Delete certificate with serial number [serialNumber]*/@@ -203,6 +240,7 @@ export const certificateServiceFactory = ({return {getCert,+ getCertPrivateKey,deleteCert,revokeCert,getCertBodydiff --git a/backend/src/services/certificate/certificate-types.ts b/backend/src/services/certificate/certificate-types.tsindex ef63f142d3..48454f8035 100644--- a/backend/src/services/certificate/certificate-types.ts+++ b/backend/src/services/certificate/certificate-types.ts@@ -2,6 +2,10 @@ import * as x509 from "@peculiar/x509";import { TProjectPermission } from "@app/lib/types";+import { TKmsServiceFactory } from "../kms/kms-service";+import { TProjectDALFactory } from "../project/project-dal";+import { TCertificateSecretDALFactory } from "./certificate-secret-dal";+export enum CertStatus {ACTIVE = "active",REVOKED = "revoked"@@ -73,3 +77,11 @@ export type TRevokeCertDTO = {export type TGetCertBodyDTO = {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">;+};