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
feat: add auto kmip setup for org
Sheen Capadngan004e310dc84c
diff --git a/backend/src/ee/routes/v1/kmip-router.ts b/backend/src/ee/routes/v1/kmip-router.tsindex b7f5384ff1..537b343cf8 100644--- a/backend/src/ee/routes/v1/kmip-router.ts+++ b/backend/src/ee/routes/v1/kmip-router.ts@@ -295,86 +295,6 @@ export const registerKmipRouter = async (server: FastifyZodProvider) => {}});- server.route({- method: "POST",- url: "/",- config: {- rateLimit: writeLimit- },- schema: {- body: z.object({- caKeyAlgorithm: z.nativeEnum(CertKeyAlgorithm)- }),- response: {- 200: z.object({- serverCertificateChain: z.string(),- clientCertificateChain: z.string()- })- }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async (req) => {- const chains = await server.services.kmip.setupOrgKmip({- actor: req.permission.type,- actorId: req.permission.id,- actorAuthMethod: req.permission.authMethod,- actorOrgId: req.permission.orgId,- ...req.body- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- event: {- type: EventType.SETUP_KMIP,- metadata: {- keyAlgorithm: req.body.caKeyAlgorithm- }- }- });-- return chains;- }- });-- server.route({- method: "GET",- url: "/",- config: {- rateLimit: readLimit- },- schema: {- response: {- 200: z.object({- serverCertificateChain: z.string(),- clientCertificateChain: z.string()- })- }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async (req) => {- const kmip = await server.services.kmip.getOrgKmip({- actor: req.permission.type,- actorId: req.permission.id,- actorAuthMethod: req.permission.authMethod,- actorOrgId: req.permission.orgId- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- event: {- type: EventType.GET_KMIP,- metadata: {- id: kmip.id- }- }- });-- return kmip;- }- });-server.route({method: "POST",url: "/server-registration",diff --git a/backend/src/ee/services/kmip/kmip-service.ts b/backend/src/ee/services/kmip/kmip-service.tsindex 482eb41be7..43a439fe2f 100644--- a/backend/src/ee/services/kmip/kmip-service.ts+++ b/backend/src/ee/services/kmip/kmip-service.ts@@ -2,8 +2,9 @@ import { ForbiddenError } from "@casl/ability";import * as x509 from "@peculiar/x509";import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";+import { PgSqlLock } from "@app/keystore/keystore";import { crypto } from "@app/lib/crypto/cryptography";-import { BadRequestError, InternalServerError, NotFoundError } from "@app/lib/errors";+import { BadRequestError, NotFoundError } from "@app/lib/errors";import { isValidIp } from "@app/lib/ip";import { ms } from "@app/lib/ms";import { isFQDN } from "@app/lib/validator/validate-url";@@ -30,10 +31,8 @@ import {TDeleteKmipClientDTO,TGenerateOrgKmipServerCertificateDTO,TGetKmipClientDTO,- TGetOrgKmipDTO,TListKmipClientsByProjectIdDTO,TRegisterServerDTO,- TSetupOrgKmipDTO,TUpdateKmipClientDTO} from "./kmip-types";@@ -58,6 +57,199 @@ export const kmipServiceFactory = ({kmipOrgServerCertificateDAL,licenseService}: TKmipServiceFactoryDep) => {+ const DEFAULT_CA_KEY_ALGORITHM = CertKeyAlgorithm.RSA_2048;++ /**+ * Initializes and returns the KMIP PKI CA hierarchy for an organization.+ * If the org config already exists, returns it. Otherwise, creates the full PKI hierarchy+ * (Root CA, Server Intermediate CA, Client Intermediate CA) within a transaction with advisory lock.+ */+ const $getOrgKmipCAs = async (orgId: string, caKeyAlgorithm: CertKeyAlgorithm = DEFAULT_CA_KEY_ALGORITHM) => {+ const { encryptor: orgKmsEncryptor, decryptor: orgKmsDecryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.Organization,+ orgId+ });++ const kmipOrgConfig = await kmipOrgConfigDAL.transaction(async (tx) => {+ const existingConfig = await kmipOrgConfigDAL.findOne({ orgId }, tx);+ if (existingConfig) return existingConfig;++ // Acquire advisory lock to prevent race conditions during initialization+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.OrgKmipInit(orgId)]);++ // Double-check after acquiring lock+ const configAfterLock = await kmipOrgConfigDAL.findOne({ orgId }, tx);+ if (configAfterLock) return configAfterLock;++ const alg = keyAlgorithmToAlgCfg(caKeyAlgorithm);++ // generate root CA+ const rootCaSerialNumber = createSerialNumber();+ const rootCaKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);+ const rootCaSkObj = crypto.nativeCrypto.KeyObject.from(rootCaKeys.privateKey);+ const rootCaIssuedAt = new Date();+ const rootCaExpiration = new Date(new Date().setFullYear(new Date().getFullYear() + 20));++ const rootCaCert = await x509.X509CertificateGenerator.createSelfSigned({+ name: `CN=KMIP Root CA,OU=${orgId}`,+ serialNumber: rootCaSerialNumber,+ notBefore: rootCaIssuedAt,+ notAfter: rootCaExpiration,+ signingAlgorithm: alg,+ keys: rootCaKeys,+ extensions: [+ // eslint-disable-next-line no-bitwise+ new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true),+ await x509.SubjectKeyIdentifierExtension.create(rootCaKeys.publicKey)+ ]+ });++ // generate intermediate server CA+ const serverIntermediateCaSerialNumber = createSerialNumber();+ const serverIntermediateCaIssuedAt = new Date();+ const serverIntermediateCaExpiration = new Date(new Date().setFullYear(new Date().getFullYear() + 10));+ const serverIntermediateCaKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);+ const serverIntermediateCaSkObj = crypto.nativeCrypto.KeyObject.from(serverIntermediateCaKeys.privateKey);++ const serverIntermediateCaCert = await x509.X509CertificateGenerator.create({+ serialNumber: serverIntermediateCaSerialNumber,+ subject: `CN=KMIP Server Intermediate CA,OU=${orgId}`,+ issuer: rootCaCert.subject,+ notBefore: serverIntermediateCaIssuedAt,+ notAfter: serverIntermediateCaExpiration,+ signingKey: rootCaKeys.privateKey,+ publicKey: serverIntermediateCaKeys.publicKey,+ signingAlgorithm: alg,+ extensions: [+ new x509.KeyUsagesExtension(+ // eslint-disable-next-line no-bitwise+ x509.KeyUsageFlags.keyCertSign |+ x509.KeyUsageFlags.cRLSign |+ x509.KeyUsageFlags.digitalSignature |+ x509.KeyUsageFlags.keyEncipherment,+ true+ ),+ new x509.BasicConstraintsExtension(true, 0, true),+ await x509.AuthorityKeyIdentifierExtension.create(rootCaCert, false),+ await x509.SubjectKeyIdentifierExtension.create(serverIntermediateCaKeys.publicKey)+ ]+ });++ // generate intermediate client CA+ const clientIntermediateCaSerialNumber = createSerialNumber();+ const clientIntermediateCaIssuedAt = new Date();+ const clientIntermediateCaExpiration = new Date(new Date().setFullYear(new Date().getFullYear() + 10));+ const clientIntermediateCaKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);+ const clientIntermediateCaSkObj = crypto.nativeCrypto.KeyObject.from(clientIntermediateCaKeys.privateKey);++ const clientIntermediateCaCert = await x509.X509CertificateGenerator.create({+ serialNumber: clientIntermediateCaSerialNumber,+ subject: `CN=KMIP Client Intermediate CA,OU=${orgId}`,+ issuer: rootCaCert.subject,+ notBefore: clientIntermediateCaIssuedAt,+ notAfter: clientIntermediateCaExpiration,+ signingKey: rootCaKeys.privateKey,+ publicKey: clientIntermediateCaKeys.publicKey,+ signingAlgorithm: alg,+ extensions: [+ new x509.KeyUsagesExtension(+ // eslint-disable-next-line no-bitwise+ x509.KeyUsageFlags.keyCertSign |+ x509.KeyUsageFlags.cRLSign |+ x509.KeyUsageFlags.digitalSignature |+ x509.KeyUsageFlags.keyEncipherment,+ true+ ),+ new x509.BasicConstraintsExtension(true, 0, true),+ await x509.AuthorityKeyIdentifierExtension.create(rootCaCert, false),+ await x509.SubjectKeyIdentifierExtension.create(clientIntermediateCaKeys.publicKey)+ ]+ });++ return kmipOrgConfigDAL.create(+ {+ orgId,+ caKeyAlgorithm,+ rootCaIssuedAt,+ rootCaExpiration,+ rootCaSerialNumber,+ encryptedRootCaCertificate: orgKmsEncryptor({ plainText: Buffer.from(rootCaCert.rawData) }).cipherTextBlob,+ encryptedRootCaPrivateKey: orgKmsEncryptor({+ plainText: rootCaSkObj.export({+ type: "pkcs8",+ format: "der"+ })+ }).cipherTextBlob,+ serverIntermediateCaIssuedAt,+ serverIntermediateCaExpiration,+ serverIntermediateCaSerialNumber,+ encryptedServerIntermediateCaCertificate: orgKmsEncryptor({+ plainText: Buffer.from(new Uint8Array(serverIntermediateCaCert.rawData))+ }).cipherTextBlob,+ encryptedServerIntermediateCaChain: orgKmsEncryptor({ plainText: Buffer.from(rootCaCert.toString("pem")) })+ .cipherTextBlob,+ encryptedServerIntermediateCaPrivateKey: orgKmsEncryptor({+ plainText: serverIntermediateCaSkObj.export({+ type: "pkcs8",+ format: "der"+ })+ }).cipherTextBlob,+ clientIntermediateCaIssuedAt,+ clientIntermediateCaExpiration,+ clientIntermediateCaSerialNumber,+ encryptedClientIntermediateCaCertificate: orgKmsEncryptor({+ plainText: Buffer.from(new Uint8Array(clientIntermediateCaCert.rawData))+ }).cipherTextBlob,+ encryptedClientIntermediateCaChain: orgKmsEncryptor({ plainText: Buffer.from(rootCaCert.toString("pem")) })+ .cipherTextBlob,+ encryptedClientIntermediateCaPrivateKey: orgKmsEncryptor({+ plainText: clientIntermediateCaSkObj.export({+ type: "pkcs8",+ format: "der"+ })+ }).cipherTextBlob+ },+ tx+ );+ });++ // Decrypt and return the CA certificates and keys+ const rootCaCertificate = orgKmsDecryptor({ cipherTextBlob: kmipOrgConfig.encryptedRootCaCertificate });+ const rootCaPrivateKey = orgKmsDecryptor({ cipherTextBlob: kmipOrgConfig.encryptedRootCaPrivateKey });++ const serverIntermediateCaCertificate = orgKmsDecryptor({+ cipherTextBlob: kmipOrgConfig.encryptedServerIntermediateCaCertificate+ });+ const serverIntermediateCaPrivateKey = orgKmsDecryptor({+ cipherTextBlob: kmipOrgConfig.encryptedServerIntermediateCaPrivateKey+ });+ const serverIntermediateCaChain = orgKmsDecryptor({+ cipherTextBlob: kmipOrgConfig.encryptedServerIntermediateCaChain+ });++ const clientIntermediateCaCertificate = orgKmsDecryptor({+ cipherTextBlob: kmipOrgConfig.encryptedClientIntermediateCaCertificate+ });+ const clientIntermediateCaPrivateKey = orgKmsDecryptor({+ cipherTextBlob: kmipOrgConfig.encryptedClientIntermediateCaPrivateKey+ });+ const clientIntermediateCaChain = orgKmsDecryptor({+ cipherTextBlob: kmipOrgConfig.encryptedClientIntermediateCaChain+ });++ return {+ config: kmipOrgConfig,+ rootCaCertificate,+ rootCaPrivateKey,+ serverIntermediateCaCertificate,+ serverIntermediateCaPrivateKey,+ serverIntermediateCaChain,+ clientIntermediateCaCertificate,+ clientIntermediateCaPrivateKey,+ clientIntermediateCaChain+ };+ };+const createKmipClient = async ({actor,actorId,@@ -267,24 +459,10 @@ export const kmipServiceFactory = ({ProjectPermissionSub.Kmip);- const kmipConfig = await kmipOrgConfigDAL.findOne({- orgId: actorOrgId- });-- if (!kmipConfig) {- throw new InternalServerError({- message: "KMIP has not been configured for the organization"- });- }-- const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId: actorOrgId- });+ // Lazily initialize KMIP org config if not already set up+ const orgKmipCAs = await $getOrgKmipCAs(actorOrgId);- const caCertObj = new x509.X509Certificate(- decryptor({ cipherTextBlob: kmipConfig.encryptedClientIntermediateCaCertificate })- );+ const caCertObj = new x509.X509Certificate(orgKmipCAs.clientIntermediateCaCertificate);const notBeforeDate = new Date();const notAfterDate = new Date(new Date().getTime() + ms(ttl));@@ -322,10 +500,10 @@ export const kmipServiceFactory = ({new x509.ExtendedKeyUsageExtension([x509.ExtendedKeyUsage[CertExtendedKeyUsage.CLIENT_AUTH]], true)];- const caAlg = keyAlgorithmToAlgCfg(kmipConfig.caKeyAlgorithm as CertKeyAlgorithm);+ const caAlg = keyAlgorithmToAlgCfg(orgKmipCAs.config.caKeyAlgorithm as CertKeyAlgorithm);const caSkObj = crypto.nativeCrypto.createPrivateKey({- key: decryptor({ cipherTextBlob: kmipConfig.encryptedClientIntermediateCaPrivateKey }),+ key: orgKmipCAs.clientIntermediateCaPrivateKey,format: "der",type: "pkcs8"});@@ -353,10 +531,8 @@ export const kmipServiceFactory = ({const skLeafObj = crypto.nativeCrypto.KeyObject.from(leafKeys.privateKey);- const rootCaCert = new x509.X509Certificate(decryptor({ cipherTextBlob: kmipConfig.encryptedRootCaCertificate }));- const serverIntermediateCaCert = new x509.X509Certificate(- decryptor({ cipherTextBlob: kmipConfig.encryptedServerIntermediateCaCertificate })- );+ const rootCaCert = new x509.X509Certificate(orgKmipCAs.rootCaCertificate);+ const serverIntermediateCaCert = new x509.X509Certificate(orgKmipCAs.serverIntermediateCaCertificate);await kmipClientCertificateDAL.create({kmipClientId: clientId,@@ -400,213 +576,6 @@ export const kmipServiceFactory = ({};};- const setupOrgKmip = async ({ caKeyAlgorithm, actorOrgId, actor, actorId, actorAuthMethod }: TSetupOrgKmipDTO) => {- const { permission } = await permissionService.getOrgPermission({- scope: OrganizationActionScope.Any,- actor,- actorId,- orgId: actorOrgId,- actorAuthMethod,- actorOrgId- });- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionKmipActions.Setup, OrgPermissionSubjects.Kmip);-- const kmipConfig = await kmipOrgConfigDAL.findOne({- orgId: actorOrgId- });-- if (kmipConfig) {- throw new BadRequestError({- message: "KMIP has already been configured for the organization"- });- }-- const plan = await licenseService.getPlan(actorOrgId);- if (!plan.kmip)- throw new BadRequestError({- message: "Failed to setup KMIP. Upgrade your plan to enterprise."- });-- const alg = keyAlgorithmToAlgCfg(caKeyAlgorithm);-- // generate root CA- const rootCaSerialNumber = createSerialNumber();- const rootCaKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);- const rootCaSkObj = crypto.nativeCrypto.KeyObject.from(rootCaKeys.privateKey);- const rootCaIssuedAt = new Date();- const rootCaExpiration = new Date(new Date().setFullYear(new Date().getFullYear() + 20));-- const rootCaCert = await x509.X509CertificateGenerator.createSelfSigned({- name: `CN=KMIP Root CA,OU=${actorOrgId}`,- serialNumber: rootCaSerialNumber,- notBefore: rootCaIssuedAt,- notAfter: rootCaExpiration,- signingAlgorithm: alg,- keys: rootCaKeys,- extensions: [- // eslint-disable-next-line no-bitwise- new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true),- await x509.SubjectKeyIdentifierExtension.create(rootCaKeys.publicKey)- ]- });-- // generate intermediate server CA- const serverIntermediateCaSerialNumber = createSerialNumber();- const serverIntermediateCaIssuedAt = new Date();- const serverIntermediateCaExpiration = new Date(new Date().setFullYear(new Date().getFullYear() + 10));- const serverIntermediateCaKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);- const serverIntermediateCaSkObj = crypto.nativeCrypto.KeyObject.from(serverIntermediateCaKeys.privateKey);-- const serverIntermediateCaCert = await x509.X509CertificateGenerator.create({- serialNumber: serverIntermediateCaSerialNumber,- subject: `CN=KMIP Server Intermediate CA,OU=${actorOrgId}`,- issuer: rootCaCert.subject,- notBefore: serverIntermediateCaIssuedAt,- notAfter: serverIntermediateCaExpiration,- signingKey: rootCaKeys.privateKey,- publicKey: serverIntermediateCaKeys.publicKey,- signingAlgorithm: alg,- extensions: [- new x509.KeyUsagesExtension(- // eslint-disable-next-line no-bitwise- x509.KeyUsageFlags.keyCertSign |- x509.KeyUsageFlags.cRLSign |- x509.KeyUsageFlags.digitalSignature |- x509.KeyUsageFlags.keyEncipherment,- true- ),- new x509.BasicConstraintsExtension(true, 0, true),- await x509.AuthorityKeyIdentifierExtension.create(rootCaCert, false),- await x509.SubjectKeyIdentifierExtension.create(serverIntermediateCaKeys.publicKey)- ]- });-- // generate intermediate client CA- const clientIntermediateCaSerialNumber = createSerialNumber();- const clientIntermediateCaIssuedAt = new Date();- const clientIntermediateCaExpiration = new Date(new Date().setFullYear(new Date().getFullYear() + 10));- const clientIntermediateCaKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);- const clientIntermediateCaSkObj = crypto.nativeCrypto.KeyObject.from(clientIntermediateCaKeys.privateKey);-- const clientIntermediateCaCert = await x509.X509CertificateGenerator.create({- serialNumber: clientIntermediateCaSerialNumber,- subject: `CN=KMIP Client Intermediate CA,OU=${actorOrgId}`,- issuer: rootCaCert.subject,- notBefore: clientIntermediateCaIssuedAt,- notAfter: clientIntermediateCaExpiration,- signingKey: rootCaKeys.privateKey,- publicKey: clientIntermediateCaKeys.publicKey,- signingAlgorithm: alg,- extensions: [- new x509.KeyUsagesExtension(- // eslint-disable-next-line no-bitwise- x509.KeyUsageFlags.keyCertSign |- x509.KeyUsageFlags.cRLSign |- x509.KeyUsageFlags.digitalSignature |- x509.KeyUsageFlags.keyEncipherment,- true- ),- new x509.BasicConstraintsExtension(true, 0, true),- await x509.AuthorityKeyIdentifierExtension.create(rootCaCert, false),- await x509.SubjectKeyIdentifierExtension.create(clientIntermediateCaKeys.publicKey)- ]- });-- const { encryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId: actorOrgId- });-- await kmipOrgConfigDAL.create({- orgId: actorOrgId,- caKeyAlgorithm,- rootCaIssuedAt,- rootCaExpiration,- rootCaSerialNumber,- encryptedRootCaCertificate: encryptor({ plainText: Buffer.from(rootCaCert.rawData) }).cipherTextBlob,- encryptedRootCaPrivateKey: encryptor({- plainText: rootCaSkObj.export({- type: "pkcs8",- format: "der"- })- }).cipherTextBlob,- serverIntermediateCaIssuedAt,- serverIntermediateCaExpiration,- serverIntermediateCaSerialNumber,- encryptedServerIntermediateCaCertificate: encryptor({- plainText: Buffer.from(new Uint8Array(serverIntermediateCaCert.rawData))- }).cipherTextBlob,- encryptedServerIntermediateCaChain: encryptor({ plainText: Buffer.from(rootCaCert.toString("pem")) })- .cipherTextBlob,- encryptedServerIntermediateCaPrivateKey: encryptor({- plainText: serverIntermediateCaSkObj.export({- type: "pkcs8",- format: "der"- })- }).cipherTextBlob,- clientIntermediateCaIssuedAt,- clientIntermediateCaExpiration,- clientIntermediateCaSerialNumber,- encryptedClientIntermediateCaCertificate: encryptor({- plainText: Buffer.from(new Uint8Array(clientIntermediateCaCert.rawData))- }).cipherTextBlob,- encryptedClientIntermediateCaChain: encryptor({ plainText: Buffer.from(rootCaCert.toString("pem")) })- .cipherTextBlob,- encryptedClientIntermediateCaPrivateKey: encryptor({- plainText: clientIntermediateCaSkObj.export({- type: "pkcs8",- format: "der"- })- }).cipherTextBlob- });-- return {- serverCertificateChain: constructPemChainFromCerts([serverIntermediateCaCert, rootCaCert]),- clientCertificateChain: constructPemChainFromCerts([clientIntermediateCaCert, rootCaCert])- };- };-- const getOrgKmip = async ({ actorOrgId, actor, actorId, actorAuthMethod }: TGetOrgKmipDTO) => {- await permissionService.getOrgPermission({- scope: OrganizationActionScope.Any,- actor,- actorId,- orgId: actorOrgId,- actorAuthMethod,- actorOrgId- });-- const kmipConfig = await kmipOrgConfigDAL.findOne({- orgId: actorOrgId- });-- if (!kmipConfig) {- throw new BadRequestError({- message: "KMIP has not been configured for the organization"- });- }-- const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId: actorOrgId- });-- const rootCaCert = new x509.X509Certificate(decryptor({ cipherTextBlob: kmipConfig.encryptedRootCaCertificate }));- const serverIntermediateCaCert = new x509.X509Certificate(- decryptor({ cipherTextBlob: kmipConfig.encryptedServerIntermediateCaCertificate })- );-- const clientIntermediateCaCert = new x509.X509Certificate(- decryptor({ cipherTextBlob: kmipConfig.encryptedClientIntermediateCaCertificate })- );-- return {- id: kmipConfig.id,- serverCertificateChain: constructPemChainFromCerts([serverIntermediateCaCert, rootCaCert]),- clientCertificateChain: constructPemChainFromCerts([clientIntermediateCaCert, rootCaCert])- };- };-const generateOrgKmipServerCertificate = async ({orgId,ttl,@@ -614,30 +583,21 @@ export const kmipServiceFactory = ({altNames,keyAlgorithm}: TGenerateOrgKmipServerCertificateDTO) => {- const kmipOrgConfig = await kmipOrgConfigDAL.findOne({- orgId- });-- if (!kmipOrgConfig) {- throw new BadRequestError({- message: "KMIP has not been configured for the organization"- });- }-const plan = await licenseService.getPlan(orgId);if (!plan.kmip)throw new BadRequestError({message: "Failed to generate KMIP server certificate. Upgrade your plan to enterprise."});- const { decryptor, encryptor } = await kmsService.createCipherPairWithDataKey({+ // Initialize KMIP org config (or return existing one)+ const orgKmipCAs = await $getOrgKmipCAs(orgId);++ const { encryptor } = await kmsService.createCipherPairWithDataKey({type: KmsDataKey.Organization,orgId});- const caCertObj = new x509.X509Certificate(- decryptor({ cipherTextBlob: kmipOrgConfig.encryptedServerIntermediateCaCertificate })- );+ const caCertObj = new x509.X509Certificate(orgKmipCAs.serverIntermediateCaCertificate);const notBeforeDate = new Date();const notAfterDate = new Date(new Date().getTime() + ms(ttl));@@ -701,14 +661,12 @@ export const kmipServiceFactory = ({const altNamesExtension = new x509.SubjectAlternativeNameExtension(altNamesArray, false);extensions.push(altNamesExtension);- const caAlg = keyAlgorithmToAlgCfg(kmipOrgConfig.caKeyAlgorithm as CertKeyAlgorithm);+ const caAlg = keyAlgorithmToAlgCfg(orgKmipCAs.config.caKeyAlgorithm as CertKeyAlgorithm);- const decryptedCaCertChain = decryptor({- cipherTextBlob: kmipOrgConfig.encryptedServerIntermediateCaChain- }).toString("utf-8");+ const decryptedCaCertChain = orgKmipCAs.serverIntermediateCaChain.toString("utf-8");const caSkObj = crypto.nativeCrypto.createPrivateKey({- key: decryptor({ cipherTextBlob: kmipOrgConfig.encryptedServerIntermediateCaPrivateKey }),+ key: orgKmipCAs.serverIntermediateCaPrivateKey,format: "der",type: "pkcs8"});@@ -778,36 +736,26 @@ export const kmipServiceFactory = ({ForbiddenError.from(permission).throwUnlessCan(OrgPermissionKmipActions.Proxy, OrgPermissionSubjects.Kmip);- const kmipConfig = await kmipOrgConfigDAL.findOne({- orgId: actorOrgId- });-- if (!kmipConfig) {- throw new BadRequestError({- message: "KMIP has not been configured for the organization"- });- }-const plan = await licenseService.getPlan(actorOrgId);if (!plan.kmip)throw new BadRequestError({message: "Failed to register KMIP server. Upgrade your plan to enterprise."});+ // Initialize KMIP org config (or return existing one)+ const orgKmipCAs = await $getOrgKmipCAs(actorOrgId);+const { privateKey, certificate, certificateChain, serialNumber } = await generateOrgKmipServerCertificate({orgId: actorOrgId,commonName: commonName ?? "kmip-server",altNames: hostnamesOrIps,- keyAlgorithm: keyAlgorithm ?? (kmipConfig.caKeyAlgorithm as CertKeyAlgorithm),+ keyAlgorithm: keyAlgorithm ?? (orgKmipCAs.config.caKeyAlgorithm as CertKeyAlgorithm),ttl});- const { clientCertificateChain } = await getOrgKmip({- actor,- actorAuthMethod,- actorId,- actorOrgId- });+ const rootCaCert = new x509.X509Certificate(orgKmipCAs.rootCaCertificate);+ const clientIntermediateCaCert = new x509.X509Certificate(orgKmipCAs.clientIntermediateCaCertificate);+ const clientCertificateChain = constructPemChainFromCerts([clientIntermediateCaCert, rootCaCert]);return {serverCertificateSerialNumber: serialNumber,@@ -825,9 +773,7 @@ export const kmipServiceFactory = ({getKmipClient,listKmipClientsByProjectId,createKmipClientCertificate,- setupOrgKmip,generateOrgKmipServerCertificate,- getOrgKmip,getServerCertificateBySerialNumber,registerServer};diff --git a/backend/src/ee/services/kmip/kmip-types.ts b/backend/src/ee/services/kmip/kmip-types.tsindex 695f469424..b6ef70a221 100644--- a/backend/src/ee/services/kmip/kmip-types.ts+++ b/backend/src/ee/services/kmip/kmip-types.ts@@ -81,12 +81,6 @@ export type TKmipRegisterDTO = {kmipMetadata?: Record<string, unknown> | null;} & KmipOperationBaseDTO;-export type TSetupOrgKmipDTO = {- caKeyAlgorithm: CertKeyAlgorithm;-} & Omit<TOrgPermission, "orgId">;--export type TGetOrgKmipDTO = Omit<TOrgPermission, "orgId">;-export type TGenerateOrgKmipServerCertificateDTO = {commonName: string;altNames: string;diff --git a/backend/src/ee/services/permission/org-permission.ts b/backend/src/ee/services/permission/org-permission.tsindex 0c00c8b408..75bf508235 100644--- a/backend/src/ee/services/permission/org-permission.ts+++ b/backend/src/ee/services/permission/org-permission.ts@@ -33,8 +33,7 @@ export enum OrgPermissionAuditLogsActions {}export enum OrgPermissionKmipActions {- Proxy = "proxy",- Setup = "setup"+ Proxy = "proxy"}export enum OrgPermissionMachineIdentityAuthTemplateActions {@@ -432,8 +431,6 @@ const buildAdminPermission = () => {can(OrgPermissionAdminConsoleAction.AccessAllProjects, OrgPermissionSubjects.AdminConsole);- can(OrgPermissionKmipActions.Setup, OrgPermissionSubjects.Kmip);-// the proxy assignment is temporary in order to prevent "more privilege" error during role assignment to MIcan(OrgPermissionKmipActions.Proxy, OrgPermissionSubjects.Kmip);diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 5533ca4296..119a618b29 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -24,6 +24,7 @@ export const PgSqlLock = {InstanceRelayConfigInit: () => pgAdvisoryLockHashText("instance-relay-config-init"),OrgGatewayV2Init: (orgId: string) => pgAdvisoryLockHashText(`org-gateway-v2-init:${orgId}`),OrgRelayConfigInit: (orgId: string) => pgAdvisoryLockHashText(`org-relay-config-init:${orgId}`),+ OrgKmipInit: (orgId: string) => pgAdvisoryLockHashText(`org-kmip-init:${orgId}`),GatewayPamSessionKey: (gatewayId: string) => pgAdvisoryLockHashText(`gateway-pam-session-key:${gatewayId}`),IdentityLogin: (identityId: string, nonce: string) => pgAdvisoryLockHashText(`identity-login:${identityId}:${nonce}`),PamResourceSshCaInit: (resourceId: string) => pgAdvisoryLockHashText(`pam-resource-ssh-ca-init:${resourceId}`),diff --git a/docs/documentation/platform/kms/kmip.mdx b/docs/documentation/platform/kms/kmip.mdxindex d82269447e..2c23f62821 100644--- a/docs/documentation/platform/kms/kmip.mdx+++ b/docs/documentation/platform/kms/kmip.mdx@@ -56,23 +56,6 @@ Ensure the following network connectivity is in place:Follow these steps in order to set up KMIP integration with Infisical:<Steps>- <Step title="Enable KMIP at the Organization Level">- First, you need to enable KMIP for your entire Infisical organization and set up its PKI infrastructure.-- Navigate to **Organization Settings > KMIP** and click **Setup KMIP**.-- -- In the modal, select the desired key algorithm to use for the KMIP PKI of your organization, then click **Continue**.-- -- This generates the KMIP PKI for your organization, creating the cryptographic foundation that will be used for secure KMIP communications.- <Info>- You do not need to manage these certificates yourself; Infisical handles the PKI infrastructure for you.- </Info>- </Step>-<Step title="Create a Machine Identity for the KMIP Server">The KMIP server needs a machine identity to authenticate with Infisical and proxy requests on behalf of clients.diff --git a/frontend/src/context/OrgPermissionContext/types.ts b/frontend/src/context/OrgPermissionContext/types.tsindex 87dc402631..ea5f0a283c 100644--- a/frontend/src/context/OrgPermissionContext/types.ts+++ b/frontend/src/context/OrgPermissionContext/types.ts@@ -87,8 +87,7 @@ export enum OrgPermissionAuditLogsActions {}export enum OrgPermissionKmipActions {- Proxy = "proxy",- Setup = "setup"+ Proxy = "proxy"}export enum OrgPermissionIdentityActions {diff --git a/frontend/src/hooks/api/kmip/mutation.ts b/frontend/src/hooks/api/kmip/mutation.tsindex af86c1fe0e..7e42dc0501 100644--- a/frontend/src/hooks/api/kmip/mutation.ts+++ b/frontend/src/hooks/api/kmip/mutation.ts@@ -8,7 +8,6 @@ import {TCreateKmipClient,TDeleteKmipClient,TGenerateKmipClientCertificate,- TSetupOrgKmipDTO,TUpdateKmipClient} from "./types";@@ -76,15 +75,3 @@ export const useGenerateKmipClientCertificate = () => {}});};--export const useSetupOrgKmip = (orgId: string) => {- const queryClient = useQueryClient();- return useMutation({- mutationFn: async (payload: TSetupOrgKmipDTO) => {- await apiRequest.post("/api/v1/kmip", payload);- },- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: kmipKeys.getOrgKmip(orgId) });- }- });-};diff --git a/frontend/src/hooks/api/kmip/queries.tsx b/frontend/src/hooks/api/kmip/queries.tsxindex f734420a4f..9417ced0b3 100644--- a/frontend/src/hooks/api/kmip/queries.tsx+++ b/frontend/src/hooks/api/kmip/queries.tsx@@ -3,17 +3,11 @@ import { useQuery, UseQueryOptions } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";import { OrderByDirection } from "../generic/types";-import {- KmipClientOrderBy,- OrgKmipConfig,- TListProjectKmipClientsDTO,- TProjectKmipClientList-} from "./types";+import { KmipClientOrderBy, TListProjectKmipClientsDTO, TProjectKmipClientList } from "./types";export const kmipKeys = {getKmipClientsByProjectId: ({ projectId, ...filters }: TListProjectKmipClientsDTO) =>- [projectId, filters] as const,- getOrgKmip: (orgId: string) => [{ orgId }, "org-kmip-config"] as const+ [projectId, filters] as const};export const useGetKmipClientsByProjectId = (@@ -57,13 +51,3 @@ export const useGetKmipClientsByProjectId = (});};-export const useGetOrgKmipConfig = (orgId: string) => {- return useQuery({- queryKey: kmipKeys.getOrgKmip(orgId),- queryFn: async () => {- const { data } = await apiRequest.get<OrgKmipConfig>("/api/v1/kmip");-- return data;- }- });-};diff --git a/frontend/src/hooks/api/kmip/types.ts b/frontend/src/hooks/api/kmip/types.tsindex c406a44d13..1bdcda85a6 100644--- a/frontend/src/hooks/api/kmip/types.ts+++ b/frontend/src/hooks/api/kmip/types.ts@@ -64,15 +64,6 @@ export enum KmipClientOrderBy {Name = "name"}-export type OrgKmipConfig = {- serverCertificateChain: string;- clientCertificateChain: string;-};--export type TSetupOrgKmipDTO = {- caKeyAlgorithm: CertKeyAlgorithm;-};-export type OrgKmipServerCert = {serialNumber: string;certificate: string;diff --git a/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts b/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.tsindex a355029ad0..62f0642d31 100644--- a/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts+++ b/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts@@ -51,8 +51,7 @@ const appConnectionsPermissionSchema = zconst kmipPermissionSchema = z.object({- [OrgPermissionKmipActions.Proxy]: z.boolean().optional(),- [OrgPermissionKmipActions.Setup]: z.boolean().optional()+ [OrgPermissionKmipActions.Proxy]: z.boolean().optional()}).optional();diff --git a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionKmipRow.tsx b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionKmipRow.tsxindex 6eb1619833..22aa6f965f 100644--- a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionKmipRow.tsx+++ b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionKmipRow.tsx@@ -20,10 +20,7 @@ enum Permission {Custom = "custom"}-const PERMISSION_ACTIONS = [- { action: "proxy", label: "Proxy KMIP requests" },- { action: "setup", label: "Setup KMIP" }-] as const;+const PERMISSION_ACTIONS = [{ action: "proxy", label: "Proxy KMIP requests" }] as const;export const OrgPermissionKmipRow = ({ isEditable, control, setValue }: Props) => {const [isRowExpanded, setIsRowExpanded] = useToggle();@@ -35,7 +32,7 @@ export const OrgPermissionKmipRow = ({ isEditable, control, setValue }: Props) =});const selectedPermissionCategory = useMemo(() => {- if (rule?.proxy || rule?.setup) {+ if (rule?.proxy) {return Permission.Custom;}return Permission.NoAccess;@@ -63,7 +60,7 @@ export const OrgPermissionKmipRow = ({ isEditable, control, setValue }: Props) =setIsCustom.off();if (val === Permission.NoAccess) {- setValue("permissions.kmip", { proxy: false, setup: false }, { shouldDirty: true });+ setValue("permissions.kmip", { proxy: false }, { shouldDirty: true });}};diff --git a/frontend/src/pages/organization/SettingsPage/components/KmipTab/OrgKmipTab.tsx b/frontend/src/pages/organization/SettingsPage/components/KmipTab/OrgKmipTab.tsxdeleted file mode 100644index 4b9b5048f9..0000000000--- a/frontend/src/pages/organization/SettingsPage/components/KmipTab/OrgKmipTab.tsx+++ /dev/null@@ -1,274 +0,0 @@-import { Controller, useForm } from "react-hook-form";-import { faCheck, faCopy, faDownload } from "@fortawesome/free-solid-svg-icons";-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { zodResolver } from "@hookform/resolvers/zod";-import { z } from "zod";--import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";-import { createNotification } from "@app/components/notifications";-import {- Button,- FormControl,- IconButton,- Modal,- ModalContent,- Select,- SelectItem,- Spinner,- TextArea,- Tooltip-} from "@app/components/v2";-import { useOrganization, useSubscription } from "@app/context";-import { downloadTxtFile } from "@app/helpers/download";-import { usePopUp, useTimedReset } from "@app/hooks";-import { certKeyAlgorithms } from "@app/hooks/api/certificates/constants";-import { CertKeyAlgorithm } from "@app/hooks/api/certificates/enums";-import { useGetOrgKmipConfig, useSetupOrgKmip } from "@app/hooks/api/kmip";-import { OrgKmipConfig } from "@app/hooks/api/kmip/types";--const orgConfigFormSchema = z.object({- caKeyAlgorithm: z.nativeEnum(CertKeyAlgorithm)-});--type TKmipOrgConfigForm = z.infer<typeof orgConfigFormSchema>;--const OrgConfigSection = ({- kmipConfig,- isKmipConfigLoading-}: {- kmipConfig?: OrgKmipConfig;- isKmipConfigLoading: boolean;-}) => {- const { popUp, handlePopUpToggle, handlePopUpClose, handlePopUpOpen } = usePopUp([- "configureKmip",- "upgradePlan"- ] as const);- const { subscription } = useSubscription();-- const {- handleSubmit,- control,- formState: { isSubmitting }- } = useForm<TKmipOrgConfigForm>({- resolver: zodResolver(orgConfigFormSchema)- });-- const { currentOrg, isSubOrganization } = useOrganization();- const { mutateAsync: setupOrgKmip } = useSetupOrgKmip(currentOrg.id);-- const onFormSubmit = async (formData: TKmipOrgConfigForm) => {- await setupOrgKmip(formData);-- createNotification({- type: "success",- text: "Successfully configured KMIP"- });-- handlePopUpClose("configureKmip");- };- const [copyTextClientCertificate, isCopyingClientCertificate, setCopyTextClientCertificate] =- useTimedReset<string>({- initialState: "Copy to clipboard"- });-- const [copyTextServerCertificate, isCopyingServerCertificate, setCopyTextServerCertificate] =- useTimedReset<string>({- initialState: "Copy to clipboard"- });-- return (- <>- <div className="flex flex-col justify-start">- <div className="mb-2 text-xl font-medium text-mineshaft-100">KMIP configuration</div>- {isKmipConfigLoading && (- <div className="mt-8 flex justify-center">- <Spinner />- </div>- )}- {!isKmipConfigLoading && kmipConfig && (- <>- <div className="mt-2">- <div className="text-lg">Certificate Chain for KMIP Clients</div>- <div className="mt-2 max-w-lg text-sm text-mineshaft-400">- This certificate chain is used by KMIP clients to verify the identity of the KMIP- server. It should be presented by the server during TLS authentication to establish- a secure and encrypted connection.- </div>- <div className="flex max-w-2xl">- <div className="flex w-full justify-end">- <Tooltip content={copyTextClientCertificate}>- <IconButton- ariaLabel="copy icon"- colorSchema="secondary"- className="group relative"- onClick={() => {- navigator.clipboard.writeText(kmipConfig.serverCertificateChain);- setCopyTextClientCertificate("Copied");- }}- >- <FontAwesomeIcon icon={isCopyingClientCertificate ? faCheck : faCopy} />- </IconButton>- </Tooltip>- <Tooltip content="Download">- <IconButton- ariaLabel="copy icon"- colorSchema="secondary"- className="group relative ml-2"- onClick={() => {- downloadTxtFile("ca-chain.pem", kmipConfig.serverCertificateChain);- }}- >- <FontAwesomeIcon icon={faDownload} />- </IconButton>- </Tooltip>- </div>- </div>- <TextArea- value={kmipConfig.serverCertificateChain}- reSize="none"- className="mt-2 h-48 max-w-2xl"- />- </div>- <div className="mt-8">- <div className="text-lg">Certificate Chain for KMIP Server</div>- <div className="mt-2 max-w-lg text-sm text-mineshaft-400">- This certificate chain is used by the KMIP server to verify the identity of KMIP- clients. It should be configured on the server to establish trust in client- certificates during mutual TLS authentication.- </div>- <div className="flex max-w-2xl">- <div className="flex w-full justify-end">- <Tooltip content={copyTextServerCertificate}>- <IconButton- ariaLabel="copy icon"- colorSchema="secondary"- className="group relative"- onClick={() => {- navigator.clipboard.writeText(kmipConfig.clientCertificateChain);- setCopyTextServerCertificate("Copied");- }}- >- <FontAwesomeIcon icon={isCopyingServerCertificate ? faCheck : faCopy} />- </IconButton>- </Tooltip>- <Tooltip content="Download">- <IconButton- ariaLabel="copy icon"- colorSchema="secondary"- className="group relative ml-2"- onClick={() => {- downloadTxtFile("ca-chain.pem", kmipConfig.clientCertificateChain);- }}- >- <FontAwesomeIcon icon={faDownload} />- </IconButton>- </Tooltip>- </div>- </div>- <TextArea- value={kmipConfig.clientCertificateChain}- reSize="none"- className="mt-2 h-48 max-w-2xl"- />- </div>- </>- )}- {!isKmipConfigLoading && !kmipConfig && (- <div className="mt-2">- <div>- KMIP has not yet been configured for the {isSubOrganization ? "sub-" : ""}- organization.- </div>- <Button- className="mt-2"- onClick={() => {- if (subscription && !subscription.kmip) {- handlePopUpOpen("upgradePlan", {- isEnterpriseFeature: true- });- return;- }-- handlePopUpOpen("configureKmip");- }}- >- Setup KMIP- </Button>- </div>- )}- </div>- <Modal- isOpen={popUp.configureKmip.isOpen}- onOpenChange={(state) => handlePopUpToggle("configureKmip", state)}- >- <ModalContent title="Configure KMIP for the organization">- <form onSubmit={handleSubmit(onFormSubmit)}>- <Controller- control={control}- name="caKeyAlgorithm"- defaultValue={CertKeyAlgorithm.RSA_2048}- render={({ field: { onChange, ...field }, fieldState: { error } }) => (- <FormControl- label="CA Key Algorithm"- errorText={error?.message}- isError={Boolean(error)}- helperText="This defines the key algorithm used for generating the KMIP Root CA and Intermediate CAs, which sign all KMIP server and client certificates."- >- <Select- defaultValue={field.value}- {...field}- onValueChange={(e) => onChange(e)}- className="w-full"- >- {certKeyAlgorithms.map(({ label, value }) => (- <SelectItem value={String(value || "")} key={label}>- {label}- </SelectItem>- ))}- </Select>- </FormControl>- )}- />- <div className="mt-6 flex w-full gap-4">- <Button- className=""- size="sm"- type="submit"- isLoading={isSubmitting}- isDisabled={isSubmitting}- >- Continue- </Button>- <Button- className=""- size="sm"- variant="outline_bg"- type="button"- onClick={() => handlePopUpClose("configureKmip")}- >- Cancel- </Button>- </div>- </form>- </ModalContent>- </Modal>- <UpgradePlanModal- isOpen={popUp.upgradePlan.isOpen}- onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}- text="Your current plan does not include access to KMIP. To unlock this feature, please upgrade to Infisical Enterprise plan."- isEnterpriseFeature={popUp.upgradePlan.data?.isEnterpriseFeature}- />- </>- );-};--export const KmipTab = () => {- const { currentOrg } = useOrganization();- const { data: kmipConfig, isPending } = useGetOrgKmipConfig(currentOrg.id);-- return (- <div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">- <OrgConfigSection kmipConfig={kmipConfig} isKmipConfigLoading={isPending} />- </div>- );-};diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgTabGroup/OrgTabGroup.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgTabGroup/OrgTabGroup.tsxindex 85d4b259c6..9b2d340c68 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgTabGroup/OrgTabGroup.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgTabGroup/OrgTabGroup.tsx@@ -7,7 +7,6 @@ import { useOrganization } from "@app/context";import { AuditLogStreamsTab } from "../AuditLogStreamTab";import { ExternalMigrationsTab } from "../ExternalMigrationsTab";-import { KmipTab } from "../KmipTab/OrgKmipTab";import { OrgEncryptionTab } from "../OrgEncryptionTab";import { OrgGeneralTab } from "../OrgGeneralTab";import { OrgProductSettingsTab } from "../OrgProductSettingsTab";@@ -64,7 +63,6 @@ export const OrgTabGroup = () => {key: "project-templates",component: ProjectTemplatesTab},- { name: "KMIP", key: "kmip", component: KmipTab },{name: "Product Enforcements",key: "product-enforcements",