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 PR comments
Carlos Monastyrskid16c23a26a69
diff --git a/backend/src/db/migrations/20260618143217_pki-hsm-connector.ts b/backend/src/db/migrations/20260618143217_pki-hsm-connector.tsindex 72efc697a6..d506ab28fc 100644--- a/backend/src/db/migrations/20260618143217_pki-hsm-connector.ts+++ b/backend/src/db/migrations/20260618143217_pki-hsm-connector.ts@@ -3,8 +3,8 @@ import { Knex } from "knex";import { TableName } from "@app/db/schemas";import { createOnUpdateTrigger, dropOnUpdateTrigger } from "@app/db/utils";-const HSM_CONNECTORS_GATEWAY_XOR_CHECK = "hsm_connectors_gateway_xor_chk";-const CERTS_KEY_SOURCE_CHECK = "certificates_key_source_chk";+const HSM_CONNECTORS_GATEWAY_XOR_CHK = "hsm_connectors_gateway_xor_chk";+const CERTS_KEY_SOURCE_CHK = "certificates_key_source_chk";const CERTS_HSM_CONNECTOR_FK = "certificates_hsmconnectorid_foreign";const CERTS_HSM_CONNECTOR_IDX = "certificates_hsmconnectorid_idx";const GATEWAYS_CAPABILITIES_GIN_IDX = "gateways_v2_capabilities_gin_idx";@@ -57,7 +57,7 @@ export async function up(knex: Knex): Promise<void> {("gatewayId" IS NULL AND "gatewayPoolId" IS NOT NULL))`,- [TableName.HsmConnector, HSM_CONNECTORS_GATEWAY_XOR_CHECK]+ [TableName.HsmConnector, HSM_CONNECTORS_GATEWAY_XOR_CHK]);await createOnUpdateTrigger(knex, TableName.HsmConnector);@@ -91,16 +91,16 @@ export async function up(knex: Knex): Promise<void> {});}- if (!(await constraintExists(knex, TableName.Certificate, CERTS_KEY_SOURCE_CHECK))) {+ if (!(await constraintExists(knex, TableName.Certificate, CERTS_KEY_SOURCE_CHK))) {await knex.raw(`ALTER TABLE ?? ADD CONSTRAINT ?? CHECK (("keySource" = 'infisical')OR("keySource" = 'hsm' AND "hsmConnectorId" IS NOT NULL AND "hsmKeyLabel" IS NOT NULL)) NOT VALID`,- [TableName.Certificate, CERTS_KEY_SOURCE_CHECK]+ [TableName.Certificate, CERTS_KEY_SOURCE_CHK]);- await knex.raw(`ALTER TABLE ?? VALIDATE CONSTRAINT ??`, [TableName.Certificate, CERTS_KEY_SOURCE_CHECK]);+ await knex.raw(`ALTER TABLE ?? VALIDATE CONSTRAINT ??`, [TableName.Certificate, CERTS_KEY_SOURCE_CHK]);}}@@ -181,8 +181,8 @@ export async function down(knex: Knex): Promise<void> {}if (await knex.schema.hasTable(TableName.Certificate)) {- if (await constraintExists(knex, TableName.Certificate, CERTS_KEY_SOURCE_CHECK)) {- await knex.raw(`ALTER TABLE ?? DROP CONSTRAINT ??`, [TableName.Certificate, CERTS_KEY_SOURCE_CHECK]);+ if (await constraintExists(knex, TableName.Certificate, CERTS_KEY_SOURCE_CHK)) {+ await knex.raw(`ALTER TABLE ?? DROP CONSTRAINT ??`, [TableName.Certificate, CERTS_KEY_SOURCE_CHK]);}const hasKeySource = await knex.schema.hasColumn(TableName.Certificate, "keySource");const hasHsmConnectorId = await knex.schema.hasColumn(TableName.Certificate, "hsmConnectorId");diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.tsindex 9ecbda163d..98ff7b4174 100644--- a/backend/src/ee/routes/v2/gateway-router.ts+++ b/backend/src/ee/routes/v2/gateway-router.ts@@ -71,9 +71,12 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {operationId: "gatewayHeartbeat",body: z.object({- capabilities: z.record(z.unknown()).optional()+ capabilities: z+ .object({+ pkcs11: z.boolean().optional()+ })+ .optional()})- .passthrough().optional(),response: {200: z.object({diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 8f7e7aec63..f0e4a12a8e 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -4978,6 +4978,10 @@ interface ReissuePkiSignerCertificateEvent {name: string;caId: string;commonName?: string;+ keyAlgorithm?: string;+ keySource?: string;+ hsmConnectorId?: string;+ hsmKeyAlgorithm?: string;};}diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.tsindex 27414b6719..e37744f4ac 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts@@ -979,19 +979,16 @@ export const gatewayV2ServiceFactory = ({capabilities}: {orgPermission: OrgServiceActor;- capabilities?: Record<string, unknown>;+ capabilities?: { pkcs11?: boolean };}) => {- const persistCapabilities = async (gatewayId: string) => {- if (capabilities === undefined) return;- await gatewayV2DAL.updateById(gatewayId, { capabilities });- };+ const nextCapabilities = capabilities ?? {};if (orgPermission.type === ActorType.GATEWAY) {const gateway = await gatewayV2DAL.findById(orgPermission.id);if (!gateway || gateway.orgId !== orgPermission.orgId) {throw new NotFoundError({ message: `Gateway ${orgPermission.id} not found.` });}- await persistCapabilities(gateway.id);+ await gatewayV2DAL.updateById(gateway.id, { capabilities: nextCapabilities });await $checkGatewayHealth(gateway.id);return;}@@ -1007,7 +1004,7 @@ export const gatewayV2ServiceFactory = ({throw new NotFoundError({ message: `Gateway for identity ${orgPermission.id} not found.` });}- await persistCapabilities(gateway.id);+ await gatewayV2DAL.updateById(gateway.id, { capabilities: nextCapabilities });await $checkGatewayHealth(gateway.id);};diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.tsindex 6fd5c36592..cad4cc3d55 100644--- a/backend/src/ee/services/license/license-fns.ts+++ b/backend/src/ee/services/license/license-fns.ts@@ -102,7 +102,6 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({pkiAcme: true,pkiScep: false,pkiPqc: false,- pkiHsm: false,kmsPqc: false,enforceMfa: false,projectTemplates: false,diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.tsindex 3f3a0294c7..3878041596 100644--- a/backend/src/ee/services/license/license-types.ts+++ b/backend/src/ee/services/license/license-types.ts@@ -82,7 +82,6 @@ export type TFeatureSet = {pkiAcme: true;pkiScep: false;pkiPqc: false;- pkiHsm: false;kmsPqc: false;enforceMfa: false;projectTemplates: false;diff --git a/backend/src/server/routes/v1/cert-manager-hsm-connector-router-schemas.ts b/backend/src/server/routes/v1/hsm-connector-router-schemas.tssimilarity index 78%rename from backend/src/server/routes/v1/cert-manager-hsm-connector-router-schemas.tsrename to backend/src/server/routes/v1/hsm-connector-router-schemas.tsindex 0cde73e9a3..bf9d445fc1 100644--- a/backend/src/server/routes/v1/cert-manager-hsm-connector-router-schemas.ts+++ b/backend/src/server/routes/v1/hsm-connector-router-schemas.ts@@ -1,7 +1,10 @@import { z } from "zod";import { slugSchema } from "@app/server/lib/schemas";-import { HsmConnectorCredentialsSchema } from "@app/services/hsm-connector/hsm-connector-fns";+import {+ HsmConnectorCredentialsSchema,+ HsmConnectorSanitizedSchema as SharedHsmConnectorSanitizedSchema+} from "@app/services/hsm-connector/hsm-connector-fns";const HSM_CONNECTOR_NAME_MAX = 32;const HSM_CONNECTOR_DESCRIPTION_MAX = 256;@@ -15,18 +18,7 @@ export const gatewayPickRefiner = (data: { gatewayId?: string | null; gatewayPooreturn hasGatewayId !== hasPool;};-export const HsmConnectorSanitizedSchema = z.object({- id: z.string().uuid(),- name: z.string(),- description: z.string().nullable(),- projectId: z.string(),- gatewayId: z.string().uuid().nullable(),- gatewayPoolId: z.string().uuid().nullable(),- slotLabel: z.string(),- keyNamePrefix: z.string().nullable(),- createdAt: z.date(),- updatedAt: z.date()-});+export const HsmConnectorSanitizedSchema = SharedHsmConnectorSanitizedSchema;export const HsmConnectorTestResultSchema = z.object({ok: z.boolean(),@@ -53,8 +45,9 @@ export const HsmConnectorTestResultSchema = z.object({.min(1)});-export const CreateBodySchema = z+export const CreateHsmConnectorBodySchema = z.object({+ projectId: z.string().uuid(),name: slugSchema({ min: 1, max: HSM_CONNECTOR_NAME_MAX, field: "name" }),description: z.string().max(HSM_CONNECTOR_DESCRIPTION_MAX).optional(),gatewayId: z.string().uuid().optional(),@@ -63,7 +56,11 @@ export const CreateBodySchema = z}).refine(gatewayPickRefiner, { message: GATEWAY_PICK_MESSAGE, path: ["gatewayId"] });-export const UpdateBodySchema = z+export const ListHsmConnectorsQuerySchema = z.object({+ projectId: z.string().uuid()+});++export const UpdateHsmConnectorBodySchema = z.object({name: slugSchema({ min: 1, max: HSM_CONNECTOR_NAME_MAX, field: "name" }).optional(),description: z.string().max(HSM_CONNECTOR_DESCRIPTION_MAX).optional(),@@ -82,17 +79,17 @@ export const UpdateBodySchema = z{ message: GATEWAY_PICK_MESSAGE, path: ["gatewayId"] });-export const ConnectorIdParamSchema = z.object({+export const HsmConnectorIdParamSchema = z.object({connectorId: z.string().uuid()});-export const LinkedCertificatesQuerySchema = z.object({+export const HsmConnectorLinkedResourcesQuerySchema = z.object({offset: z.coerce.number().min(0).default(0),limit: z.coerce.number().min(1).max(100).default(20)});-export const LinkedCertificatesResponseSchema = z.object({- linkedCertificates: z.array(+export const HsmConnectorLinkedResourcesResponseSchema = z.object({+ certificates: z.array(z.object({id: z.string().uuid(),commonName: z.string(),diff --git a/backend/src/server/routes/v1/cert-manager-hsm-connector-router.ts b/backend/src/server/routes/v1/hsm-connector-router.tssimilarity index 79%rename from backend/src/server/routes/v1/cert-manager-hsm-connector-router.tsrename to backend/src/server/routes/v1/hsm-connector-router.tsindex 70a0f75012..62c7affd17 100644--- a/backend/src/server/routes/v1/cert-manager-hsm-connector-router.ts+++ b/backend/src/server/routes/v1/hsm-connector-router.ts@@ -7,16 +7,17 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";import {- ConnectorIdParamSchema,- CreateBodySchema,+ CreateHsmConnectorBodySchema,+ HsmConnectorIdParamSchema,+ HsmConnectorLinkedResourcesQuerySchema,+ HsmConnectorLinkedResourcesResponseSchema,HsmConnectorSanitizedSchema,HsmConnectorTestResultSchema,- LinkedCertificatesQuerySchema,- LinkedCertificatesResponseSchema,- UpdateBodySchema-} from "./cert-manager-hsm-connector-router-schemas";+ ListHsmConnectorsQuerySchema,+ UpdateHsmConnectorBodySchema+} from "./hsm-connector-router-schemas";-export const registerCertManagerHsmConnectorRouter = async (server: FastifyZodProvider) => {+export const registerHsmConnectorRouter = async (server: FastifyZodProvider) => {server.route({method: "POST",url: "/",@@ -25,14 +26,14 @@ export const registerCertManagerHsmConnectorRouter = async (server: FastifyZodPrhide: false,operationId: "createHsmConnector",tags: [ApiDocsTags.HsmConnectors],- body: CreateBodySchema,+ body: CreateHsmConnectorBodySchema,response: { 200: z.object({ hsmConnector: HsmConnectorSanitizedSchema }) }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {const hsmConnector = await server.services.hsmConnector.createHsmConnector({- projectId: req.internalCertManagerProjectId,+ projectId: req.body.projectId,name: req.body.name,description: req.body.description,gatewayId: req.body.gatewayId,@@ -66,12 +67,13 @@ export const registerCertManagerHsmConnectorRouter = async (server: FastifyZodPrhide: false,operationId: "listHsmConnectors",tags: [ApiDocsTags.HsmConnectors],+ querystring: ListHsmConnectorsQuerySchema,response: { 200: z.object({ hsmConnectors: HsmConnectorSanitizedSchema.array() }) }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {const hsmConnectors = await server.services.hsmConnector.listHsmConnectors(- { projectId: req.internalCertManagerProjectId },+ { projectId: req.query.projectId },req.permission);return { hsmConnectors };@@ -86,7 +88,7 @@ export const registerCertManagerHsmConnectorRouter = async (server: FastifyZodPrhide: false,operationId: "getHsmConnector",tags: [ApiDocsTags.HsmConnectors],- params: ConnectorIdParamSchema,+ params: HsmConnectorIdParamSchema,response: { 200: z.object({ hsmConnector: HsmConnectorSanitizedSchema }) }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),@@ -107,8 +109,8 @@ export const registerCertManagerHsmConnectorRouter = async (server: FastifyZodPrhide: false,operationId: "updateHsmConnector",tags: [ApiDocsTags.HsmConnectors],- params: ConnectorIdParamSchema,- body: UpdateBodySchema,+ params: HsmConnectorIdParamSchema,+ body: UpdateHsmConnectorBodySchema,response: { 200: z.object({ hsmConnector: HsmConnectorSanitizedSchema }) }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),@@ -149,28 +151,24 @@ export const registerCertManagerHsmConnectorRouter = async (server: FastifyZodPrhide: false,operationId: "deleteHsmConnector",tags: [ApiDocsTags.HsmConnectors],- params: ConnectorIdParamSchema,+ params: HsmConnectorIdParamSchema,response: { 200: z.object({ id: z.string().uuid() }) }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const connector = await server.services.hsmConnector.getHsmConnectorById(- { connectorId: req.params.connectorId },- req.permission- );- const result = await server.services.hsmConnector.deleteHsmConnector(+ const deleted = await server.services.hsmConnector.deleteHsmConnector({ connectorId: req.params.connectorId },req.permission);await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: connector.projectId,+ projectId: deleted.projectId,event: {type: EventType.DELETE_HSM_CONNECTOR,- metadata: { connectorId: result.id, name: connector.name }+ metadata: { connectorId: deleted.id, name: deleted.name }}});- return result;+ return { id: deleted.id };}});@@ -182,27 +180,23 @@ export const registerCertManagerHsmConnectorRouter = async (server: FastifyZodPrhide: false,operationId: "testHsmConnector",tags: [ApiDocsTags.HsmConnectors],- params: ConnectorIdParamSchema,+ params: HsmConnectorIdParamSchema,response: { 200: HsmConnectorTestResultSchema }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const connector = await server.services.hsmConnector.getHsmConnectorById(- { connectorId: req.params.connectorId },- req.permission- );- const result = await server.services.hsmConnector.testHsmConnector(+ const { projectId, name, result } = await server.services.hsmConnector.testHsmConnector({ connectorId: req.params.connectorId },req.permission);await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: connector.projectId,+ projectId,event: {type: EventType.TEST_HSM_CONNECTOR,metadata: {connectorId: req.params.connectorId,- name: connector.name,+ name,ok: result.ok,memberCount: result.members.length}@@ -214,19 +208,19 @@ export const registerCertManagerHsmConnectorRouter = async (server: FastifyZodPrserver.route({method: "GET",- url: "/:connectorId/linked-certificates",+ url: "/:connectorId/linked-resources",config: { rateLimit: readLimit },schema: {hide: false,- operationId: "listHsmConnectorLinkedCertificates",+ operationId: "listHsmConnectorLinkedResources",tags: [ApiDocsTags.HsmConnectors],- params: ConnectorIdParamSchema,- querystring: LinkedCertificatesQuerySchema,- response: { 200: LinkedCertificatesResponseSchema }+ params: HsmConnectorIdParamSchema,+ querystring: HsmConnectorLinkedResourcesQuerySchema,+ response: { 200: HsmConnectorLinkedResourcesResponseSchema }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- return server.services.hsmConnector.listLinkedCertificates(+ return server.services.hsmConnector.listLinkedResources({connectorId: req.params.connectorId,offset: req.query.offset,diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.tsindex dbb685f271..6438832fcf 100644--- a/backend/src/server/routes/v1/index.ts+++ b/backend/src/server/routes/v1/index.ts@@ -17,7 +17,7 @@ import { registerAuthRoutes } from "./auth-router";import { registerProjectBotRouter } from "./bot-router";import { registerCertManagerAccessRouter } from "./cert-manager-access-routers";import { registerCertManagerExportRouter } from "./cert-manager-export-router";-import { registerCertManagerHsmConnectorRouter } from "./cert-manager-hsm-connector-router";+import { registerHsmConnectorRouter } from "./hsm-connector-router";import { registerCertManagerInstanceRouter } from "./cert-manager-instance-router";import { registerCaRouter } from "./certificate-authority-router";import { CERTIFICATE_AUTHORITY_REGISTER_ROUTER_MAP } from "./certificate-authority-routers";@@ -187,6 +187,8 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {{ prefix: "/projects/:projectId/memberships" });+ await server.register(registerHsmConnectorRouter, { prefix: "/hsm-connectors" });+await server.register(async (pkiRouter) => {await pkiRouter.register(injectCertManagerProjectId);@@ -241,7 +243,6 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {await pkiRouter.register(registerCertificateCleanupRouter, { prefix: "/certificate-cleanup" });await pkiRouter.register(registerCertificateInventoryViewRouter, { prefix: "/certificate-inventory-views" });await pkiRouter.register(registerCertManagerAccessRouter, { prefix: "/access" });- await pkiRouter.register(registerCertManagerHsmConnectorRouter, { prefix: "/hsm-connectors" });await pkiRouter.register(async (pkiSyncRouter) => {await registerPkiSyncRouter(pkiSyncRouter as unknown as FastifyZodProvider);diff --git a/backend/src/server/routes/v1/signer-routers/certificate-router.ts b/backend/src/server/routes/v1/signer-routers/certificate-router.tsindex 476a68235a..dcadf33afe 100644--- a/backend/src/server/routes/v1/signer-routers/certificate-router.ts+++ b/backend/src/server/routes/v1/signer-routers/certificate-router.ts@@ -6,8 +6,9 @@ import { ApiDocsTags } from "@app/lib/api-docs";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";+import { CertKeySource, HsmKeyAlgorithm } from "@app/services/signer/signer-enums";-import { SignerIdParamsSchema } from "./schemas";+import { SignerIdParamsSchema, SignerKeyAlgorithm } from "./schemas";export const registerSignerCertificateRouter = async (server: FastifyZodProvider) => {server.route({@@ -18,12 +19,25 @@ export const registerSignerCertificateRouter = async (server: FastifyZodProviderhide: false,operationId: "reissueSignerCertificate",tags: [ApiDocsTags.PkiSigners],- description: "Re-issue the signer's certificate (optionally from a different CA)",+ description: "Re-issue the signer's certificate (optionally from a different CA or with a different key source)",params: SignerIdParamsSchema,body: z.object({caId: z.string().uuid(),commonName: z.string().trim().min(1).max(256).optional(),- certificateTtlDays: z.number().int().min(1).max(3650).optional()+ certificateTtlDays: z.number().int().min(1).max(3650).optional(),+ keyAlgorithm: SignerKeyAlgorithm.schema.optional(),+ certificate: z+ .object({+ keySource: z.nativeEnum(CertKeySource),+ hsmConnectorId: z.string().uuid().optional(),+ hsmKeyAlgorithm: z.nativeEnum(HsmKeyAlgorithm).optional()+ })+ .refine(+ (data) =>+ data.keySource !== CertKeySource.Hsm || (Boolean(data.hsmConnectorId) && Boolean(data.hsmKeyAlgorithm)),+ { message: `hsmConnectorId and hsmKeyAlgorithm are required when keySource = '${CertKeySource.Hsm}'` }+ )+ .optional()}),response: { 200: PkiSignersSchema }},@@ -47,7 +61,11 @@ export const registerSignerCertificateRouter = async (server: FastifyZodProvidersignerId: signer.id,name: signer.name,caId: req.body.caId,- commonName: req.body.commonName+ commonName: req.body.commonName,+ keyAlgorithm: req.body.keyAlgorithm,+ keySource: req.body.certificate?.keySource,+ hsmConnectorId: req.body.certificate?.hsmConnectorId,+ hsmKeyAlgorithm: req.body.certificate?.hsmKeyAlgorithm}}});diff --git a/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.tsindex b79e856ae3..e0b9ab7239 100644--- a/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts+++ b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts@@ -848,11 +848,34 @@ export const AwsPcaCertificateAuthorityFns = ({logger.info(revokeResult, "AWS PCA RevokeCertificate result");};+ const orderCertificateForSigner = (args: {+ caId: string;+ commonName: string;+ altNames?: Array<{ type: CertSubjectAlternativeNameType; value: string }>;+ keyUsages?: CertKeyUsage[];+ extendedKeyUsages?: CertExtendedKeyUsage[];+ validity: { ttl: string };+ notBefore?: Date;+ notAfter?: Date;+ signatureAlgorithm?: string;+ keyAlgorithm?: CertKeyAlgorithm;+ isRenewal?: boolean;+ originalCertificateId?: string;+ csr?: string;+ organization?: string;+ organizationalUnit?: string;+ country?: string;+ state?: string;+ locality?: string;+ isCancelled?: () => Promise<boolean>;+ }) => orderCertificateFromProfile(args);+return {createCertificateAuthority,updateCertificateAuthority,listCertificateAuthorities,orderCertificateFromProfile,+ orderCertificateForSigner,revokeCertificate};};diff --git a/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts b/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.tsindex dd83b5fe6a..de878f7596 100644--- a/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts+++ b/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts@@ -1612,12 +1612,30 @@ export const AzureAdCsCertificateAuthorityFns = ({}};+ const orderCertificateForSigner = (args: {+ caId: string;+ commonName: string;+ altNames?: string[];+ keyUsages?: CertKeyUsage[];+ extendedKeyUsages?: CertExtendedKeyUsage[];+ template?: string;+ validity: { ttl: string };+ notBefore?: Date;+ notAfter?: Date;+ signatureAlgorithm?: string;+ keyAlgorithm?: CertKeyAlgorithm;+ isRenewal?: boolean;+ originalCertificateId?: string;+ isCancelled?: () => Promise<boolean>;+ }) => orderCertificateFromProfile(args);+return {createCertificateAuthority,updateCertificateAuthority,listCertificateAuthorities,orderSubscriberCertificate,orderCertificateFromProfile,+ orderCertificateForSigner,getTemplates};};diff --git a/backend/src/services/hsm-connector/hsm-connector-dal.ts b/backend/src/services/hsm-connector/hsm-connector-dal.tsindex 6ed8f90e60..545134911f 100644--- a/backend/src/services/hsm-connector/hsm-connector-dal.ts+++ b/backend/src/services/hsm-connector/hsm-connector-dal.ts@@ -1,3 +1,5 @@+import { Knex } from "knex";+import { TDbClient } from "@app/db";import { TableName } from "@app/db/schemas";import { DatabaseError } from "@app/lib/errors";@@ -8,9 +10,9 @@ export type THsmConnectorDALFactory = ReturnType<typeof hsmConnectorDALFactory>;export const hsmConnectorDALFactory = (db: TDbClient) => {const hsmConnectorOrm = ormify(db, TableName.HsmConnector);- const countReferencingCertificates = async (connectorId: string): Promise<number> => {+ const countReferencingCertificates = async (connectorId: string, tx?: Knex): Promise<number> => {try {- const result = await db(TableName.Certificate)+ const result = await (tx || db)(TableName.Certificate).where("hsmConnectorId", connectorId).count<{ count: string }[]>("id as count").first();@@ -32,7 +34,7 @@ export const hsmConnectorDALFactory = (db: TDbClient) => {}};- const listLinkedCertificates = async (connectorId: string, { offset, limit }: { offset: number; limit: number }) => {+ const listLinkedResources = async (connectorId: string, { offset, limit }: { offset: number; limit: number }) => {try {const baseQuery = db.replicaNode()(TableName.Certificate).where("hsmConnectorId", connectorId);@@ -47,7 +49,7 @@ export const hsmConnectorDALFactory = (db: TDbClient) => {]);return {- rows: rows.map((r) => ({+ certificates: rows.map((r) => ({id: r.id,commonName: r.commonName,status: r.status,@@ -58,7 +60,7 @@ export const hsmConnectorDALFactory = (db: TDbClient) => {totalCount: Number(totalCountResult?.count ?? 0)};} catch (error) {- throw new DatabaseError({ error, name: "HsmConnectorDAL.listLinkedCertificates" });+ throw new DatabaseError({ error, name: "HsmConnectorDAL.listLinkedResources" });}};@@ -66,6 +68,6 @@ export const hsmConnectorDALFactory = (db: TDbClient) => {...hsmConnectorOrm,countReferencingCertificates,findByProjectId,- listLinkedCertificates+ listLinkedResources};};diff --git a/backend/src/services/hsm-connector/hsm-connector-fns.ts b/backend/src/services/hsm-connector/hsm-connector-fns.tsindex 719327da04..f8f7c82343 100644--- a/backend/src/services/hsm-connector/hsm-connector-fns.ts+++ b/backend/src/services/hsm-connector/hsm-connector-fns.ts@@ -55,6 +55,19 @@ export const decryptHsmConnectorCredentials = async ({return HsmConnectorCredentialsSchema.parse(JSON.parse(plainText.toString()));};+export const HsmConnectorSanitizedSchema = z.object({+ id: z.string().uuid(),+ name: z.string(),+ description: z.string().nullable(),+ projectId: z.string(),+ gatewayId: z.string().uuid().nullable(),+ gatewayPoolId: z.string().uuid().nullable(),+ slotLabel: z.string(),+ keyNamePrefix: z.string().nullable(),+ createdAt: z.date(),+ updatedAt: z.date()+});+export const sanitizeHsmConnector = (args: {row: {id: string;@@ -67,15 +80,16 @@ export const sanitizeHsmConnector = (args: {updatedAt: Date;};credentials: THsmConnectorCredentials;-}): THsmConnectorSanitized => ({- id: args.row.id,- name: args.row.name,- description: args.row.description ?? null,- projectId: args.row.projectId,- gatewayId: args.row.gatewayId ?? null,- gatewayPoolId: args.row.gatewayPoolId ?? null,- slotLabel: args.credentials.slotLabel,- keyNamePrefix: args.credentials.keyNamePrefix ?? null,- createdAt: args.row.createdAt,- updatedAt: args.row.updatedAt-});+}): THsmConnectorSanitized =>+ HsmConnectorSanitizedSchema.parse({+ id: args.row.id,+ name: args.row.name,+ description: args.row.description ?? null,+ projectId: args.row.projectId,+ gatewayId: args.row.gatewayId ?? null,+ gatewayPoolId: args.row.gatewayPoolId ?? null,+ slotLabel: args.credentials.slotLabel,+ keyNamePrefix: args.credentials.keyNamePrefix ?? null,+ createdAt: args.row.createdAt,+ updatedAt: args.row.updatedAt+ });diff --git a/backend/src/services/hsm-connector/hsm-connector-routing.ts b/backend/src/services/hsm-connector/hsm-connector-routing.tsindex cefc90c0d0..d9bc2b4cbb 100644--- a/backend/src/services/hsm-connector/hsm-connector-routing.ts+++ b/backend/src/services/hsm-connector/hsm-connector-routing.ts@@ -36,7 +36,7 @@ export const hsmConnectorRoutingFactory = ({ gatewayV2Service, gatewayPoolServicif (connector.gatewayId) {if (triedGatewayIds.has(connector.gatewayId)) {throw new BadRequestError({- message: "Gateway is unreachable for PKCS#11; check the gateway is running with --pkcs11-module."+ message: "Gateway is unreachable for HSM operations. Ensure the gateway is online and has HSM support enabled."});}return connector.gatewayId;@@ -49,7 +49,7 @@ export const hsmConnectorRoutingFactory = ({ gatewayV2Service, gatewayPoolServicif (capable.length === 0) {throw new BadRequestError({message:- "No healthy PKCS#11-enabled gateway in the pool. Start at least one gateway with --pkcs11-module pointing at the HSM."+ "No HSM-capable gateway available in the pool. Ensure at least one gateway in the pool has HSM support enabled."});}return capable[Math.floor(Math.random() * capable.length)].id;@@ -196,7 +196,8 @@ export const hsmConnectorRoutingFactory = ({ gatewayV2Service, gatewayPoolServic}if (targets.length === 0) {throw new BadRequestError({- message: "No healthy PKCS#11-enabled gateway in the pool. Start at least one gateway with --pkcs11-module."+ message:+ "No HSM-capable gateway available in the pool. Ensure at least one gateway in the pool has HSM support enabled."});}}diff --git a/backend/src/services/hsm-connector/hsm-connector-service.ts b/backend/src/services/hsm-connector/hsm-connector-service.tsindex 79bdcc6c77..9f897f5077 100644--- a/backend/src/services/hsm-connector/hsm-connector-service.ts+++ b/backend/src/services/hsm-connector/hsm-connector-service.ts@@ -31,7 +31,6 @@ import type {THsmConnectorCredentials,THsmConnectorSanitized,THsmConnectorServiceActor,- THsmConnectorTestResult,TListHsmConnectorsDTO,TTestHsmConnectorDTO,TUpdateHsmConnectorDTO@@ -83,9 +82,9 @@ export const hsmConnectorServiceFactory = ({const assertLicense = async (orgId: string) => {const plan = await licenseService.getPlan(orgId);- if (!plan.pkiHsm) {+ if (!plan.hsm) {throw new BadRequestError({- message: "Your plan does not include HSM-backed code signing. Please upgrade to use HSM Connectors."+ message: "Your plan does not include HSM support. Please upgrade to use HSM Connectors."});}};@@ -102,7 +101,7 @@ export const hsmConnectorServiceFactory = ({projectId,actorAuthMethod: actor.authMethod,actorOrgId: actor.orgId,- actionProjectType: ActionProjectType.CertificateManager+ actionProjectType: ActionProjectType.Any});ForbiddenError.from(permission).throwUnlessCan(action, ProjectPermissionSub.HsmConnectors);};@@ -162,7 +161,7 @@ export const hsmConnectorServiceFactory = ({const cause = (err as { error?: { code?: string } })?.error;if (cause?.code === "23505") {throw new BadRequestError({- message: `An HSM Connector named "${dto.name}" already exists in this project.`+ message: `An HSM Connector named "${dto.name}" already exists.`});}throw err;@@ -289,27 +288,25 @@ export const hsmConnectorServiceFactory = ({return sanitizeHsmConnector({ row: updated, credentials: parsedCreds.data });};- const deleteHsmConnector = async (- dto: TDeleteHsmConnectorDTO,- actor: THsmConnectorServiceActor- ): Promise<{ id: string }> => {+ const deleteHsmConnector = async (dto: TDeleteHsmConnectorDTO, actor: THsmConnectorServiceActor) => {const row = await hsmConnectorDAL.findById(dto.connectorId);if (!row) throw new NotFoundError({ message: `HSM Connector ${dto.connectorId} not found.` });await assertProjectPermission(actor, row.projectId, ProjectPermissionHsmConnectorActions.Delete);- const refCount = await hsmConnectorDAL.countReferencingCertificates(row.id);- if (refCount > 0) {- throw new BadRequestError({- message: `HSM Connector is in use by ${refCount} certificate(s). Open the connector to see the linked certificates panel and re-issue or retire them first.`- });- }-- await hsmConnectorDAL.deleteById(row.id);- return { id: row.id };+ await hsmConnectorDAL.transaction(async (tx) => {+ const refCount = await hsmConnectorDAL.countReferencingCertificates(row.id, tx);+ if (refCount > 0) {+ throw new BadRequestError({+ message: `HSM Connector is in use by ${refCount} certificate(s). Open the connector to see the linked certificates panel and re-issue or retire them first.`+ });+ }+ await hsmConnectorDAL.deleteById(row.id, tx);+ });+ return { id: row.id, name: row.name, projectId: row.projectId };};- const listLinkedCertificates = async (+ const listLinkedResources = async (dto: { connectorId: string; offset: number; limit: number },actor: THsmConnectorServiceActor) => {@@ -323,24 +320,20 @@ export const hsmConnectorServiceFactory = ({projectId: row.projectId,actorAuthMethod: actor.authMethod,actorOrgId: actor.orgId,- actionProjectType: ActionProjectType.CertificateManager+ actionProjectType: ActionProjectType.Any});ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCertificateActions.Read,ProjectPermissionSub.Certificates);- const { rows, totalCount } = await hsmConnectorDAL.listLinkedCertificates(row.id, {+ return hsmConnectorDAL.listLinkedResources(row.id, {offset: dto.offset,limit: dto.limit});- return { linkedCertificates: rows, totalCount };};- const testHsmConnector = async (- dto: TTestHsmConnectorDTO,- actor: THsmConnectorServiceActor- ): Promise<THsmConnectorTestResult> => {+ const testHsmConnector = async (dto: TTestHsmConnectorDTO, actor: THsmConnectorServiceActor) => {const row = await hsmConnectorDAL.findById(dto.connectorId);if (!row) throw new NotFoundError({ message: `HSM Connector ${dto.connectorId} not found.` });@@ -352,11 +345,12 @@ export const hsmConnectorServiceFactory = ({kmsService});- return routing.runTestRoundTrip({+ const result = await routing.runTestRoundTrip({gatewayId: row.gatewayId ?? null,gatewayPoolId: row.gatewayPoolId ?? null,credentials});+ return { projectId: row.projectId, name: row.name, result };};const $loadConnector = async (connectorId: string, expectedProjectId: string) => {@@ -448,7 +442,7 @@ export const hsmConnectorServiceFactory = ({updateHsmConnector,deleteHsmConnector,testHsmConnector,- listLinkedCertificates,+ listLinkedResources,assertAttachPermission,generateKeyPair,sign,diff --git a/backend/src/services/signer/signer-issuance-fns.ts b/backend/src/services/signer/signer-issuance-fns.tsindex 348de07ef3..87be5cfac2 100644--- a/backend/src/services/signer/signer-issuance-fns.ts+++ b/backend/src/services/signer/signer-issuance-fns.ts@@ -332,7 +332,7 @@ export const renewHsmBackedSignerCertificate = async (): Promise<{ certificateId: string; hsmKeyLabel: string }> => {const ca = await deps.certificateAuthorityDAL.findByIdWithAssociatedCa(input.caId);if (!ca || ca.projectId !== input.projectId) {- throw new BadRequestError({ message: `Certificate authority '${input.caId}' is not in this project.` });+ throw new BadRequestError({ message: `Certificate authority '${input.caId}' was not found.` });}if (ca.status !== CaStatus.ACTIVE) {throw new BadRequestError({ message: "The selected certificate authority is not active." });@@ -353,7 +353,7 @@ export const renewHsmBackedSignerCertificate = async (if (stored.length !== publicKeySpkiDer.length || !stored.equals(publicKeySpkiDer)) {throw new BadRequestError({message:- "HSM returned a different public key than the one recorded at issuance. Renewal aborted; investigate the HSM and the Gateway."+ "HSM returned a different public key for the recorded key label. This typically means the key was deleted and recreated under the same label on the HSM, or the HSM Connector now routes to a different HSM. Renewal aborted: verify the key label on the HSM and the Connector's routing."});}}diff --git a/backend/src/services/signer/signer-issuance-service.ts b/backend/src/services/signer/signer-issuance-service.tsindex ae2a3dd5d2..1437d1b71f 100644--- a/backend/src/services/signer/signer-issuance-service.ts+++ b/backend/src/services/signer/signer-issuance-service.ts@@ -135,8 +135,6 @@ export const signerIssuanceServiceFactory = ({});}- await signerIssuanceJobDAL.cancelOpenForSigner(input.signerId, "Superseded by a newer issuance request.");-if (input.hsm) {if (input.hsm.actor) {await hsmConnectorService.assertAttachPermission(input.hsm.actor, input.hsm.hsmConnectorId, input.projectId);@@ -175,21 +173,31 @@ export const signerIssuanceServiceFactory = ({const encryptedCsrHsm = await encryptForProject(input.projectId, Buffer.from(built.csrPem));const hsmCertKeyAlgorithm = hsmKeyAlgorithmToCertKeyAlgorithm(input.hsm.hsmKeyAlgorithm);- const hsmJob = await signerIssuanceJobDAL.create({- signerId: input.signerId,- caId: input.caId,- caType,- status: SignerIssuanceJobStatus.Pending,- commonName: input.commonName,- certificateTtlDays: input.certificateTtlDays,- keyAlgorithm: hsmCertKeyAlgorithm,- encryptedCsr: encryptedCsrHsm,- encryptedPrivateKey: null,- keySource: CertKeySource.Hsm,- hsmConnectorId: input.hsm.hsmConnectorId,- hsmKeyLabel: keyLabel,- hsmPublicKeySpki: publicKeySpkiDer,- nextPollAt: new Date()+ const hsmJob = await signerIssuanceJobDAL.transaction(async (tx) => {+ await signerIssuanceJobDAL.cancelOpenForSigner(+ input.signerId,+ "Superseded by a newer issuance request.",+ tx+ );+ return signerIssuanceJobDAL.create(+ {+ signerId: input.signerId,+ caId: input.caId,+ caType,+ status: SignerIssuanceJobStatus.Pending,+ commonName: input.commonName,+ certificateTtlDays: input.certificateTtlDays,+ keyAlgorithm: hsmCertKeyAlgorithm,+ encryptedCsr: encryptedCsrHsm,+ encryptedPrivateKey: null,+ keySource: CertKeySource.Hsm,+ hsmConnectorId: input.hsm!.hsmConnectorId,+ hsmKeyLabel: keyLabel,+ hsmPublicKeySpki: publicKeySpkiDer,+ nextPollAt: new Date()+ },+ tx+ );});void (async () => {@@ -211,17 +219,23 @@ export const signerIssuanceServiceFactory = ({const encryptedCsr = await encryptForProject(input.projectId, Buffer.from(csrPem));const encryptedPrivateKey = await encryptForProject(input.projectId, Buffer.from(privateKeyPem));- const job = await signerIssuanceJobDAL.create({- signerId: input.signerId,- caId: input.caId,- caType,- status: SignerIssuanceJobStatus.Pending,- commonName: input.commonName,- certificateTtlDays: input.certificateTtlDays,- keyAlgorithm,- encryptedCsr,- encryptedPrivateKey,- nextPollAt: new Date()+ const job = await signerIssuanceJobDAL.transaction(async (tx) => {+ await signerIssuanceJobDAL.cancelOpenForSigner(input.signerId, "Superseded by a newer issuance request.", tx);+ return signerIssuanceJobDAL.create(+ {+ signerId: input.signerId,+ caId: input.caId,+ caType,+ status: SignerIssuanceJobStatus.Pending,+ commonName: input.commonName,+ certificateTtlDays: input.certificateTtlDays,+ keyAlgorithm,+ encryptedCsr,+ encryptedPrivateKey,+ nextPollAt: new Date()+ },+ tx+ );});void (async () => {@@ -374,46 +388,52 @@ export const signerIssuanceServiceFactory = ({return;}- if (job.keySource === CertKeySource.Hsm && job.hsmConnectorId && job.hsmKeyLabel) {- try {- const certAlg = job.keyAlgorithm as CertKeyAlgorithm;- await certificateDAL.updateById(certificateId, {- keySource: CertKeySource.Hsm,- hsmConnectorId: job.hsmConnectorId,- hsmKeyLabel: job.hsmKeyLabel,- hsmPublicKeySpki: job.hsmPublicKeySpki ?? null,- keyAlgorithm: certAlg- });- } catch (patchErr) {- const reason = formatSignerIssuanceErrorReason(- patchErr,- "Failed to record HSM coordinates on the issued certificate"+ const isHsmJob = job.keySource === CertKeySource.Hsm && job.hsmConnectorId && job.hsmKeyLabel;+ try {+ await signerDAL.transaction(async (tx) => {+ if (isHsmJob) {+ const certAlg = job.keyAlgorithm as CertKeyAlgorithm;+ await certificateDAL.updateById(+ certificateId,+ {+ keySource: CertKeySource.Hsm,+ hsmConnectorId: job.hsmConnectorId,+ hsmKeyLabel: job.hsmKeyLabel,+ hsmPublicKeySpki: job.hsmPublicKeySpki ?? null,+ keyAlgorithm: certAlg+ },+ tx+ );+ }+ await signerDAL.updateById(+ job.signerId,+ {+ certificateId,+ status: SignerStatus.Active,+ certificateFailureReason: null+ },+ tx);- await markJobFailed(job, reason);- return;- }- }-- await signerDAL.transaction(async (tx) => {- await signerDAL.updateById(- job.signerId,- {- certificateId,- status: SignerStatus.Active,- certificateFailureReason: null- },- tx- );- await signerIssuanceJobDAL.updateById(- job.id,- {- status: SignerIssuanceJobStatus.Completed,- certificateId,- failureReason: null- },- tx+ await signerIssuanceJobDAL.updateById(+ job.id,+ {+ status: SignerIssuanceJobStatus.Completed,+ certificateId,+ failureReason: null+ },+ tx+ );+ });+ } catch (txErr) {+ const reason = formatSignerIssuanceErrorReason(+ txErr,+ isHsmJob+ ? "Failed to atomically record HSM coordinates and attach the certificate to the signer"+ : "Failed to attach the issued certificate to the signer");- });+ await markJobFailed(job, reason);+ return;+ }logger.info(`signer issuance: signer attached [jobId=${job.id}] [signerId=${job.signerId}] [certificateId=${certificateId}]`);@@ -437,7 +457,7 @@ export const signerIssuanceServiceFactory = ({"HSM-backed signers are not supported with Azure AD CS yet. Use AWS Private CA, or switch the signer's key source to Infisical."});}- const azureResult = await azureAdCsFns.orderCertificateFromProfile({+ const azureResult = await azureAdCsFns.orderCertificateForSigner({caId: job.caId,commonName: job.commonName,altNames: [],@@ -453,7 +473,7 @@ export const signerIssuanceServiceFactory = ({}certificateId = azureResult.certificateId;} else {- const awsResult = await awsPcaFns.orderCertificateFromProfile({+ const awsResult = await awsPcaFns.orderCertificateForSigner({caId: job.caId,commonName: job.commonName,altNames: [],diff --git a/backend/src/services/signer/signer-service.ts b/backend/src/services/signer/signer-service.tsindex 800a7a3ac4..97a938d853 100644--- a/backend/src/services/signer/signer-service.ts+++ b/backend/src/services/signer/signer-service.ts@@ -56,9 +56,10 @@ import { TProjectDALFactory } from "../project/project-dal";import { getProjectKmsCertificateKeyId } from "../project/project-fns";import { isBuiltInSignerRole, unknownSignerRoleMessage } from "../signer-membership/signer-membership-service";import { TSignerDALFactory } from "./signer-dal";-import { CertKeySource, SignerStatus, SigningOperationStatus } from "./signer-enums";+import { CertKeySource, HsmKeyAlgorithm, SignerStatus, SigningOperationStatus } from "./signer-enums";import { formatSignerIssuanceErrorReason } from "./signer-issuance-errors";import {+ hsmKeyAlgorithmToCertKeyAlgorithm,issueHsmBackedSignerCertificate,issueSignerCertificate,mapCertKeyAlgorithmToHsmKeyAlgorithm,@@ -183,6 +184,61 @@ const validateSigningAlgorithmForKey = (signingAlgorithm: SigningAlgorithm, keyA}};+type TResolvedHsmReissue = {+ isHsm: true;+ switchingKeySource: boolean;+ keyAlgorithm: CertKeyAlgorithm;+ hsmConnectorId: string;+ hsmKeyAlgorithm: HsmKeyAlgorithm;+};+type TResolvedInfisicalReissue = {+ isHsm: false;+ switchingKeySource: boolean;+ keyAlgorithm: CertKeyAlgorithm;+};+type TResolvedReissueTarget = TResolvedHsmReissue | TResolvedInfisicalReissue;++export const resolveReissueTarget = ({+ dto,+ signer,+ currentCert+}: {+ dto: TReissueCertificateDTO;+ signer: { keyAlgorithm?: string | null };+ currentCert: {+ keySource?: string | null;+ keyAlgorithm?: string | null;+ hsmConnectorId?: string | null;+ } | null;+}): TResolvedReissueTarget => {+ const currentIsHsm =+ currentCert?.keySource === CertKeySource.Hsm &&+ Boolean(currentCert.hsmConnectorId) &&+ Boolean(currentCert.keyAlgorithm);+ const overrideKeySource = dto.certificate?.keySource;+ const switchingKeySource = overrideKeySource !== undefined && overrideKeySource !== currentCert?.keySource;+ const targetIsHsm = overrideKeySource ? overrideKeySource === CertKeySource.Hsm : currentIsHsm;++ if (targetIsHsm) {+ const hsmConnectorId = dto.certificate?.hsmConnectorId ?? currentCert?.hsmConnectorId ?? null;+ const hsmKeyAlgorithm =+ dto.certificate?.hsmKeyAlgorithm ??+ (currentCert?.keyAlgorithm ? mapCertKeyAlgorithmToHsmKeyAlgorithm(currentCert.keyAlgorithm) : undefined);+ if (!hsmConnectorId || !hsmKeyAlgorithm) {+ throw new BadRequestError({+ message: "hsmConnectorId and hsmKeyAlgorithm are required to (re)issue with an HSM key source."+ });+ }+ const keyAlgorithm = dto.certificate?.hsmKeyAlgorithm+ ? hsmKeyAlgorithmToCertKeyAlgorithm(dto.certificate.hsmKeyAlgorithm)+ : ((currentCert?.keyAlgorithm as CertKeyAlgorithm) ?? CertKeyAlgorithm.RSA_2048);+ return { isHsm: true, switchingKeySource, keyAlgorithm, hsmConnectorId, hsmKeyAlgorithm };+ }++ const keyAlgorithm = dto.keyAlgorithm ?? (signer.keyAlgorithm as CertKeyAlgorithm) ?? CertKeyAlgorithm.RSA_2048;+ return { isHsm: false, switchingKeySource, keyAlgorithm };+};+export const signerServiceFactory = ({signerDAL,signingOperationDAL,@@ -943,34 +999,52 @@ export const signerServiceFactory = ({});}+ const reissueCurrentCert = signer.certificateId ? await certificateDAL.findById(signer.certificateId) : null;+ const target = resolveReissueTarget({+ dto,+ signer,+ currentCert: reissueCurrentCert+ });++ if (reissueCaType === CaType.AZURE_AD_CS && target.isHsm) {+ throw new BadRequestError({+ message:+ "HSM-backed signers are not supported with Azure AD CS yet. Use AWS Private CA, an Internal CA, or switch the signer's key source to Infisical."+ });+ }++ if (target.isHsm) {+ await hsmConnectorService.assertAttachPermission(+ { type: dto.actor, id: dto.actorId, authMethod: dto.actorAuthMethod, orgId: dto.actorOrgId },+ target.hsmConnectorId,+ signer.projectId+ );+ }++ const { isHsm: targetIsHsm, switchingKeySource, keyAlgorithm: targetKeyAlgorithm } = target;+await signerDAL.updateById(dto.signerId, {caId: dto.caId,commonName: nextCommonName,- certificateTtlDays: effectiveTtl+ certificateTtlDays: effectiveTtl,+ keyAlgorithm: targetKeyAlgorithm});- const reissueKeyAlgorithm: CertKeyAlgorithm =- (signer.keyAlgorithm as CertKeyAlgorithm) ?? CertKeyAlgorithm.RSA_2048;-if (reissueIsExternal) {- const reissueCurrentCert = signer.certificateId ? await certificateDAL.findById(signer.certificateId) : null;- const reissueHsm =- reissueCurrentCert?.keySource === CertKeySource.Hsm &&- reissueCurrentCert.hsmConnectorId &&- reissueCurrentCert.keyAlgorithm- ? {- hsmConnectorId: reissueCurrentCert.hsmConnectorId,- hsmKeyAlgorithm: mapCertKeyAlgorithmToHsmKeyAlgorithm(reissueCurrentCert.keyAlgorithm),- hsmKeyLabel: reissueCurrentCert.hsmKeyLabel ?? undefined,- hsmPublicKeySpki: reissueCurrentCert.hsmPublicKeySpki ?? undefined,- actor: {- type: dto.actor,- id: dto.actorId,- authMethod: dto.actorAuthMethod,- orgId: dto.actorOrgId- }+ const reissueHsm = targetIsHsm+ ? {+ hsmConnectorId: target.hsmConnectorId,+ hsmKeyAlgorithm: target.hsmKeyAlgorithm,+ hsmKeyLabel: switchingKeySource ? undefined : (reissueCurrentCert?.hsmKeyLabel ?? undefined),+ hsmPublicKeySpki: switchingKeySource ? undefined : (reissueCurrentCert?.hsmPublicKeySpki ?? undefined),+ actor: {+ type: dto.actor,+ id: dto.actorId,+ authMethod: dto.actorAuthMethod,+ orgId: dto.actorOrgId}- : undefined;+ }+ : undefined;await signerDAL.updateById(dto.signerId, {status: SignerStatus.Pending,certificateFailureReason: null@@ -982,7 +1056,7 @@ export const signerServiceFactory = ({caId: dto.caId,commonName: nextCommonName,certificateTtlDays: nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS,- keyAlgorithm: reissueKeyAlgorithm,+ keyAlgorithm: targetKeyAlgorithm,hsm: reissueHsm});return await signerDAL.findById(dto.signerId);@@ -999,42 +1073,53 @@ export const signerServiceFactory = ({}try {- const currentCert = signer.certificateId ? await certificateDAL.findById(signer.certificateId) : null;- const currentIsHsm =- currentCert?.keySource === CertKeySource.Hsm &&- Boolean(currentCert.hsmConnectorId) &&- Boolean(currentCert.hsmKeyLabel) &&- Boolean(currentCert.keyAlgorithm);-let certificateId: string;- if (currentIsHsm && currentCert) {- await hsmConnectorService.assertAttachPermission(- { type: dto.actor, id: dto.actorId, authMethod: dto.actorAuthMethod, orgId: dto.actorOrgId },- currentCert.hsmConnectorId as string,- signer.projectId- );- const result = await renewHsmBackedSignerCertificate(- {- certificateAuthorityDAL,- internalCertificateAuthorityService,- certificateBodyDAL,- certificateDAL,- hsmConnectorService,- projectDAL,- kmsService- },- {- caId: dto.caId,- projectId: signer.projectId,- commonName: nextCommonName,- certificateTtlDays: nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS,- hsmConnectorId: currentCert.hsmConnectorId as string,- hsmKeyLabel: currentCert.hsmKeyLabel as string,- expectedPublicKeySpkiDer: currentCert.hsmPublicKeySpki ?? undefined,- hsmKeyAlgorithm: mapCertKeyAlgorithmToHsmKeyAlgorithm(currentCert.keyAlgorithm as string)- }- );- certificateId = result.certificateId;+ if (targetIsHsm) {+ if (switchingKeySource || !reissueCurrentCert?.hsmKeyLabel) {+ const result = await issueHsmBackedSignerCertificate(+ {+ certificateAuthorityDAL,+ internalCertificateAuthorityService,+ certificateBodyDAL,+ certificateDAL,+ hsmConnectorService,+ projectDAL,+ kmsService+ },+ {+ caId: dto.caId,+ projectId: signer.projectId,+ commonName: nextCommonName,+ certificateTtlDays: nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS,+ hsmConnectorId: target.hsmConnectorId,+ hsmKeyAlgorithm: target.hsmKeyAlgorithm+ }+ );+ certificateId = result.certificateId;+ } else {+ const result = await renewHsmBackedSignerCertificate(+ {+ certificateAuthorityDAL,+ internalCertificateAuthorityService,+ certificateBodyDAL,+ certificateDAL,+ hsmConnectorService,+ projectDAL,+ kmsService+ },+ {+ caId: dto.caId,+ projectId: signer.projectId,+ commonName: nextCommonName,+ certificateTtlDays: nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS,+ hsmConnectorId: target.hsmConnectorId,+ hsmKeyLabel: reissueCurrentCert.hsmKeyLabel as string,+ expectedPublicKeySpkiDer: reissueCurrentCert.hsmPublicKeySpki ?? undefined,+ hsmKeyAlgorithm: target.hsmKeyAlgorithm+ }+ );+ certificateId = result.certificateId;+ }} else {const result = await issueSignerCertificate({@@ -1050,7 +1135,7 @@ export const signerServiceFactory = ({projectId: signer.projectId,commonName: nextCommonName,certificateTtlDays: nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS,- keyAlgorithm: reissueKeyAlgorithm+ keyAlgorithm: targetKeyAlgorithm});certificateId = result.certificateId;diff --git a/backend/src/services/signer/signer-types.ts b/backend/src/services/signer/signer-types.tsindex 4bb1622569..11443f6ec9 100644--- a/backend/src/services/signer/signer-types.ts+++ b/backend/src/services/signer/signer-types.ts@@ -96,6 +96,8 @@ export type TReissueCertificateDTO = {caId: string;commonName?: string;certificateTtlDays?: number;+ keyAlgorithm?: CertKeyAlgorithm;+ certificate?: TSignerCertificateInput;} & TActorPermission;export type TExportCertificateDTO = {diff --git a/docs/cli/commands/gateway.mdx b/docs/cli/commands/gateway.mdxindex cc38e67e2f..467de768f2 100644--- a/docs/cli/commands/gateway.mdx+++ b/docs/cli/commands/gateway.mdx@@ -97,6 +97,17 @@ Once started, the gateway component will:```</Accordion>++ <Accordion title="--pkcs11-module">+ Absolute path to the PKCS#11 driver shipped by your HSM vendor. When set, the gateway loads the driver on startup and is reachable by HSM Connectors for signing operations.++ ```bash+ # Example+ infisical gateway start <gateway-name> --enroll-method=token --token=<token> --domain=<domain> --pkcs11-module=/opt/fortanix/pkcs11/fortanix_pkcs11.so+ ```++ See [HSM Connectors](/documentation/platform/pki/settings/hsm-connectors) for the full setup.+ </Accordion></AccordionGroup></Accordion>@@ -159,6 +170,17 @@ sudo infisical gateway systemd install my-gateway --enroll-method=token --token=**Note:** For Infisical Cloud users using instance relays, the relay infrastructure is already running and managed by Infisical. If using organization relays or self-hosted instance relays, you must first start a relay server. For more information on deploying relays, refer to the [Relay Deployment Guide](/documentation/platform/gateways/relay-deployment).</Accordion>++ <Accordion title="--pkcs11-module">+ Absolute path to the PKCS#11 driver shipped by your HSM vendor. When set, the systemd unit captures the flag so every restart loads the same driver and the gateway is reachable by HSM Connectors.++ ```bash+ # Example+ sudo infisical gateway systemd install my-gateway --enroll-method=token --token=<token> --domain=<domain> --pkcs11-module=/opt/fortanix/pkcs11/fortanix_pkcs11.so+ ```++ See [HSM Connectors](/documentation/platform/pki/settings/hsm-connectors) for the full setup.+ </Accordion></AccordionGroup>### Service Detailsdiff --git a/docs/docs.json b/docs/docs.jsonindex 39ff11f777..f1f6df7b1f 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -897,7 +897,13 @@"documentation/platform/pki/settings/policies","documentation/platform/pki/settings/profiles","documentation/platform/pki/settings/certificate-cleanup",- "documentation/platform/pki/settings/hsm-connectors"+ {+ "group": "HSM",+ "pages": [+ "documentation/platform/pki/settings/hsm-connectors",+ "documentation/platform/pki/settings/hsm-connectors-fortanix-dsm"+ ]+ }]}]diff --git a/docs/documentation/platform/pki/code-signing/signers.mdx b/docs/documentation/platform/pki/code-signing/signers.mdxindex 43c76708de..e5216ff731 100644--- a/docs/documentation/platform/pki/code-signing/signers.mdx+++ b/docs/documentation/platform/pki/code-signing/signers.mdx@@ -63,11 +63,10 @@ In **Certificate Manager → Code Signing → Signers**, click **Create Signer**| Field | Description ||-------|-------------|| **Certificate Authority** | The CA that issues the certificate. Internal CAs issue immediately. External CAs (AWS Private CA, Azure AD CS) issue asynchronously and the Signer enters **Pending** until the cert lands. |- | **Key source** | Where the leaf key for this Signer is generated. **Infisical-managed** (default) lets Infisical generate and manage the key for you. **HSM-backed** generates the key inside your own HSM through an [HSM Connector](/documentation/platform/pki/settings/hsm-connectors). |+ | **Key source** | Where the signing key is generated. **Infisical** (default) lets Infisical generate and manage the key for you. **HSM** generates the key inside your own HSM through an [HSM Connector](/documentation/platform/pki/settings/hsm-connectors). || **Common Name** | The legal name shown on the certificate, for example `Acme Mobile, Inc.`. Fixed once the certificate is issued. To change it you must reissue. |- | **Key algorithm** | The key for the signing certificate: `RSA-2048`, `RSA-3072`, `RSA-4096`, `ECDSA P-256`, `ECDSA P-384`, or `ECDSA P-521`. Shown only when **Key source = Infisical-managed**. |- | **HSM Connector** | The Connector that decides which Gateway routes operations to your HSM. Shown only when **Key source = HSM-backed**. See [HSM Connectors](/documentation/platform/pki/settings/hsm-connectors). |- | **HSM key algorithm** | Algorithm Infisical asks the HSM to generate: `RSA_2048`, `RSA_4096`, `ECC_P256`, or `ECC_P384`. Shown only when **Key source = HSM-backed**. |+ | **Key algorithm** | The signing key algorithm. With **Key source = Infisical**: `RSA-2048`, `RSA-3072`, `RSA-4096`, `ECDSA P-256`, `ECDSA P-384`, or `ECDSA P-521`. With **Key source = HSM**: `RSA_2048`, `RSA_4096`, `ECC_P256`, or `ECC_P384`. |+ | **HSM Connector** | The HSM Connector Infisical uses to reach your HSM. Set the Connector up first under **Certificate Manager > Settings > HSM Connectors**. Shown only when **Key source = HSM**. See [HSM Connectors](/documentation/platform/pki/settings/hsm-connectors). || **Validity (days)** | How long each issued certificate is valid for. Default 365. || **Renew before (days)** | Optional, 1 to 30. Auto-renew this many days before expiry. Must be less than Validity. Leave empty to disable auto-renewal. |@@ -98,16 +97,11 @@ In **Certificate Manager → Code Signing → Signers**, click **Create Signer**## HSM-backed Signers-When you pick **Key source = HSM-backed** on the Certificate step, two extra fields appear:+When you pick **Key source = HSM** on the Certificate step, pick the [HSM Connector](/documentation/platform/pki/settings/hsm-connectors) Infisical should use and the HSM key algorithm. The private key never leaves the HSM and every sign operation routes through the linked Connector. Infisical only holds the public key and the issued certificate.-| Field | Description |-|-------|-------------|-| **HSM Connector** | The [HSM Connector](/documentation/platform/pki/settings/hsm-connectors) Infisical uses to reach your HSM. Set the Connector up first under **Cert Manager Settings > HSM Connectors**. |-| **HSM key algorithm** | Algorithm the HSM generates for this Signer: `RSA_2048`, `RSA_4096`, `ECC_P256`, or `ECC_P384`. |+You can later switch an existing Signer between Infisical and HSM by reissuing the certificate with a different key source. Hit the [reissue endpoint](/api-reference/endpoints/code-signing/signers/reissue) with a `certificate.keySource` body, plus `hsmConnectorId` and `hsmKeyAlgorithm` when switching to HSM. The signer keeps its name, members, policy, and CA. Only the underlying key and the cert wrapping it change.-The private key never leaves the HSM. Every sign operation routes through the linked Connector. Infisical only ever holds the public key and the issued certificate. Key source is fixed at create time. To switch a Signer between Infisical-managed and HSM-backed, create a new Signer with the desired key source.--See [HSM Connectors](/documentation/platform/pki/settings/hsm-connectors) for the Gateway + Connector setup an HSM-backed Signer depends on.+See [HSM Connectors](/documentation/platform/pki/settings/hsm-connectors) for the setup an HSM-backed Signer depends on.## Signer statuses@@ -183,8 +177,10 @@ To sign with a Signer, pick the integration that matches your tooling:<Accordion title="What happens to signed artifacts when I delete a Signer?">Artifacts already signed remain valid as long as the certificate they were signed with is still valid and the verifier trusts the issuing CA's chain. Deleting the Signer in Infisical only removes Infisical's ability to sign new artifacts with that certificate. It does not invalidate past signatures.</Accordion>- <Accordion title="Can I migrate an existing Infisical-managed Signer to an HSM?">- Not in place. Key source is fixed at create time so the Signer's certificate and its key never go out of sync. Create a new HSM-backed Signer alongside the old one, route new sign traffic to it, and disable or delete the old Signer once you're satisfied.+ <Accordion title="Can I migrate an existing Signer between Infisical and an HSM?">+ Yes. Reissue the Signer's certificate with a different `certificate.keySource` via the [reissue endpoint](/api-reference/endpoints/code-signing/signers/reissue). When switching to HSM you also pass `hsmConnectorId` and `hsmKeyAlgorithm`. The signer keeps its name, members, approval policy, and CA. Only the key and the cert wrapping it change.++ The previous certificate stays in the inventory and still references its original HSM key (the HSM key itself is not deleted, only the Infisical-side reference). Delete or retire the old certificate before you try to delete the HSM Connector it referenced.</Accordion></AccordionGroup>diff --git a/docs/documentation/platform/pki/settings/hsm-connectors-fortanix-dsm.mdx b/docs/documentation/platform/pki/settings/hsm-connectors-fortanix-dsm.mdxnew file mode 100644index 0000000000..6f3f3249e6--- /dev/null+++ b/docs/documentation/platform/pki/settings/hsm-connectors-fortanix-dsm.mdx@@ -0,0 +1,93 @@+---+title: "Fortanix DSM"+sidebarTitle: "Fortanix DSM"+description: "Connect Infisical to Fortanix Data Security Manager via an HSM Connector."+---++This page covers the end-to-end setup for connecting Fortanix Data Security Manager (DSM) to Infisical through an HSM Connector. Read [HSM Connectors](/documentation/platform/pki/settings/hsm-connectors) first for the concept.++## Prerequisites++- A Fortanix DSM account with at least one group and an application configured for PKCS#11 access.+- A host inside your network that can reach your DSM endpoint over HTTPS, where you can install the Fortanix PKCS#11 client and run an [Infisical Gateway](/documentation/platform/gateways/overview).+- Project-level permission to create HSM Connectors in Infisical (`HSM Connectors > Create`).++## Step 1: Install the Fortanix PKCS#11 driver on the Gateway host++Download the Fortanix PKCS#11 client from the Fortanix DSM dashboard (Settings -> Client configurations) for the OS that will run the Gateway. Install it and confirm the driver file path is readable by the Gateway user:++```bash+ls -l /opt/fortanix/pkcs11/fortanix_pkcs11.so+```++The default install path on Linux is `/opt/fortanix/pkcs11/fortanix_pkcs11.so`. If you put it somewhere else, use that path everywhere in the steps below.++Create or copy the Fortanix client configuration file at `/etc/fortanix/pkcs11/pkcs11.conf`. The minimum keys are the DSM endpoint and the API key for the application that will be used as the PKCS#11 user. Fortanix provides the file content directly from the dashboard.++Verify the driver loads:++```bash+pkcs11-tool --module /opt/fortanix/pkcs11/fortanix_pkcs11.so --list-slots+```++You should see one slot per Fortanix DSM group your application is a member of, each with a slot label and a serial number.++## Step 2: Start the Gateway with the driver attached++Append `--pkcs11-module=/opt/fortanix/pkcs11/fortanix_pkcs11.so` to the Gateway start (or systemd install) command:++<Tabs>+ <Tab title="Linux (systemd)">+ ```bash+ sudo infisical gateway systemd install <gateway-name> \+ --enroll-method=token \+ --token=<enrollment-token> \+ --domain=<your-infisical-domain> \+ --pkcs11-module=/opt/fortanix/pkcs11/fortanix_pkcs11.so+ sudo systemctl start <gateway-name>+ ```+ </Tab>+ <Tab title="Foreground">+ ```bash+ infisical gateway start <gateway-name> \+ --enroll-method=token \+ --token=<enrollment-token> \+ --domain=<your-infisical-domain> \+ --pkcs11-module=/opt/fortanix/pkcs11/fortanix_pkcs11.so+ ```+ </Tab>+</Tabs>++Check the Gateway logs for a confirmation that the PKCS#11 module loaded.++## Step 3: Create the HSM Connector in Infisical++In **Certificate Manager > Settings > HSM Connectors**, click **Add HSM Connector** and fill in:++| Field | Value |+|-------|-------|+| **Name** | Slug-friendly identifier, e.g. `fortanix-prod`. |+| **Gateway** | The Gateway you started above (or a Pool that contains it). |+| **Slot label** | The Fortanix slot label from `pkcs11-tool --list-slots`. |+| **PIN** | The Fortanix application's PKCS#11 PIN. |+| **Key label prefix** | Optional. Useful if your DSM hosts keys for multiple environments. |++On submit Infisical runs a Verify round-trip through the Gateway. A wrong PIN, missing slot label, or unreachable Gateway is caught here and the Connector is not persisted.++## Troubleshooting++- **"slot not found" on Verify**: confirm the slot label matches what `pkcs11-tool --list-slots` reports. Fortanix slot labels are case-sensitive.+- **"login failed" on Verify**: re-check the PIN. The PIN is the Fortanix application's PKCS#11 PIN, not the DSM account password.+- **"gateway unreachable"**: the Gateway must be running with HSM support enabled. Check the Gateway log for the PKCS#11 module load line.+- **Slow operations**: if the Gateway host can't reach DSM over HTTPS with low latency, every sign call pays the round-trip. Run the Gateway in the same network as DSM whenever possible.++## What's next?++<CardGroup cols={2}>+ <Card title="HSM Connectors" icon="shield-halved" href="/documentation/platform/pki/settings/hsm-connectors">+ Concept overview and the generic setup flow.+ </Card>+ <Card title="Signers" icon="signature" href="/documentation/platform/pki/code-signing/signers">+ Create an HSM-backed Signer that uses this Connector.+ </Card>+</CardGroup>diff --git a/docs/documentation/platform/pki/settings/hsm-connectors.mdx b/docs/documentation/platform/pki/settings/hsm-connectors.mdxindex ecd9e5076d..78da69e8f8 100644--- a/docs/documentation/platform/pki/settings/hsm-connectors.mdx+++ b/docs/documentation/platform/pki/settings/hsm-connectors.mdx@@ -1,55 +1,72 @@---title: "HSM Connectors"-sidebarTitle: "HSM Connectors"+sidebarTitle: "Overview"description: "Register a Hardware Security Module that Infisical reaches through one of your Gateways."----An **HSM Connector** is a resource that tells Infisical how to reach a slot on your Hardware Security Module. The Connector carries the routing (which Gateway can talk to the HSM) and the credentials (slot label, PIN) needed to authenticate to that slot. Infisical features that support HSM-backed keys reference the Connector to perform PKCS#11 operations on your HSM.+An **HSM Connector** is the resource you create in Infisical to register a slot on your Hardware Security Module. It holds the slot's credentials (slot label, PIN) and a reference to a [Gateway](/documentation/platform/gateways/overview) running inside your network that can talk to the HSM. Infisical features that support HSM-backed keys reference the Connector when they need to perform PKCS#11 operations on your HSM.-Infisical never talks to the HSM directly. A Gateway you run inside your network does, using your HSM vendor's PKCS#11 driver. The Connector itself stores nothing about your HSM keys. It is a routing and credentials record.+The Connector itself stores no key material. It is a credentials and routing record. Infisical never talks to the HSM directly. Instead, a Gateway acts as the bridge, loading your HSM vendor's PKCS#11 driver in the network where the HSM lives.++## Before you start++Have these on hand before you create a Connector:++- A **running, HSM-capable Gateway** on a host that can reach your HSM. New to Gateways? Start at [Gateway Deployment](/documentation/platform/gateways/gateway-deployment), then come back. The Gateway must be started with `--pkcs11-module=<absolute path>` so it loads your HSM's PKCS#11 driver.+- The **absolute path to the PKCS#11 driver** (`.so` on Linux, `.dll` on Windows) provided by your HSM vendor.+- The **slot label** and **PIN** of the HSM slot Infisical should use. Both come from your HSM provider.## How it fits together+At the top level there are three actors:++```mermaid+graph LR+ A[Infisical] --> B[Gateway<br/>on your network]+ B --> C[Your HSM]+```++The detailed exchange Infisical performs against the HSM through the Gateway looks like this:+```mermaidsequenceDiagram- participant Caller as Caller<br/>participant Infisical as Infisical- participant Gateway as Gateway<br/>(--pkcs11-module)- participant HSM as Your HSM<br/>+ participant Gateway as Gateway<br/>(HSM-enabled)+ participant HSM as Your HSM- Caller->>Infisical: Operation that uses an HSM Connector- Infisical->>Gateway: PKCS#11 request+ Infisical->>Gateway: PKCS#11 request via HSM ConnectorGateway->>HSM: C_* call via vendor driverHSM-->>Gateway: ResultGateway-->>Infisical: Result- Infisical-->>Caller: Response```Three pieces have to be in place for an HSM Connector to be usable:-1. **A Gateway** running on a host that can talk to your HSM, started with `--pkcs11-module=<path to vendor .so/.dll>`.+1. **A Gateway** running on a host that can talk to your HSM, started with `--pkcs11-module=<path to vendor .so/.dll>`. See [Gateway Deployment](/documentation/platform/gateways/gateway-deployment).2. **An HSM Connector** that points at that Gateway (or a Pool that contains it) and carries the slot credentials.3. **A consumer**, a feature that supports HSM-backed keys. See the feature's own docs for how it references an HSM Connector.## Run a Gateway with PKCS#11 enabled-The same Gateway binary you already deploy can serve HSM operations: just pass the PKCS#11 driver path at start time. A Gateway started without that flag stays a regular Gateway. HSM Connectors will skip it automatically.+The Gateway is the agent Infisical talks to when it needs your HSM. You install it once on a host inside your network, start it with your HSM's PKCS#11 driver path, and Infisical routes every HSM operation through it. A Gateway started without the PKCS#11 driver path is not eligible for HSM Connectors and is skipped automatically.++If you have never deployed a Gateway before, read [Gateway Deployment](/documentation/platform/gateways/gateway-deployment) first for the general install and auth flow, then return here for the HSM-specific flag.<Steps><Step title="Install your HSM's PKCS#11 driver on the Gateway host">- Install the PKCS#11 library shipped by your HSM vendor on the same machine where the Gateway will run. Note the absolute path to the `.so` or `.dll`. You will pass it to the Gateway in the next step.+ Install the PKCS#11 library shipped by your HSM vendor on the machine where the Gateway will run. Note the absolute path to the `.so` or `.dll`. You will pass it to the Gateway in the next step.- For example, a Fortanix DSM deployment typically installs its driver at `/opt/fortanix/pkcs11/fortanix_pkcs11.so`. Any vendor with a PKCS#11 driver works the same way.+ For example, the Fortanix DSM PKCS#11 driver is commonly placed at `/opt/fortanix/pkcs11/fortanix_pkcs11.so` by Fortanix's installer, though you can put it anywhere the Gateway process can read.Follow the vendor's onboarding to provision a slot, configure operator credentials, and confirm `pkcs11-tool --module <driver> --list-slots` returns the expected slot label.</Step><Step title="Create the Gateway in the Infisical UI">- Go to **Organization Settings > Networking > Gateways**, click **Create Gateway**, name it, and pick an auth method. Then click **Show deploy command** and copy the install command for your platform. This is the same flow as a regular Gateway. See [Gateway Deployment](/documentation/platform/gateways/gateway-deployment) for full setup detail (relay, firewall, AWS or token auth).+ Go to **Organization Settings > Networking > Gateways**, click **Create Gateway**, name it, and pick an auth method. Then click **Show deploy command** and copy the install command for your platform. See [Gateway Deployment](/documentation/platform/gateways/gateway-deployment) for full setup detail (relay, firewall, AWS or token auth).</Step><Step title="Start the Gateway with --pkcs11-module">- Append `--pkcs11-module=<absolute path>` to the start command. The Gateway loads the driver once on startup, advertises PKCS#11 capability in its heartbeat, and serves HSM operations alongside its other traffic.+ Append `--pkcs11-module=<absolute path>` to the start command. The Gateway loads the driver once on startup and serves HSM operations alongside its other traffic.<Tabs><Tab title="Linux (Production)">@@ -75,7 +92,7 @@ The same Gateway binary you already deploy can serve HSM operations: just pass t</Tab></Tabs>- On startup you should see a log line like `PKCS#11 module loaded, Gateway will serve HSM requests`. If the driver path is wrong or unreadable, the Gateway exits with an error before connecting.+ On startup you should see a log line confirming the PKCS#11 module loaded. If the driver path is wrong or unreadable, the Gateway exits with an error before connecting.</Step><Step title="(Optional) Add the Gateway to a Pool">@@ -84,12 +101,12 @@ The same Gateway binary you already deploy can serve HSM operations: just pass t</Steps><Note>-PKCS#11 driver libraries are vendor-specific binaries. Place them on the Gateway host with the same file permissions the Gateway process expects to read, and verify the driver matches your HSM firmware version before connecting it to production traffic.+PKCS#11 driver libraries are vendor-specific binaries. Make sure the file is readable by the user running the Gateway (typically owner-only readable, mode 0640 with the Gateway user in the owning group, or 0644 if simpler). Verify the driver matches your HSM firmware version before connecting it to production traffic.</Note>## Create an HSM Connector-Once you have a PKCS#11-enabled Gateway running and heartbeating, create the Connector in Cert Manager.+Once you have a PKCS#11-enabled Gateway running, create the Connector in Cert Manager.In **Certificate Manager > Settings > HSM Connectors**, click **Add HSM Connector**. The wizard walks you through three steps.@@ -101,16 +118,16 @@ In **Certificate Manager > Settings > HSM Connectors**, click **Add HSM Connecto| **Description** | Optional. Context for your team. Example: *Fortanix DSM, production keys*. |</Step>- <Step title="Reached from">- Pick how Infisical reaches your HSM:+ <Step title="Connection">+ Pick the **Gateway** Infisical uses to reach your HSM:- **Gateway**: route every operation through one specific Gateway. Use this if you have a single PKCS#11-enabled Gateway, or if you want strict routing.- - **Gateway Pool**: route through any healthy, PKCS#11-capable member of the pool. Recommended for production so a single Gateway outage doesn't stop operations. Non-PKCS#11 members of the pool (regular Gateways serving other resources) are skipped automatically.+ - **Gateway Pool**: route through any healthy, PKCS#11-capable member of the pool. Recommended for production so a single Gateway outage doesn't stop operations. Pool members without PKCS#11 enabled are skipped automatically.- Only Gateways that have advertised PKCS#11 capability in their last heartbeat are eligible. The "Reached from" step shows the filtered list. If the dropdown is empty, double-check the Gateway is running with `--pkcs11-module`.+ Only HSM-capable Gateways are eligible. The Gateway dropdown shows the filtered list. If it's empty, double-check the Gateway is running with `--pkcs11-module`.</Step>- <Step title="Access">+ <Step title="Credentials">Supply the credentials Infisical uses to authenticate to the HSM slot through the Gateway.| Field | Description |@@ -119,12 +136,10 @@ In **Certificate Manager > Settings > HSM Connectors**, click **Add HSM Connecto| **PIN** | The PKCS#11 user PIN for that slot. Stored encrypted with your KMS key, sent to the Gateway over the proxied TLS channel on every request. || **Key label prefix** | Optional prefix prepended to every key label Infisical creates in this slot. Example: `infisical-` produces labels like `infisical-{id}`. Useful when the HSM hosts keys for multiple applications. |- Click **Create HSM Connector**. Infisical runs a Verify against the HSM before persisting the Connector. Wrong PIN, unknown slot label, or unreachable Gateway are caught at this point and the Connector is not saved.+ Click **Add HSM Connector**. Infisical runs a Verify against the HSM before persisting the Connector. Wrong PIN, unknown slot label, or unreachable Gateway are caught at this point and the Connector is not saved.</Step></Steps>-After creation, the Connector appears in the list with a per-row **Verify** action that re-runs the same round-trip on demand.-## FAQ<AccordionGroup>@@ -138,7 +153,19 @@ After creation, the Connector appears in the list with a per-row **Verify** actiNo. Connectors routed through a pool ignore non-capable members. You can mix one or two PKCS#11-enabled Gateways with the rest of your pool freely.</Accordion><Accordion title="Which mechanisms are supported?">- The PKCS#11 bridge supports `CKM_RSA_PKCS`, `CKM_SHA256_RSA_PKCS`, `CKM_SHA384_RSA_PKCS`, `CKM_SHA512_RSA_PKCS`, and `CKM_ECDSA_SHA256` / `SHA384` / `SHA512`. Key algorithms supported for generation are `RSA_2048`, `RSA_4096`, `ECC_P256`, and `ECC_P384`.+ The PKCS#11 bridge supports the following signing mechanisms:++ | Mechanism | What it does |+ |-----------|--------------|+ | RSA PKCS#1 v1.5 | Raw RSA signing of a pre-hashed digest |+ | SHA-256 with RSA PKCS#1 v1.5 | RSA signing with SHA-256 inside the HSM |+ | SHA-384 with RSA PKCS#1 v1.5 | RSA signing with SHA-384 inside the HSM |+ | SHA-512 with RSA PKCS#1 v1.5 | RSA signing with SHA-512 inside the HSM |+ | ECDSA with SHA-256 | ECDSA signing with SHA-256 inside the HSM |+ | ECDSA with SHA-384 | ECDSA signing with SHA-384 inside the HSM |+ | ECDSA with SHA-512 | ECDSA signing with SHA-512 inside the HSM |++ Key algorithms supported for generation: RSA 2048-bit, RSA 4096-bit, ECDSA P-256, and ECDSA P-384.</Accordion><Accordion title="Can I rotate the PIN without recreating resources that reference the Connector?">Yes. Edit the Connector and update the PIN. The next operation uses the new credential. Existing references continue to work unchanged.@@ -148,10 +175,13 @@ After creation, the Connector appears in the list with a per-row **Verify** acti## What's next?<CardGroup cols={2}>+ <Card title="Fortanix DSM" icon="shield-halved" href="/documentation/platform/pki/settings/hsm-connectors-fortanix-dsm">+ Step-by-step Fortanix Data Security Manager setup.+ </Card><Card title="Gateway Deployment" icon="server" href="/documentation/platform/gateways/gateway-deployment">Full Gateway setup including relay, firewall, and AWS auth.</Card><Card title="Gateway Pools" icon="object-group" href="/documentation/platform/gateways/gateway-pools">- Group PKCS#11-enabled Gateways for high availability.+ Group HSM-capable Gateways for high availability.</Card></CardGroup>diff --git a/frontend/src/hooks/api/hsmConnectors/mutations.tsx b/frontend/src/hooks/api/hsmConnectors/mutations.tsxindex 8c81c4f13b..f006cec58a 100644--- a/frontend/src/hooks/api/hsmConnectors/mutations.tsx+++ b/frontend/src/hooks/api/hsmConnectors/mutations.tsx@@ -15,13 +15,13 @@ export const useCreateHsmConnector = () => {return useMutation({mutationFn: async (payload: TCreateHsmConnectorPayload) => {const { data } = await apiRequest.post<{ hsmConnector: THsmConnector }>(- "/api/v1/cert-manager/hsm-connectors",+ "/api/v1/hsm-connectors",payload);return data.hsmConnector;},onSuccess: () => {- queryClient.invalidateQueries({ queryKey: hsmConnectorKeys.list() });+ queryClient.invalidateQueries({ queryKey: hsmConnectorKeys.all });}});};@@ -31,16 +31,16 @@ export const useUpdateHsmConnector = () => {return useMutation({mutationFn: async ({ connectorId, ...patch }: TUpdateHsmConnectorPayload) => {const { data } = await apiRequest.patch<{ hsmConnector: THsmConnector }>(- `/api/v1/cert-manager/hsm-connectors/${connectorId}`,+ `/api/v1/hsm-connectors/${connectorId}`,patch);return data.hsmConnector;},onSuccess: (_data, variables) => {- queryClient.invalidateQueries({ queryKey: hsmConnectorKeys.list() });+ queryClient.invalidateQueries({ queryKey: hsmConnectorKeys.all });queryClient.invalidateQueries({ queryKey: hsmConnectorKeys.byId(variables.connectorId) });queryClient.invalidateQueries({- queryKey: hsmConnectorKeys.linkedCertificatesAll(variables.connectorId)+ queryKey: hsmConnectorKeys.linkedResourcesAll(variables.connectorId)});}});@@ -51,7 +51,7 @@ export const useDeleteHsmConnector = () => {return useMutation({mutationFn: async ({ connectorId }: { connectorId: string }) => {const { data } = await apiRequest.delete<{ id: string }>(- `/api/v1/cert-manager/hsm-connectors/${connectorId}`+ `/api/v1/hsm-connectors/${connectorId}`);return data;},@@ -65,7 +65,7 @@ export const useTestHsmConnector = () => {return useMutation({mutationFn: async ({ connectorId }: { connectorId: string }) => {const { data } = await apiRequest.post<THsmConnectorTestResult>(- `/api/v1/cert-manager/hsm-connectors/${connectorId}/test`+ `/api/v1/hsm-connectors/${connectorId}/test`);return data;}diff --git a/frontend/src/hooks/api/hsmConnectors/queries.tsx b/frontend/src/hooks/api/hsmConnectors/queries.tsxindex ea1a0aeecb..7449e26881 100644--- a/frontend/src/hooks/api/hsmConnectors/queries.tsx+++ b/frontend/src/hooks/api/hsmConnectors/queries.tsx@@ -6,26 +6,28 @@ import { THsmConnector, THsmConnectorLinkedCertificate } from "./types";export const hsmConnectorKeys = {all: ["hsm-connectors"] as const,- list: () => [...hsmConnectorKeys.all, "list"] as const,+ listByProject: (projectId: string) => [...hsmConnectorKeys.all, "list", projectId] as const,byId: (id: string) => [...hsmConnectorKeys.all, "by-id", id] as const,- linkedCertificatesAll: (id: string) =>- [...hsmConnectorKeys.all, "linked-certificates", id] as const,- linkedCertificates: (id: string, pagination: { offset: number; limit: number }) =>- [...hsmConnectorKeys.linkedCertificatesAll(id), pagination] as const+ linkedResourcesAll: (id: string) => [...hsmConnectorKeys.all, "linked-resources", id] as const,+ linkedResources: (id: string, pagination: { offset: number; limit: number }) =>+ [...hsmConnectorKeys.linkedResourcesAll(id), pagination] as const};export const useListHsmConnectors = (+ projectId: string | undefined,options?: Omit<UseQueryOptions<THsmConnector[]>, "queryKey" | "queryFn">) => {return useQuery({- queryKey: hsmConnectorKeys.list(),+ ...options,+ queryKey: hsmConnectorKeys.listByProject(projectId ?? ""),queryFn: async () => {const { data } = await apiRequest.get<{ hsmConnectors: THsmConnector[] }>(- "/api/v1/cert-manager/hsm-connectors"+ "/api/v1/hsm-connectors",+ { params: { projectId } });return data.hsmConnectors;},- ...options+ enabled: Boolean(projectId) && (options?.enabled ?? true)});};@@ -38,7 +40,7 @@ export const useGetHsmConnectorById = (queryKey: hsmConnectorKeys.byId(connectorId ?? ""),queryFn: async () => {const { data } = await apiRequest.get<{ hsmConnector: THsmConnector }>(- `/api/v1/cert-manager/hsm-connectors/${connectorId}`+ `/api/v1/hsm-connectors/${connectorId}`);return data.hsmConnector;},@@ -46,11 +48,11 @@ export const useGetHsmConnectorById = (});};-export const useListHsmConnectorLinkedCertificates = (+export const useListHsmConnectorLinkedResources = (connectorId: string | undefined,pagination?: { offset?: number; limit?: number },options?: Omit<- UseQueryOptions<{ linkedCertificates: THsmConnectorLinkedCertificate[]; totalCount: number }>,+ UseQueryOptions<{ certificates: THsmConnectorLinkedCertificate[]; totalCount: number }>,"queryKey" | "queryFn">) => {@@ -58,16 +60,16 @@ export const useListHsmConnectorLinkedCertificates = (return useQuery({...options,- queryKey: hsmConnectorKeys.linkedCertificates(connectorId ?? "", { offset, limit }),+ queryKey: hsmConnectorKeys.linkedResources(connectorId ?? "", { offset, limit }),queryFn: async () => {const { data } = await apiRequest.get<{- linkedCertificates: THsmConnectorLinkedCertificate[];+ certificates: THsmConnectorLinkedCertificate[];totalCount: number;- }>(`/api/v1/cert-manager/hsm-connectors/${connectorId}/linked-certificates`, {+ }>(`/api/v1/hsm-connectors/${connectorId}/linked-resources`, {params: { offset, limit }});return {- linkedCertificates: data.linkedCertificates ?? [],+ certificates: data.certificates ?? [],totalCount: data.totalCount ?? 0};},diff --git a/frontend/src/hooks/api/hsmConnectors/types.ts b/frontend/src/hooks/api/hsmConnectors/types.tsindex 327b6b5110..bb56e41621 100644--- a/frontend/src/hooks/api/hsmConnectors/types.ts+++ b/frontend/src/hooks/api/hsmConnectors/types.ts@@ -14,6 +14,7 @@ export type THsmConnector = {};export type TCreateHsmConnectorPayload = {+ projectId: string;name: string;description?: string;gatewayId?: string;diff --git a/frontend/src/hooks/api/signers/types.ts b/frontend/src/hooks/api/signers/types.tsindex f570e8038a..79d6edf336 100644--- a/frontend/src/hooks/api/signers/types.ts+++ b/frontend/src/hooks/api/signers/types.ts@@ -282,6 +282,12 @@ export type TReissueSignerCertificateDTO = {caId: string;commonName?: string;certificateTtlDays?: number;+ keyAlgorithm?: SignerKeyAlgorithm;+ certificate?: {+ keySource: CertKeySource;+ hsmConnectorId?: string;+ hsmKeyAlgorithm?: HsmKeyAlgorithm;+ };};export type TEnableSignerDTO = { signerId: string };diff --git a/frontend/src/hooks/api/subscriptions/types.ts b/frontend/src/hooks/api/subscriptions/types.tsindex a8d0b15e78..4d73a7d354 100644--- a/frontend/src/hooks/api/subscriptions/types.ts+++ b/frontend/src/hooks/api/subscriptions/types.ts@@ -63,7 +63,6 @@ export type SubscriptionPlan = {pkiAcme: boolean;pkiLegacyTemplates: boolean;pkiPqc: boolean;- pkiHsm: boolean;kmsPqc: boolean;enforceMfa: boolean;enforceGoogleSSO: boolean;diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsxindex 5cbc624c4c..5acb01458a 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx@@ -63,7 +63,7 @@ export const CertificateStep = ({};const { subscription } = useSubscription();- const isHsmLicensed = Boolean(subscription?.pkiHsm);+ const isHsmLicensed = Boolean(subscription?.hsm);const { permission } = useProjectPermission();const canAttachHsm = permission.can(ProjectPermissionHsmConnectorActions.Attach,@@ -156,10 +156,10 @@ export const CertificateStep = ({<SelectValue /></SelectTrigger><SelectContent position="popper">- <SelectItem value={CertKeySource.Infisical}>Infisical-managed key</SelectItem>+ <SelectItem value={CertKeySource.Infisical}>Infisical</SelectItem><SelectItem value={CertKeySource.Hsm} disabled={!isHsmLicensed || !canAttachHsm}><div className="flex items-center gap-2">- HSM-backed key+ HSM{!isHsmLicensed && <Badge variant="info">Enterprise</Badge>}{isHsmLicensed && !canAttachHsm && (<Badge variant="warning">Permission required</Badge>@@ -254,7 +254,7 @@ export const CertificateStep = ({render={({ field, fieldState: { error } }) => (<Field><FieldLabel>- HSM key algorithm <span className="text-danger">*</span>+ Key algorithm <span className="text-danger">*</span></FieldLabel><FieldContent><Select value={field.value} onValueChange={field.onChange}>diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsxindex b2bc737fc1..f7d8a80d42 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx@@ -69,9 +69,12 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =});const groupsQuery = useGetOrganizationGroups(orgId);const { subscription } = useSubscription();- const { data: hsmConnectors = [], isPending: isHsmConnectorsLoading } = useListHsmConnectors({- enabled: Boolean(subscription?.pkiHsm)- });+ const { data: hsmConnectors = [], isPending: isHsmConnectorsLoading } = useListHsmConnectors(+ projectId,+ {+ enabled: Boolean(subscription?.hsm)+ }+ );const createSigner = useCreateSigner();diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.tsindex 92c3901516..1050246dff 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts@@ -100,7 +100,7 @@ export const STEPS: WizardStep[] = [subtitle: "Pick the Certificate Authority and the name on the certificate.",rightLabel: "CERTIFICATE",rightDescription:- "Tells Infisical which CA issues the signing certificate, the name shown on it, and how long it stays valid. The Common Name is fixed once issued. Pick the key source here. HSM-backed adds two extra fields inline (connector and HSM key algorithm).",+ "Tells Infisical which CA issues the signing certificate, the name shown on it, and how long it stays valid. The Common Name is fixed once issued. Pick the key source: Infisical or HSM (the keypair stays inside your own HSM).",docsUrl: PkiDocsUrls.codeSigning.signers.certificate},{diff --git a/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/HsmConnectorLinkedCertsSection.tsx b/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/HsmConnectorLinkedCertsSection.tsxindex 1d2afe4fa4..6cfecb7f90 100644--- a/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/HsmConnectorLinkedCertsSection.tsx+++ b/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/HsmConnectorLinkedCertsSection.tsx@@ -27,18 +27,18 @@ import {} from "@app/components/v3";import { useOrganization, useProject } from "@app/context";import { CertStatus } from "@app/hooks/api/certificates/enums";-import { useListHsmConnectorLinkedCertificates } from "@app/hooks/api/hsmConnectors";+import { useListHsmConnectorLinkedResources } from "@app/hooks/api/hsmConnectors";type Props = { connectorId: string };export const HsmConnectorLinkedCertsSection = ({ connectorId }: Props) => {const [page, setPage] = useState(1);const [perPage, setPerPage] = useState(20);- const { data, isPending } = useListHsmConnectorLinkedCertificates(connectorId, {+ const { data, isPending } = useListHsmConnectorLinkedResources(connectorId, {offset: (page - 1) * perPage,limit: perPage});- const linked = data?.linkedCertificates ?? [];+ const linked = data?.certificates ?? [];const totalCount = data?.totalCount ?? 0;const navigate = useNavigate();const { currentProject } = useProject();diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/BasicsStep.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/BasicsStep.tsxindex 091d5fdf3c..d2d0d3628e 100644--- a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/BasicsStep.tsx+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/BasicsStep.tsx@@ -46,7 +46,7 @@ export const BasicsStep = ({ form }: Props) => (<TextArea{...field}value={field.value ?? ""}- placeholder="What this HSM is used for (e.g. production macOS code-signing keys)."+ placeholder="What this HSM is used for (e.g. production signing keys)."rows={3}isError={Boolean(error)}/>diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsxindex 96e4f315a3..e8ef6d21b5 100644--- a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx@@ -2,24 +2,19 @@ import { useMemo, useState } from "react";import { useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { useQuery } from "@tanstack/react-query";-import { CheckIcon, ClipboardListIcon, ShieldCheckIcon } from "lucide-react";+import { ShieldCheckIcon } from "lucide-react";import { createNotification } from "@app/components/notifications";import {Button,- IconButton,Sheet,SheetContent,SheetHeader,SheetTitle,Stepper,StepperList,- StepperStep,- Tooltip,- TooltipContent,- TooltipTrigger+ StepperStep} from "@app/components/v3";-import { useTimedReset } from "@app/hooks";import { useListGatewayPools } from "@app/hooks/api/gateway-pools";import { gatewaysQueryKeys } from "@app/hooks/api/gateways/queries";import { useCreateHsmConnector } from "@app/hooks/api/hsmConnectors";@@ -37,24 +32,16 @@ import {} from "./schemas";import { INITIAL_WIZARD_STATE, STEPS, WizardState } from "./types";-const GATEWAY_PKCS11_COMMAND = `infisical gateway start <name> \\- --enroll-method=token \\- --token=<enrollment-token> \\- --domain=<your-infisical-domain> \\- --pkcs11-module=/path/to/vendor.so`;-type Props = {+ projectId: string;isOpen: boolean;onOpenChange: (open: boolean) => void;};-export const CreateHsmConnectorWizard = ({ isOpen, onOpenChange }: Props) => {+export const CreateHsmConnectorWizard = ({ projectId, isOpen, onOpenChange }: Props) => {const [step, setStep] = useState(0);const [state, setState] = useState<WizardState>(INITIAL_WIZARD_STATE);const [submitting, setSubmitting] = useState(false);- const [, isCommandCopied, setCommandCopyState] = useTimedReset<string>({- initialState: "Copy"- });const { data: gateways = [], isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());const { data: pools = [], isPending: isPoolsLoading } = useListGatewayPools();@@ -109,6 +96,7 @@ export const CreateHsmConnectorWizard = ({ isOpen, onOpenChange }: Props) => {try {const [kind, id] = finalState.reachedFrom.split(":");await createMutation.mutateAsync({+ projectId,name: finalState.name,description: finalState.description.trim() || undefined,gatewayId: kind === "gateway" ? id : undefined,@@ -193,8 +181,7 @@ export const CreateHsmConnectorWizard = ({ isOpen, onOpenChange }: Props) => {Add HSM Connector</div><p className="text-sm leading-4 text-mineshaft-400">- Register the hardware security module that holds your signing keys. Infisical- reaches it through one of your hosts.+ Register the hardware security module that holds your signing keys.</p></div></div>@@ -258,50 +245,18 @@ export const CreateHsmConnectorWizard = ({ isOpen, onOpenChange }: Props) => {<div className="mt-auto space-y-3">{step === 1 && (<div className="max-w-full space-y-2 rounded-md border border-border bg-mineshaft-800 p-3 text-xs">- <p className="font-semibold text-foreground">Start a Gateway with PKCS#11</p>+ <p className="font-semibold text-foreground">No HSM-capable Gateway yet?</p><p className="text-muted">- Run this on a machine that can reach your HSM. Use your vendor's PKCS#11- library path for <code className="text-mineshaft-200">--pkcs11-module</code>.- </p>- <div className="relative">- <pre className="max-w-full overflow-x-auto rounded bg-mineshaft-900 p-2 pr-8 text-[11px] break-all whitespace-pre-wrap text-mineshaft-200">- {GATEWAY_PKCS11_COMMAND}- </pre>- <Tooltip>- <TooltipTrigger asChild>- <IconButton- variant="ghost"- size="xs"- aria-label="Copy command"- className="absolute top-1 right-1"- onClick={() => {- navigator.clipboard.writeText(GATEWAY_PKCS11_COMMAND);- setCommandCopyState("Copied");- }}- >- {isCommandCopied ? (- <CheckIcon className="size-3.5" />- ) : (- <ClipboardListIcon className="size-3.5 text-label" />- )}- </IconButton>- </TooltipTrigger>- <TooltipContent>- {isCommandCopied ? "Copied" : "Copy command"}- </TooltipContent>- </Tooltip>- </div>- <p className="pt-1 text-muted">- Full guide:{" "}+ Follow the{" "}<a- href="https://infisical.com/docs/documentation/platform/pki/code-signing/hsm-connectors"+ href="https://infisical.com/docs/documentation/platform/pki/settings/hsm-connectors"target="_blank"rel="noreferrer"className="text-primary hover:underline">- HSM Connectors docs- </a>- .+ HSM Connectors guide+ </a>{" "}+ for the step-by-step Gateway setup.</p></div>)}diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/HostStep.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/HostStep.tsxindex b9e6cf3366..64a168b12b 100644--- a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/HostStep.tsx+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/HostStep.tsx@@ -33,7 +33,7 @@ export const HostStep = ({ form, options, isLoading }: Props) => (render={({ field, fieldState: { error } }) => (<Field><FieldLabel>- Reached from <span className="text-danger">*</span>+ Gateway <span className="text-danger">*</span></FieldLabel><FieldContent><FilterableSelect<ReachedFromOption>@@ -53,12 +53,23 @@ export const HostStep = ({ form, options, isLoading }: Props) => (group === "gateway" ? "Gateways" : "Gateway Pools": undefined}- placeholder="Select a Gateway..."- noOptionsMessage={() => "No PKCS#11-enabled Gateways found."}+ placeholder="Select a Gateway or Gateway Pool..."+ noOptionsMessage={() => "No Gateways connected to an HSM yet."}isError={Boolean(error)}/><FieldDescription>- The Infisical Gateway that will reach the HSM over PKCS#11.+ A{" "}+ <a+ href="https://infisical.com/docs/documentation/platform/gateways/overview"+ target="_blank"+ rel="noreferrer"+ className="underline"+ >+ Gateway+ </a>{" "}+ is a lightweight agent you run inside your own network. Infisical sends signing+ requests to it, and it talks to the HSM directly. Only Gateways started with your+ HSM's PKCS#11 driver appear here.</FieldDescription><FieldError errors={[error]} /></FieldContent>@@ -70,16 +81,12 @@ export const HostStep = ({ form, options, isLoading }: Props) => (<div className="rounded-md border border-border bg-mineshaft-800 p-4"><div className="flex items-start gap-3"><ServerIcon className="mt-0.5 size-4 shrink-0 text-mineshaft-400" />- <div className="space-y-1 text-sm">- <p className="font-medium text-foreground">No PKCS#11-enabled Gateways yet</p>- <p className="text-muted">- Start an Infisical Gateway on a machine that can reach your HSM, passing your HSM- vendor's PKCS#11 library:- </p>- <pre className="mt-2 overflow-x-auto rounded bg-mineshaft-900 p-2 text-xs text-mineshaft-200">- infisical gateway start my-gateway --pkcs11-module=/path/to/vendor.so+ <div className="min-w-0 flex-1 space-y-2 text-sm">+ <p className="font-medium text-foreground">No Gateways are connected to an HSM yet</p>+ <p className="text-muted">Start a Gateway on a machine that can reach your HSM:</p>+ <pre className="overflow-x-auto rounded bg-mineshaft-900 p-2 text-xs text-mineshaft-200">+ infisical gateway start my-gateway --pkcs11-module=/path/to/HSM-vendor.so</pre>- <p className="text-muted">The Gateway will appear here as soon as it heartbeats.</p></div></div></div>diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/types.ts b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/types.tsindex dce4765598..c5f1708503 100644--- a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/types.ts+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/types.ts@@ -33,23 +33,23 @@ export const STEPS: WizardStep[] = [subtitle: "A descriptive name and what this HSM is for.",rightLabel: "BASICS",rightDescription:- "Give the connector a descriptive name so your team can identify it later (for example, fortanix-prod for production code-signing keys). The description is optional but useful when you manage more than one HSM."+ "Give the connector a descriptive name so your team can identify it later (for example, fortanix-prod). The description is optional but useful when you manage more than one HSM."},{- name: "Reached from",- shortDescription: "Which Gateway reaches the HSM",- title: "Reached from",- subtitle: "Pick the Infisical Gateway that will reach the HSM over PKCS#11.",- rightLabel: "REACHED FROM",+ name: "Connection",+ shortDescription: "Gateway that reaches the HSM",+ title: "Connection",+ subtitle: "Choose the Gateway that connects Infisical to your HSM.",+ rightLabel: "CONNECTION",rightDescription:- "Infisical never talks to the HSM directly. A Gateway you run inside your network does, using your HSM vendor's PKCS#11 library. Only Gateways started with --pkcs11-module appear here. If the list is empty, start a Gateway pointed at your HSM's PKCS#11 library first."+ "A Gateway is a lightweight agent you run inside your own network. Infisical sends signing requests to it, and it talks to the HSM directly. Only Gateways connected to an HSM appear here. If the list is empty, follow the HSM Connectors guide to set one up."},{- name: "Access",+ name: "Credentials",shortDescription: "Slot and PIN",- title: "Access",+ title: "Credentials",subtitle: "How Infisical signs in to your HSM.",- rightLabel: "ACCESS",+ rightLabel: "CREDENTIALS",rightDescription:"The slot label is the PKCS#11 token label of the slot on the HSM where signing keys will live. The PIN authenticates Infisical to that slot. The key label prefix is prepended to every key Infisical creates so you can identify them in your HSM tooling."}diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/HsmConnectorsTab.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/HsmConnectorsTab.tsxindex 55f98c7e98..b6562523a3 100644--- a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/HsmConnectorsTab.tsx+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/HsmConnectorsTab.tsx@@ -24,6 +24,7 @@ import {CardDescription,CardHeader,CardTitle,+ DocumentationLinkBadge,DropdownMenu,DropdownMenuContent,DropdownMenuItem,@@ -57,6 +58,7 @@ import {useListHsmConnectors,useTestHsmConnector} from "@app/hooks/api/hsmConnectors";+import { PkiDocsUrls } from "@app/pages/cert-manager/pki-docs-urls";import { CreateHsmConnectorWizard } from "./CreateHsmConnectorWizard";import { DeleteHsmConnectorDialog } from "./DeleteHsmConnectorDialog";@@ -66,7 +68,7 @@ export const HsmConnectorsTab = () => {const navigate = useNavigate();const { orgId, projectId } = useParams({ strict: false });const { subscription } = useSubscription();- const isLicensed = Boolean(subscription?.pkiHsm);+ const isLicensed = Boolean(subscription?.hsm);const [addOpen, setAddOpen] = useState(false);const [testingId, setTestingId] = useState<string | null>(null);const [editing, setEditing] = useState<THsmConnector | null>(null);@@ -83,7 +85,9 @@ export const HsmConnectorsTab = () => {});};- const { data: connectors = [], isPending } = useListHsmConnectors({ enabled: isLicensed });+ const { data: connectors = [], isPending } = useListHsmConnectors(projectId, {+ enabled: isLicensed+ });const testMutation = useTestHsmConnector();const { data: gateways = [] } = useQuery({ ...gatewaysQueryKeys.list(), enabled: isLicensed });@@ -107,8 +111,8 @@ export const HsmConnectorsTab = () => {<div className="mb-3 text-2xl">🛡️</div><h4 className="mb-2 text-lg font-medium text-mineshaft-100">Enterprise Feature</h4><p className="mx-auto mb-4 max-w-md text-sm text-mineshaft-300">- HSM Connectors let you back code-signing keys with a Hardware Security Module. The- keypair stays inside your HSM and every signature is performed there.+ HSM Connectors let you back signing keys with a Hardware Security Module. The keypair+ stays inside your HSM and every signature is performed there.</p><Button onClick={() => setUpgradeOpen(true)}>Upgrade to Enterprise</Button></div>@@ -165,9 +169,12 @@ export const HsmConnectorsTab = () => {return (<Card><CardHeader>- <CardTitle>HSM Connectors</CardTitle>+ <CardTitle>+ HSM Connectors+ <DocumentationLinkBadge href={PkiDocsUrls.settings.hsmConnectors} />+ </CardTitle><CardDescription>- Hardware security modules that hold your signing keys, reached through your hosts.+ Hardware security modules that hold your signing keys.</CardDescription><CardAction><ProjectPermissionCan@@ -295,7 +302,7 @@ export const HsmConnectorsTab = () => {<EmptyDescription>{search? "No HSM Connectors match your search."- : "Add an HSM Connector to register a slot on your Hardware Security Module. Code-signing certificates can then be issued with HSM-backed keys."}+ : "Add an HSM Connector to register a slot on your Hardware Security Module."}</EmptyDescription></EmptyHeader></Empty>@@ -303,7 +310,13 @@ export const HsmConnectorsTab = () => {</>)}</CardContent>- <CreateHsmConnectorWizard isOpen={addOpen} onOpenChange={setAddOpen} />+ {projectId && (+ <CreateHsmConnectorWizard+ projectId={projectId}+ isOpen={addOpen}+ onOpenChange={setAddOpen}+ />+ )}<EditHsmConnectorSheet connector={editing} onClose={() => setEditing(null)} /><DeleteHsmConnectorDialog connector={deleting} onClose={() => setDeleting(null)} /></Card>diff --git a/frontend/src/pages/cert-manager/pki-docs-urls.ts b/frontend/src/pages/cert-manager/pki-docs-urls.tsindex 30756680ca..325c3e7c15 100644--- a/frontend/src/pages/cert-manager/pki-docs-urls.ts+++ b/frontend/src/pages/cert-manager/pki-docs-urls.ts@@ -21,11 +21,12 @@ export const PkiDocsUrls = {pqcAlgorithms: `${PKI_DOCS_BASE_URL}/reference/pqc-algorithms`},- // Settings (policies, profiles, cleanup)+ // Settings (policies, profiles, cleanup, HSM connectors)settings: {policies: `${PKI_DOCS_BASE_URL}/settings/policies`,profiles: `${PKI_DOCS_BASE_URL}/settings/profiles`,- certificateCleanup: `${PKI_DOCS_BASE_URL}/settings/certificate-cleanup`+ certificateCleanup: `${PKI_DOCS_BASE_URL}/settings/certificate-cleanup`,+ hsmConnectors: `${PKI_DOCS_BASE_URL}/settings/hsm-connectors`},// Applications