Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

Add PKI HSMs

Carlos Monastyrski910ec358dda6
diff --git a/backend/package.json b/backend/package.json
index 7ebe0ac511..786b0ad1b9 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -204,7 +204,11 @@
"@opentelemetry/resources": "^2.7.1",
"@opentelemetry/sdk-metrics": "^2.7.1",
"@opentelemetry/semantic-conventions": "^1.34.0",
+ "@peculiar/asn1-csr": "^2.6.0",
+ "@peculiar/asn1-ecc": "^2.6.0",
+ "@peculiar/asn1-rsa": "^2.6.1",
"@peculiar/asn1-schema": "^2.3.8",
+ "@peculiar/asn1-x509": "^2.6.1",
"@peculiar/x509": "^1.12.1",
"@react-email/components": "^1.0.1",
"@simplewebauthn/server": "^13.2.2",
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 80c501d3e4..30d0092956 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -109,6 +109,7 @@ import { TFolderCommitServiceFactory } from "@app/services/folder-commit/folder-
import { TGitHubAppServiceFactory } from "@app/services/github-app/github-app-service";
import { TGroupProjectServiceFactory } from "@app/services/group-project/group-project-service";
import { THsmServiceFactory } from "@app/services/hsm/hsm-service";
+import { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";
import { TIdentityServiceFactory } from "@app/services/identity/identity-service";
import { TIdentityAccessTokenServiceFactory } from "@app/services/identity-access-token/identity-access-token-service";
import { TIdentityAliCloudAuthServiceFactory } from "@app/services/identity-alicloud-auth/identity-alicloud-auth-service";
@@ -392,6 +393,7 @@ declare module "fastify" {
totp: TTotpServiceFactory;
webAuthn: TWebAuthnServiceFactory;
appConnection: TAppConnectionServiceFactory;
+ hsmConnector: THsmConnectorServiceFactory;
secretSync: TSecretSyncServiceFactory;
kmip: TKmipServiceFactory;
kmipOperation: TKmipOperationServiceFactory;
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 7ebc208a22..244552f46b 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -206,6 +206,9 @@ import {
THoneyTokenSecretMappingsUpdate,
THoneyTokensInsert,
THoneyTokensUpdate,
+ THsmConnectors,
+ THsmConnectorsInsert,
+ THsmConnectorsUpdate,
TIdentities,
TIdentitiesInsert,
TIdentitiesUpdate,
@@ -1521,6 +1524,11 @@ declare module "knex/types/tables" {
TAppConnectionsInsert,
TAppConnectionsUpdate
>;
+ [TableName.HsmConnector]: KnexOriginal.CompositeTableType<
+ THsmConnectors,
+ THsmConnectorsInsert,
+ THsmConnectorsUpdate
+ >;
[TableName.SecretSync]: KnexOriginal.CompositeTableType<TSecretSyncs, TSecretSyncsInsert, TSecretSyncsUpdate>;
[TableName.KmipClient]: KnexOriginal.CompositeTableType<TKmipClients, TKmipClientsInsert, TKmipClientsUpdate>;
[TableName.KmipOrgConfig]: KnexOriginal.CompositeTableType<
diff --git a/backend/src/db/migrations/20260618143217_pki-hsm-connector.ts b/backend/src/db/migrations/20260618143217_pki-hsm-connector.ts
new file mode 100644
index 0000000000..381f311bf2
--- /dev/null
+++ b/backend/src/db/migrations/20260618143217_pki-hsm-connector.ts
@@ -0,0 +1,205 @@
+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 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";
+const ISSUANCE_JOBS_HSM_CONNECTOR_IDX = "pki_signer_issuance_jobs_hsm_connector_idx";
+
+const indexExists = async (knex: Knex, indexName: string): Promise<boolean> => {
+ const result = await knex.raw(`SELECT 1 FROM pg_indexes WHERE indexname = ?`, [indexName]);
+ return result.rows.length > 0;
+};
+
+const constraintExists = async (knex: Knex, table: string, constraintName: string): Promise<boolean> => {
+ const result = await knex.raw(
+ `SELECT 1 FROM pg_constraint c
+ JOIN pg_class t ON t.oid = c.conrelid
+ WHERE t.relname = ? AND c.conname = ?`,
+ [table, constraintName]
+ );
+ return result.rows.length > 0;
+};
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasTable(TableName.HsmConnector))) {
+ await knex.schema.createTable(TableName.HsmConnector, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ t.string("name", 32).notNullable();
+ t.string("description", 256);
+ t.string("projectId").notNullable();
+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
+
+ // Exactly one of gatewayId / gatewayPoolId is set (enforced by the XOR check below).
+ t.uuid("gatewayId").nullable();
+ t.foreign("gatewayId").references("id").inTable(TableName.GatewayV2).onDelete("RESTRICT");
+ t.uuid("gatewayPoolId").nullable();
+ t.foreign("gatewayPoolId").references("id").inTable(TableName.GatewayPool).onDelete("RESTRICT");
+
+ t.binary("encryptedCredentials").notNullable();
+
+ t.timestamps(true, true, true);
+
+ t.unique(["projectId", "name"]);
+ t.index(["gatewayId"]);
+ t.index(["gatewayPoolId"]);
+ });
+
+ await knex.raw(
+ `
+ ALTER TABLE ?? ADD CONSTRAINT ?? CHECK (
+ ("gatewayId" IS NOT NULL AND "gatewayPoolId" IS NULL)
+ OR
+ ("gatewayId" IS NULL AND "gatewayPoolId" IS NOT NULL)
+ )
+ `,
+ [TableName.HsmConnector, HSM_CONNECTORS_GATEWAY_XOR_CHECK]
+ );
+
+ await createOnUpdateTrigger(knex, TableName.HsmConnector);
+ }
+
+ if (await knex.schema.hasTable(TableName.Certificate)) {
+ const hasKeySource = await knex.schema.hasColumn(TableName.Certificate, "keySource");
+ const hasHsmConnectorId = await knex.schema.hasColumn(TableName.Certificate, "hsmConnectorId");
+ const hasHsmKeyLabel = await knex.schema.hasColumn(TableName.Certificate, "hsmKeyLabel");
+ const hasHsmPublicKeySpki = await knex.schema.hasColumn(TableName.Certificate, "hsmPublicKeySpki");
+
+ if (!hasKeySource || !hasHsmConnectorId || !hasHsmKeyLabel || !hasHsmPublicKeySpki) {
+ await knex.schema.alterTable(TableName.Certificate, (t) => {
+ if (!hasKeySource) {
+ t.string("keySource", 32).notNullable().defaultTo("infisical");
+ }
+ if (!hasHsmConnectorId) {
+ t.uuid("hsmConnectorId").nullable();
+ t.foreign("hsmConnectorId", CERTS_HSM_CONNECTOR_FK)
+ .references("id")
+ .inTable(TableName.HsmConnector)
+ .onDelete("RESTRICT");
+ t.index(["hsmConnectorId"], CERTS_HSM_CONNECTOR_IDX, { predicate: knex.whereNotNull("hsmConnectorId") });
+ }
+ if (!hasHsmKeyLabel) {
+ t.string("hsmKeyLabel", 128).nullable();
+ }
+ if (!hasHsmPublicKeySpki) {
+ t.binary("hsmPublicKeySpki").nullable();
+ }
+ });
+ }
+
+ if (!(await constraintExists(knex, TableName.Certificate, CERTS_KEY_SOURCE_CHECK))) {
+ 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]
+ );
+ await knex.raw(`ALTER TABLE ?? VALIDATE CONSTRAINT ??`, [TableName.Certificate, CERTS_KEY_SOURCE_CHECK]);
+ }
+ }
+
+ if (await knex.schema.hasTable(TableName.GatewayV2)) {
+ if (!(await knex.schema.hasColumn(TableName.GatewayV2, "capabilities"))) {
+ await knex.schema.alterTable(TableName.GatewayV2, (t) => {
+ t.jsonb("capabilities").notNullable().defaultTo(knex.raw(`'{}'::jsonb`));
+ });
+ }
+ if (!(await indexExists(knex, GATEWAYS_CAPABILITIES_GIN_IDX))) {
+ await knex.raw(`CREATE INDEX ?? ON ?? USING gin ("capabilities")`, [
+ GATEWAYS_CAPABILITIES_GIN_IDX,
+ TableName.GatewayV2
+ ]);
+ }
+ }
+
+ if (await knex.schema.hasTable(TableName.PkiSignerCertificateIssuanceJobs)) {
+ const hasKeySource = await knex.schema.hasColumn(TableName.PkiSignerCertificateIssuanceJobs, "keySource");
+ const hasHsmConnectorId = await knex.schema.hasColumn(TableName.PkiSignerCertificateIssuanceJobs, "hsmConnectorId");
+ const hasHsmKeyLabel = await knex.schema.hasColumn(TableName.PkiSignerCertificateIssuanceJobs, "hsmKeyLabel");
+ const hasHsmPublicKeySpki = await knex.schema.hasColumn(
+ TableName.PkiSignerCertificateIssuanceJobs,
+ "hsmPublicKeySpki"
+ );
+
+ if (!hasKeySource || !hasHsmConnectorId || !hasHsmKeyLabel || !hasHsmPublicKeySpki) {
+ await knex.schema.alterTable(TableName.PkiSignerCertificateIssuanceJobs, (t) => {
+ if (!hasKeySource) {
+ t.string("keySource", 32).notNullable().defaultTo("infisical");
+ }
+ if (!hasHsmConnectorId) {
+ t.uuid("hsmConnectorId").nullable();
+ t.foreign("hsmConnectorId").references("id").inTable(TableName.HsmConnector).onDelete("SET NULL");
+ t.index(["hsmConnectorId"], ISSUANCE_JOBS_HSM_CONNECTOR_IDX, {
+ predicate: knex.whereNotNull("hsmConnectorId")
+ });
+ }
+ if (!hasHsmKeyLabel) {
+ t.string("hsmKeyLabel", 128).nullable();
+ }
+ if (!hasHsmPublicKeySpki) {
+ t.binary("hsmPublicKeySpki").nullable();
+ }
+ });
+ }
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.PkiSignerCertificateIssuanceJobs)) {
+ const hasKeySource = await knex.schema.hasColumn(TableName.PkiSignerCertificateIssuanceJobs, "keySource");
+ const hasHsmConnectorId = await knex.schema.hasColumn(TableName.PkiSignerCertificateIssuanceJobs, "hsmConnectorId");
+ const hasHsmKeyLabel = await knex.schema.hasColumn(TableName.PkiSignerCertificateIssuanceJobs, "hsmKeyLabel");
+ const hasHsmPublicKeySpki = await knex.schema.hasColumn(
+ TableName.PkiSignerCertificateIssuanceJobs,
+ "hsmPublicKeySpki"
+ );
+ if (hasKeySource || hasHsmConnectorId || hasHsmKeyLabel || hasHsmPublicKeySpki) {
+ await knex.schema.alterTable(TableName.PkiSignerCertificateIssuanceJobs, (t) => {
+ if (hasHsmPublicKeySpki) t.dropColumn("hsmPublicKeySpki");
+ if (hasHsmKeyLabel) t.dropColumn("hsmKeyLabel");
+ if (hasHsmConnectorId) t.dropColumn("hsmConnectorId");
+ if (hasKeySource) t.dropColumn("keySource");
+ });
+ }
+ }
+
+ if (await knex.schema.hasTable(TableName.GatewayV2)) {
+ if (await indexExists(knex, GATEWAYS_CAPABILITIES_GIN_IDX)) {
+ await knex.raw(`DROP INDEX ??`, [GATEWAYS_CAPABILITIES_GIN_IDX]);
+ }
+ if (await knex.schema.hasColumn(TableName.GatewayV2, "capabilities")) {
+ await knex.schema.alterTable(TableName.GatewayV2, (t) => {
+ t.dropColumn("capabilities");
+ });
+ }
+ }
+
+ 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]);
+ }
+ const hasKeySource = await knex.schema.hasColumn(TableName.Certificate, "keySource");
+ const hasHsmConnectorId = await knex.schema.hasColumn(TableName.Certificate, "hsmConnectorId");
+ const hasHsmKeyLabel = await knex.schema.hasColumn(TableName.Certificate, "hsmKeyLabel");
+ const hasHsmPublicKeySpki = await knex.schema.hasColumn(TableName.Certificate, "hsmPublicKeySpki");
+ if (hasKeySource || hasHsmConnectorId || hasHsmKeyLabel || hasHsmPublicKeySpki) {
+ await knex.schema.alterTable(TableName.Certificate, (t) => {
+ if (hasHsmPublicKeySpki) t.dropColumn("hsmPublicKeySpki");
+ if (hasHsmKeyLabel) t.dropColumn("hsmKeyLabel");
+ if (hasHsmConnectorId) {
+ t.dropColumn("hsmConnectorId");
+ }
+ if (hasKeySource) t.dropColumn("keySource");
+ });
+ }
+ }
+
+ await dropOnUpdateTrigger(knex, TableName.HsmConnector);
+ await knex.schema.dropTableIfExists(TableName.HsmConnector);
+}
diff --git a/backend/src/db/schemas/certificates.ts b/backend/src/db/schemas/certificates.ts
index 3c1cd6b2c3..f0f04a2350 100644
--- a/backend/src/db/schemas/certificates.ts
+++ b/backend/src/db/schemas/certificates.ts
@@ -5,6 +5,8 @@
import { z } from "zod";
+import { zodBuffer } from "@app/lib/zod";
+
import { TImmutableDBKeys } from "./models";
export const CertificatesSchema = z.object({
@@ -46,7 +48,11 @@ export const CertificatesSchema = z.object({
source: z.string().nullable().optional(),
discoveryMetadata: z.unknown().nullable().optional(),
externalMetadata: z.unknown().nullable().optional(),
- applicationId: z.string().uuid().nullable().optional()
+ applicationId: z.string().uuid().nullable().optional(),
+ keySource: z.string().default("infisical"),
+ hsmConnectorId: z.string().uuid().nullable().optional(),
+ hsmKeyLabel: z.string().nullable().optional(),
+ hsmPublicKeySpki: zodBuffer.nullable().optional()
});
export type TCertificates = z.infer<typeof CertificatesSchema>;
diff --git a/backend/src/db/schemas/gateways-v2.ts b/backend/src/db/schemas/gateways-v2.ts
index bc4506537c..e4941300c4 100644
--- a/backend/src/db/schemas/gateways-v2.ts
+++ b/backend/src/db/schemas/gateways-v2.ts
@@ -21,7 +21,8 @@ export const GatewaysV2Schema = z.object({
encryptedPamSessionKey: zodBuffer.nullable().optional(),
healthAlertedAt: z.date().nullable().optional(),
tokenVersion: z.number().default(0),
- heartbeatTTL: z.number().nullable().optional()
+ heartbeatTTL: z.number().nullable().optional(),
+ capabilities: z.unknown()
});
export type TGatewaysV2 = z.infer<typeof GatewaysV2Schema>;
diff --git a/backend/src/db/schemas/hsm-connectors.ts b/backend/src/db/schemas/hsm-connectors.ts
new file mode 100644
index 0000000000..6e6f8ee2c5
--- /dev/null
+++ b/backend/src/db/schemas/hsm-connectors.ts
@@ -0,0 +1,26 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { zodBuffer } from "@app/lib/zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const HsmConnectorsSchema = z.object({
+ id: z.string().uuid(),
+ name: z.string(),
+ description: z.string().nullable().optional(),
+ projectId: z.string(),
+ gatewayId: z.string().uuid().nullable().optional(),
+ gatewayPoolId: z.string().uuid().nullable().optional(),
+ encryptedCredentials: zodBuffer,
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type THsmConnectors = z.infer<typeof HsmConnectorsSchema>;
+export type THsmConnectorsInsert = Omit<z.input<typeof HsmConnectorsSchema>, TImmutableDBKeys>;
+export type THsmConnectorsUpdate = Partial<Omit<z.input<typeof HsmConnectorsSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index c3260d5011..a52a493abf 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -71,6 +71,7 @@ export * from "./honey-token-configs";
export * from "./honey-token-events";
export * from "./honey-token-secret-mappings";
export * from "./honey-tokens";
+export * from "./hsm-connectors";
export * from "./identities";
export * from "./identity-access-token-revocations";
export * from "./identity-access-tokens";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index 9ca5e4181a..fce4dbef2a 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -180,6 +180,7 @@ export enum TableName {
ProjectSlackConfigs = "project_slack_configs",
AppConnection = "app_connections",
AppConnectionCredentialRotation = "app_connection_credential_rotations",
+ HsmConnector = "hsm_connectors",
SecretSync = "secret_syncs",
PkiSync = "pki_syncs",
CertificateSync = "certificate_syncs",
diff --git a/backend/src/db/schemas/pki-signer-certificate-issuance-jobs.ts b/backend/src/db/schemas/pki-signer-certificate-issuance-jobs.ts
index eb42827f0a..68563dcac5 100644
--- a/backend/src/db/schemas/pki-signer-certificate-issuance-jobs.ts
+++ b/backend/src/db/schemas/pki-signer-certificate-issuance-jobs.ts
@@ -28,7 +28,11 @@ export const PkiSignerCertificateIssuanceJobsSchema = z.object({
failureReason: z.string().nullable().optional(),
certificateId: z.string().uuid().nullable().optional(),
createdAt: z.date(),
- updatedAt: z.date()
+ updatedAt: z.date(),
+ keySource: z.string().default("infisical"),
+ hsmConnectorId: z.string().uuid().nullable().optional(),
+ hsmKeyLabel: z.string().nullable().optional(),
+ hsmPublicKeySpki: zodBuffer.nullable().optional()
});
export type TPkiSignerCertificateIssuanceJobs = z.infer<typeof PkiSignerCertificateIssuanceJobsSchema>;
diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.ts
index 3afa024d62..9ecbda163d 100644
--- a/backend/src/ee/routes/v2/gateway-router.ts
+++ b/backend/src/ee/routes/v2/gateway-router.ts
@@ -14,7 +14,8 @@ const SanitizedGatewayV2Schema = GatewaysV2Schema.pick({
createdAt: true,
updatedAt: true,
heartbeat: true,
- heartbeatTTL: true
+ heartbeatTTL: true,
+ capabilities: true
});
export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
@@ -68,6 +69,12 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
},
schema: {
operationId: "gatewayHeartbeat",
+ body: z
+ .object({
+ capabilities: z.record(z.unknown()).optional()
+ })
+ .passthrough()
+ .optional(),
response: {
200: z.object({
message: z.string()
@@ -77,7 +84,8 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),
handler: async (req) => {
await server.services.gatewayV2.heartbeat({
- orgPermission: req.permission
+ orgPermission: req.permission,
+ capabilities: req.body?.capabilities
});
return { message: "Successfully triggered heartbeat" };
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index fd5d9b79aa..8f7e7aec63 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -54,6 +54,7 @@ import {
TUpdateSecretSyncDTO
} from "@app/services/secret-sync/secret-sync-types";
import { TDuplicateSecretAttributes } from "@app/services/secret-v2-bridge/secret-v2-bridge-types";
+import { CertKeySource } from "@app/services/signer/signer-enums";
import { TWebhookPayloads } from "@app/services/webhook/webhook-types";
import { WorkflowIntegration } from "@app/services/workflow-integration/workflow-integration-types";
@@ -571,6 +572,10 @@ export enum EventType {
CREATE_APP_CONNECTION = "create-app-connection",
UPDATE_APP_CONNECTION = "update-app-connection",
DELETE_APP_CONNECTION = "delete-app-connection",
+ CREATE_HSM_CONNECTOR = "create-hsm-connector",
+ UPDATE_HSM_CONNECTOR = "update-hsm-connector",
+ DELETE_HSM_CONNECTOR = "delete-hsm-connector",
+ TEST_HSM_CONNECTOR = "test-hsm-connector",
GET_APP_CONNECTION_USAGE = "get-app-connection-usage",
MIGRATE_APP_CONNECTION = "migrate-app-connection",
ROTATE_APP_CONNECTION_CREDENTIALS = "rotate-app-connection-credentials",
@@ -4518,6 +4523,43 @@ interface RotateAppConnectionCredentialsEvent {
};
}
+interface CreateHsmConnectorEvent {
+ type: EventType.CREATE_HSM_CONNECTOR;
+ metadata: {
+ connectorId: string;
+ name: string;
+ gatewayId: string | null;
+ gatewayPoolId: string | null;
+ };
+}
+
+interface UpdateHsmConnectorEvent {
+ type: EventType.UPDATE_HSM_CONNECTOR;
+ metadata: {
+ connectorId: string;
+ name: string;
+ fieldsUpdated: string[];
+ };
+}
+
+interface DeleteHsmConnectorEvent {
+ type: EventType.DELETE_HSM_CONNECTOR;
+ metadata: {
+ connectorId: string;
+ name: string;
+ };
+}
+
+interface TestHsmConnectorEvent {
+ type: EventType.TEST_HSM_CONNECTOR;
+ metadata: {
+ connectorId: string;
+ name: string;
+ ok: boolean;
+ memberCount: number;
+ };
+}
+
interface CreateGitHubAppEvent {
type: EventType.CREATE_GITHUB_APP;
metadata: {
@@ -4850,6 +4892,8 @@ interface CreatePkiSignerEvent {
caId?: string | null;
commonName?: string | null;
approvalPolicyId?: string | null;
+ keySource?: CertKeySource;
+ hsmConnectorId?: string | null;
};
}
@@ -7756,6 +7800,10 @@ export type Event =
| GetAppConnectionUsageEvent
| MigrateAppConnectionEvent
| RotateAppConnectionCredentialsEvent
+ | CreateHsmConnectorEvent
+ | UpdateHsmConnectorEvent
+ | DeleteHsmConnectorEvent
+ | TestHsmConnectorEvent
| CreateGitHubAppEvent
| DeleteGitHubAppEvent
| GetSshHostGroupEvent
diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-service.ts b/backend/src/ee/services/gateway-pool/gateway-pool-service.ts
index 072f643cc5..5d00a93606 100644
--- a/backend/src/ee/services/gateway-pool/gateway-pool-service.ts
+++ b/backend/src/ee/services/gateway-pool/gateway-pool-service.ts
@@ -303,6 +303,10 @@ export const gatewayPoolServiceFactory = ({
return selected;
};
+ const listHealthyGateways = async (poolId: string) => {
+ return gatewayPoolMembershipDAL.findHealthyGatewaysByPoolId(poolId);
+ };
+
const getPlatformConnectionDetailsByPoolId = async ({
poolId,
targetHost,
@@ -447,6 +451,7 @@ export const gatewayPoolServiceFactory = ({
addGatewayToPool,
removeGatewayFromPool,
pickRandomHealthyGateway,
+ listHealthyGateways,
getPlatformConnectionDetailsByPoolId,
getConnectedResources,
getConnectedResourcesCount,
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
index 02c847f520..27414b6719 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -974,12 +974,24 @@ export const gatewayV2ServiceFactory = ({
await $checkGatewayHealth(gateway.id);
};
- const heartbeat = async ({ orgPermission }: { orgPermission: OrgServiceActor }) => {
+ const heartbeat = async ({
+ orgPermission,
+ capabilities
+ }: {
+ orgPermission: OrgServiceActor;
+ capabilities?: Record<string, unknown>;
+ }) => {
+ const persistCapabilities = async (gatewayId: string) => {
+ if (capabilities === undefined) return;
+ await gatewayV2DAL.updateById(gatewayId, { 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 $checkGatewayHealth(gateway.id);
return;
}
@@ -995,6 +1007,7 @@ export const gatewayV2ServiceFactory = ({
throw new NotFoundError({ message: `Gateway for identity ${orgPermission.id} not found.` });
}
+ await persistCapabilities(gateway.id);
await $checkGatewayHealth(gateway.id);
};
diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.ts
index cad4cc3d55..6fd5c36592 100644
--- a/backend/src/ee/services/license/license-fns.ts
+++ b/backend/src/ee/services/license/license-fns.ts
@@ -102,6 +102,7 @@ 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.ts
index 3878041596..3f3a0294c7 100644
--- a/backend/src/ee/services/license/license-types.ts
+++ b/backend/src/ee/services/license/license-types.ts
@@ -82,6 +82,7 @@ export type TFeatureSet = {
pkiAcme: true;
pkiScep: false;
pkiPqc: false;
+ pkiHsm: false;
kmsPqc: false;
enforceMfa: false;
projectTemplates: false;
diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.ts
index 9a6f5c13e6..2b5ef3ce80 100644
--- a/backend/src/ee/services/permission/default-roles.ts
+++ b/backend/src/ee/services/permission/default-roles.ts
@@ -17,6 +17,7 @@ import {
ProjectPermissionDynamicSecretActions,
ProjectPermissionGroupActions,
ProjectPermissionHoneyTokenActions,
+ ProjectPermissionHsmConnectorActions,
ProjectPermissionIdentityActions,
ProjectPermissionInsightsActions,
ProjectPermissionKmipActions,
@@ -406,6 +407,18 @@ const buildAdminPermissionRules = () => {
ProjectPermissionSub.AppConnections
);
+ can(
+ [
+ ProjectPermissionHsmConnectorActions.Read,
+ ProjectPermissionHsmConnectorActions.Create,
+ ProjectPermissionHsmConnectorActions.Edit,
+ ProjectPermissionHsmConnectorActions.Delete,
+ ProjectPermissionHsmConnectorActions.Test,
+ ProjectPermissionHsmConnectorActions.Attach
+ ],
+ ProjectPermissionSub.HsmConnectors
+ );
+
can(
[
ProjectPermissionHoneyTokenActions.Read,
@@ -691,6 +704,11 @@ const buildMemberPermissionRules = () => {
can(ProjectPermissionAppConnectionActions.Connect, ProjectPermissionSub.AppConnections);
+ can(
+ [ProjectPermissionHsmConnectorActions.Read, ProjectPermissionHsmConnectorActions.Test],
+ ProjectPermissionSub.HsmConnectors
+ );
+
can([ProjectPermissionActions.Read], ProjectPermissionSub.PamFolders);
can([ProjectPermissionActions.Read], ProjectPermissionSub.PamResources);
diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.ts
index 0b7f5a97d8..36a8a42293 100644
--- a/backend/src/ee/services/permission/project-permission.ts
+++ b/backend/src/ee/services/permission/project-permission.ts
@@ -234,6 +234,15 @@ export enum ProjectPermissionAppConnectionActions {
RotateCredentials = "rotate-credentials"
}
+export enum ProjectPermissionHsmConnectorActions {
+ Read = "read-hsm-connectors",
+ Create = "create-hsm-connectors",
+ Edit = "edit-hsm-connectors",
+ Delete = "delete-hsm-connectors",
+ Test = "test-hsm-connectors",
+ Attach = "attach-hsm-connectors"
+}
+
export enum ProjectPermissionSecretScanningFindingActions {
Read = "read-findings",
Update = "update-findings"
@@ -375,6 +384,7 @@ export enum ProjectPermissionSub {
SecretScanningConfigs = "secret-scanning-configs",
SecretEventSubscriptions = "secret-event-subscriptions",
AppConnections = "app-connections",
+ HsmConnectors = "hsm-connectors",
PamFolders = "pam-folders",
PamResources = "pam-resources",
PamDomains = "pam-domains",
@@ -716,6 +726,7 @@ export type ProjectPermissionSet =
| (ForcedSubject<ProjectPermissionSub.AppConnections> & AppConnectionSubjectFields)
)
]
+ | [ProjectPermissionHsmConnectorActions, ProjectPermissionSub.HsmConnectors]
| [ProjectPermissionActions, ProjectPermissionSub.PamFolders]
| [
ProjectPermissionActions,
@@ -1834,6 +1845,12 @@ const GeneralPermissionSchema = [
"When specified, only matching conditions will be allowed to access given resource."
).optional()
}),
+ z.object({
+ subject: z.literal(ProjectPermissionSub.HsmConnectors).describe("The entity this permission pertains to."),
+ action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionHsmConnectorActions).describe(
+ "Describe what action an entity can take."
+ )
+ }),
z.object({
subject: z.literal(ProjectPermissionSub.PamFolders).describe("The entity this permission pertains to."),
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionActions).describe(
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 338deee33f..12d396ec98 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -71,6 +71,7 @@ export enum ApiDocsTags {
CertManagerInstance = "Certificate Manager Instance",
PkiCertificateCollections = "PKI Certificate Collections",
PkiAlerting = "PKI Alerting",
+ HsmConnectors = "HSM Connectors",
PkiDiscovery = "PKI Discovery",
PkiInstallations = "PKI Installations",
PkiSigners = "PKI Signers",
diff --git a/backend/src/lib/csr/build-csr-with-external-signer.ts b/backend/src/lib/csr/build-csr-with-external-signer.ts
new file mode 100644
index 0000000000..39ac97ed64
--- /dev/null
+++ b/backend/src/lib/csr/build-csr-with-external-signer.ts
@@ -0,0 +1,200 @@
+import { Attributes, CertificationRequest, CertificationRequestInfo } from "@peculiar/asn1-csr";
+import { ECDSASigValue, id_ecdsaWithSHA256, id_ecdsaWithSHA384 } from "@peculiar/asn1-ecc";
+import { id_sha256WithRSAEncryption, id_sha384WithRSAEncryption } from "@peculiar/asn1-rsa";
+import { AsnConvert, OctetString } from "@peculiar/asn1-schema";
+import {
+ AlgorithmIdentifier,
+ Attribute,
+ BasicConstraints,
+ ExtendedKeyUsage,
+ Extension,
+ Extensions,
+ GeneralName,
+ id_ce_basicConstraints,
+ id_ce_extKeyUsage,
+ id_ce_keyUsage,
+ id_ce_subjectAltName,
+ id_kp_codeSigning,
+ KeyUsage,
+ KeyUsageFlags,
+ Name,
+ SubjectAlternativeName,
+ SubjectPublicKeyInfo
+} from "@peculiar/asn1-x509";
+import * as x509 from "@peculiar/x509";
+
+import { BadRequestError } from "@app/lib/errors";
+import { HsmKeyAlgorithm } from "@app/services/signer/signer-enums";
+
+export type BuildCsrInput = {
+ publicKeySpkiDer: Buffer;
+ keyAlgorithm: HsmKeyAlgorithm;
+ subjectCommonName: string;
+ subjectAltNames?: string[];
+ signCallback: (tbsBytes: Buffer, mechanism: string, isDigest: boolean) => Promise<Buffer>;
+};
+
+export type BuiltCsr = {
+ csrPem: string;
+ csrDer: Buffer;
+ signatureAlgorithmName: string;
+};
+
+const pickAlgorithmShape = (
+ keyAlgorithm: HsmKeyAlgorithm
+): {
+ mechanism: string;
+ pk11SignsDigest: boolean;
+ isEcdsa: boolean;
+ oid: string;
+ parameters?: ArrayBuffer;
+} => {
+ const nullParams = new Uint8Array([0x05, 0x00]).buffer as ArrayBuffer;
+ switch (keyAlgorithm) {
+ case HsmKeyAlgorithm.RSA_2048:
+ return {
+ mechanism: "CKM_SHA256_RSA_PKCS",
+ pk11SignsDigest: false,
+ isEcdsa: false,
+ oid: id_sha256WithRSAEncryption,
+ parameters: nullParams
+ };
+ case HsmKeyAlgorithm.RSA_4096:
+ return {
+ mechanism: "CKM_SHA384_RSA_PKCS",
+ pk11SignsDigest: false,
+ isEcdsa: false,
+ oid: id_sha384WithRSAEncryption,
+ parameters: nullParams
+ };
+ case HsmKeyAlgorithm.ECC_P256:
+ return {
+ mechanism: "CKM_ECDSA_SHA256",
+ pk11SignsDigest: false,
+ isEcdsa: true,
+ oid: id_ecdsaWithSHA256
+ };
+ case HsmKeyAlgorithm.ECC_P384:
+ return {
+ mechanism: "CKM_ECDSA_SHA384",
+ pk11SignsDigest: false,
+ isEcdsa: true,
+ oid: id_ecdsaWithSHA384
+ };
+ default: {
+ throw new BadRequestError({ message: `Unsupported keyAlgorithm for CSR: ${keyAlgorithm as string}` });
+ }
+ }
+};
+
+const bufferToArrayBuffer = (buf: Buffer): ArrayBuffer => {
+ const ab = new ArrayBuffer(buf.length);
+ new Uint8Array(ab).set(buf);
+ return ab;
+};
+
+const buildCodeSigningExtensions = (subjectAltNames?: string[]): Extensions => {
+ const extensions: Extension[] = [];
+
+ // RFC 5280 requires basicConstraints critical on code-signing leaves.
+ const basic = AsnConvert.serialize(new BasicConstraints({ cA: false }));
+ extensions.push(
+ new Extension({
+ extnID: id_ce_basicConstraints,
+ critical: true,
+ extnValue: new OctetString(basic)
+ })
+ );
+
+ const ku = AsnConvert.serialize(new KeyUsage(KeyUsageFlags.digitalSignature));
+ extensions.push(
+ new Extension({
+ extnID: id_ce_keyUsage,
+ critical: true,
+ extnValue: new OctetString(ku)
+ })
+ );
+
+ const eku = AsnConvert.serialize(new ExtendedKeyUsage([id_kp_codeSigning]));
+ extensions.push(
+ new Extension({
+ extnID: id_ce_extKeyUsage,
+ critical: true,
+ extnValue: new OctetString(eku)
+ })
+ );
+
+ if (subjectAltNames && subjectAltNames.length > 0) {
+ const san = new SubjectAlternativeName(subjectAltNames.map((dns) => new GeneralName({ dNSName: dns })));
+ const sanDer = AsnConvert.serialize(san);
+ extensions.push(
+ new Extension({
+ extnID: id_ce_subjectAltName,
+ critical: false,
+ extnValue: new OctetString(sanDer)
+ })
+ );
+ }
+
+ return new Extensions(extensions);
+};
+
+// PKCS#11 emits raw `r || s`; X.509 expects DER ECDSASigValue.
+const rawRsToDer = (raw: Buffer): Buffer => {
+ if (raw.length % 2 !== 0) {
+ throw new BadRequestError({ message: `Unexpected ECDSA signature length: ${raw.length}` });
+ }
+ const half = raw.length / 2;
+ const r = raw.subarray(0, half);
+ const s = raw.subarray(half);
+ const sig = new ECDSASigValue({
+ r: bufferToArrayBuffer(r),
+ s: bufferToArrayBuffer(s)
+ });
+ return Buffer.from(AsnConvert.serialize(sig));
+};
+
+export const buildCsrWithExternalSigner = async (input: BuildCsrInput): Promise<BuiltCsr> => {
+ const shape = pickAlgorithmShape(input.keyAlgorithm);
+
+ const spki = AsnConvert.parse(bufferToArrayBuffer(input.publicKeySpkiDer), SubjectPublicKeyInfo);
+
+ const nameDer = new x509.Name(`CN=${input.subjectCommonName}`).toArrayBuffer();
+ const subject = AsnConvert.parse(nameDer, Name);
+
+ // extensionRequest (RFC 2985 OID 1.2.840.113549.1.9.14) carries EKU + SAN + KU + BC.
+ const exts = buildCodeSigningExtensions(input.subjectAltNames);
+ const extReqAttr = new Attribute({
+ type: "1.2.840.113549.1.9.14",
+ values: [AsnConvert.serialize(exts)]
+ });
+
+ const tbs = new CertificationRequestInfo({
+ version: 0,
+ subject,
+ subjectPKInfo: spki,
+ attributes: new Attributes([extReqAttr])
+ });
+ const tbsDer = Buffer.from(AsnConvert.serialize(tbs));
+
+ // isDigest=false: HSM hashes via *_SHA<NN>_* so the wire payload stays raw TBS.
+ let signatureBytes = await input.signCallback(tbsDer, shape.mechanism, shape.pk11SignsDigest);
+ if (shape.isEcdsa) {
+ signatureBytes = rawRsToDer(signatureBytes);
+ }
+
+ const sigAlg = new AlgorithmIdentifier({
+ algorithm: shape.oid,
+ parameters: shape.parameters
+ });
+
+ const csr = new CertificationRequest({
+ certificationRequestInfo: tbs,
+ signatureAlgorithm: sigAlg,
+ signature: bufferToArrayBuffer(signatureBytes)
+ });
+ const csrDer = Buffer.from(AsnConvert.serialize(csr));
+ const csrPem = x509.PemConverter.encode(csrDer, "CERTIFICATE REQUEST");
+
+ return { csrPem, csrDer, signatureAlgorithmName: shape.mechanism };
+};
diff --git a/backend/src/lib/csr/pkcs11-algorithm-map.ts b/backend/src/lib/csr/pkcs11-algorithm-map.ts
new file mode 100644
index 0000000000..cfd64147e0
--- /dev/null
+++ b/backend/src/lib/csr/pkcs11-algorithm-map.ts
@@ -0,0 +1,68 @@
+import { SigningAlgorithm } from "@app/lib/crypto/sign/types";
+import { BadRequestError } from "@app/lib/errors";
+
+export type Pkcs11SigningMechanism = {
+ mechanism: string;
+ // ECDSA mechanisms return raw r||s; caller must convert to DER before X.509 use.
+ isEcdsa: boolean;
+};
+
+export const mapSigningAlgorithmToPkcs11Mechanism = (
+ algorithm: SigningAlgorithm,
+ isDigest: boolean
+): Pkcs11SigningMechanism => {
+ if (isDigest) {
+ if (algorithm.startsWith("RSASSA_PKCS1")) {
+ throw new BadRequestError({
+ message:
+ `Pre-hashed RSA signing (isDigest=true) is not supported with HSM-backed keys. ` +
+ `Send the raw message with isDigest=false so the HSM can apply DigestInfo + PKCS#1 v1.5 padding.`
+ });
+ }
+ if (algorithm.startsWith("ECDSA_SHA_")) return { mechanism: "CKM_ECDSA", isEcdsa: true };
+ } else {
+ switch (algorithm) {
+ case SigningAlgorithm.RSASSA_PKCS1_V1_5_SHA_256:
+ return { mechanism: "CKM_SHA256_RSA_PKCS", isEcdsa: false };
+ case SigningAlgorithm.RSASSA_PKCS1_V1_5_SHA_384:
+ return { mechanism: "CKM_SHA384_RSA_PKCS", isEcdsa: false };
+ case SigningAlgorithm.RSASSA_PKCS1_V1_5_SHA_512:
+ return { mechanism: "CKM_SHA512_RSA_PKCS", isEcdsa: false };
+ case SigningAlgorithm.ECDSA_SHA_256:
+ return { mechanism: "CKM_ECDSA_SHA256", isEcdsa: true };
+ case SigningAlgorithm.ECDSA_SHA_384:
+ return { mechanism: "CKM_ECDSA_SHA384", isEcdsa: true };
+ default:
+ break;
+ }
+ }
+ throw new BadRequestError({
+ message: `Signing algorithm ${algorithm} is not supported on HSM-backed certificates`
+ });
+};
+
+const trimLeadingZeros = (b: Buffer): Buffer => {
+ let i = 0;
+ while (i < b.length - 1 && b[i] === 0x00) i += 1;
+ return b.subarray(i);
+};
+
+// ASN.1 INTEGER requires a leading 0x00 byte when the high bit is set; otherwise the value
+// reads as negative. The bitwise check inspects the sign bit on a Buffer byte.
+// eslint-disable-next-line no-bitwise
+const needsAsnSignPad = (b: Buffer): boolean => b.length > 0 && (b[0] & 0x80) !== 0;
+
+export const ecdsaRawRsToDer = (raw: Buffer): Buffer => {
+ if (raw.length % 2 !== 0) {
+ throw new BadRequestError({ message: `Unexpected ECDSA signature length: ${raw.length}` });
+ }
+ const half = raw.length / 2;
+ const r = trimLeadingZeros(raw.subarray(0, half));
+ const s = trimLeadingZeros(raw.subarray(half));
+ const rPadded = needsAsnSignPad(r) ? Buffer.concat([Buffer.from([0x00]), r]) : r;
+ const sPadded = needsAsnSignPad(s) ? Buffer.concat([Buffer.from([0x00]), s]) : s;
+ const rTlv = Buffer.concat([Buffer.from([0x02, rPadded.length]), rPadded]);
+ const sTlv = Buffer.concat([Buffer.from([0x02, sPadded.length]), sPadded]);
+ const seqBody = Buffer.concat([rTlv, sTlv]);
+ return Buffer.concat([Buffer.from([0x30, seqBody.length]), seqBody]);
+};
diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.ts
index 1c686f796e..7c37d5014b 100644
--- a/backend/src/lib/gateway-v2/gateway-v2.ts
+++ b/backend/src/lib/gateway-v2/gateway-v2.ts
@@ -95,7 +95,8 @@ export const createGatewayConnection = async (
[GatewayProxyProtocol.Health]: ["infisical-health", "infisical-ping"],
[GatewayProxyProtocol.Pam]: ["infisical-pam-proxy"],
[GatewayProxyProtocol.PamRdpBrowser]: ["infisical-pam-rdp-browser"],
- [GatewayProxyProtocol.PamSessionCancellation]: ["infisical-pam-session-cancellation"]
+ [GatewayProxyProtocol.PamSessionCancellation]: ["infisical-pam-session-cancellation"],
+ [GatewayProxyProtocol.Pkcs11]: ["infisical-pkcs11"]
};
const tlsOptions: tls.ConnectionOptions = {
diff --git a/backend/src/lib/gateway-v2/pkcs11-rpc.ts b/backend/src/lib/gateway-v2/pkcs11-rpc.ts
new file mode 100644
index 0000000000..998d794eb8
--- /dev/null
+++ b/backend/src/lib/gateway-v2/pkcs11-rpc.ts
@@ -0,0 +1,122 @@
+import http from "node:http";
+
+import { logger } from "@app/lib/logger";
+
+export type Pkcs11RpcEndpoint = "/v1/test" | "/v1/generate-key-pair" | "/v1/sign" | "/v1/get-public-key";
+
+export type Pkcs11RpcRequestBody = {
+ slotLabel: string;
+ pin: string;
+ params: Record<string, unknown>;
+};
+
+export type Pkcs11RpcSuccess<T> = { ok: true; status: number; result: T };
+export type Pkcs11RpcFailure = {
+ ok: false;
+ status: number;
+ errorCode: string;
+ errorMessage: string;
+};
+export type Pkcs11RpcResponse<T> = Pkcs11RpcSuccess<T> | Pkcs11RpcFailure;
+
+export const PKCS11_RPC_TIMEOUT_MS = 30_000;
+
+export const callPkcs11Endpoint = async <T>(args: {
+ port: number;
+ endpoint: Pkcs11RpcEndpoint;
+ body: Pkcs11RpcRequestBody;
+ timeoutMs?: number;
+}): Promise<Pkcs11RpcResponse<T>> => {
+ const payload = JSON.stringify(args.body);
+ return new Promise<Pkcs11RpcResponse<T>>((resolve, reject) => {
+ const req = http.request(
+ {
+ host: "127.0.0.1",
+ port: args.port,
+ path: args.endpoint,
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "Content-Length": Buffer.byteLength(payload).toString(),
+ Connection: "close"
+ },
+ timeout: args.timeoutMs ?? PKCS11_RPC_TIMEOUT_MS
+ },
+ (res) => {
+ const chunks: Buffer[] = [];
+ res.on("data", (chunk: Buffer) => chunks.push(chunk));
+ res.on("end", () => {
+ const text = Buffer.concat(chunks).toString("utf8");
+ const status = res.statusCode ?? 0;
+ if (!text) {
+ resolve({
+ ok: false,
+ status,
+ errorCode: "internal",
+ errorMessage: `Empty response body from Gateway (status ${status})`
+ });
+ return;
+ }
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ resolve({
+ ok: false,
+ status,
+ errorCode: "internal",
+ errorMessage: `Malformed response body from Gateway: ${text.slice(0, 256)}`
+ });
+ return;
+ }
+ if (status >= 200 && status < 300) {
+ const { result } = parsed as { result?: T };
+ if (result === undefined) {
+ resolve({
+ ok: false,
+ status,
+ errorCode: "internal",
+ errorMessage: "Gateway response missing `result` field"
+ });
+ return;
+ }
+ resolve({ ok: true, status, result });
+ return;
+ }
+ const errEnv = (parsed as { error?: { code?: string; message?: string } }).error;
+ resolve({
+ ok: false,
+ status,
+ errorCode: errEnv?.code ?? "internal",
+ errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}`
+ });
+ });
+ res.on("error", (err) => {
+ logger.warn({ err }, `PKCS#11 RPC response stream error [port=${args.port}]`);
+ reject(err);
+ });
+ }
+ );
+ req.on("timeout", () => {
+ req.destroy(new Error(`PKCS#11 RPC timed out after ${args.timeoutMs ?? PKCS11_RPC_TIMEOUT_MS}ms`));
+ });
+ req.on("error", (err) => {
+ logger.warn({ err }, `PKCS#11 RPC request error [port=${args.port}]`);
+ reject(err);
+ });
+ req.write(payload);
+ req.end();
+ });
+};
+
+export const isRetryablePkcs11RpcError = (failure: Pkcs11RpcFailure): boolean => {
+ if (failure.status === 502 || failure.status === 503 || failure.status === 504) return true;
+ switch (failure.errorCode) {
+ case "driver_unavailable":
+ case "gateway_timeout":
+ case "pkcs11_not_supported":
+ return true;
+ default:
+ return false;
+ }
+};
diff --git a/backend/src/lib/gateway/types.ts b/backend/src/lib/gateway/types.ts
index f4049f8a80..cf22b9fdba 100644
--- a/backend/src/lib/gateway/types.ts
+++ b/backend/src/lib/gateway/types.ts
@@ -11,7 +11,8 @@ export enum GatewayProxyProtocol {
Health = "health",
Pam = "pam",
PamRdpBrowser = "pam-rdp-browser",
- PamSessionCancellation = "pam-session-cancellation"
+ PamSessionCancellation = "pam-session-cancellation",
+ Pkcs11 = "pkcs11"
}
export enum GatewayHttpProxyActions {
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index f932ba0f20..72448ebdd2 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -330,6 +330,8 @@ import { gitHubAppServiceFactory } from "@app/services/github-app/github-app-ser
import { groupProjectDALFactory } from "@app/services/group-project/group-project-dal";
import { groupProjectServiceFactory } from "@app/services/group-project/group-project-service";
import { healthAlertServiceFactory } from "@app/services/health-alert/health-alert-queue";
+import { hsmConnectorDALFactory } from "@app/services/hsm-connector/hsm-connector-dal";
+import { hsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";
import { identityDALFactory } from "@app/services/identity/identity-dal";
import { identityMetadataDALFactory } from "@app/services/identity/identity-metadata-dal";
import { identityOrgDALFactory } from "@app/services/identity/identity-org-dal";
@@ -656,6 +658,7 @@ export const registerRoutes = async (
const trustedIpDAL = trustedIpDALFactory(db);
const telemetryDAL = telemetryDALFactory(db);
const appConnectionDAL = appConnectionDALFactory(db);
+ const hsmConnectorDAL = hsmConnectorDALFactory(db);
const secretSyncDAL = secretSyncDALFactory(db, folderDAL);
const userNotificationDAL = userNotificationDALFactory(db);
@@ -2625,6 +2628,15 @@ export const registerRoutes = async (
keyStore
});
+ const hsmConnectorService = hsmConnectorServiceFactory({
+ hsmConnectorDAL,
+ permissionService,
+ kmsService,
+ gatewayV2Service,
+ gatewayPoolService,
+ licenseService
+ });
+
const honeyTokenConfigService = honeyTokenConfigServiceFactory({
honeyTokenConfigDAL,
permissionService,
@@ -3248,7 +3260,9 @@ export const registerRoutes = async (
projectDAL,
kmsService,
certificateIssuanceQueue,
- cronJob
+ cronJob,
+ hsmConnectorService,
+ certificateDAL
});
const signerService = signerServiceFactory({
@@ -3269,7 +3283,8 @@ export const registerRoutes = async (
approvalRequestDAL,
approvalRequestGrantsDAL,
membershipDAL,
- membershipRoleDAL
+ membershipRoleDAL,
+ hsmConnectorService
});
const signerAutoRenewalQueue = signerAutoRenewalQueueFactory({
@@ -3804,6 +3819,7 @@ export const registerRoutes = async (
totp: totpService,
webAuthn: webAuthnService,
appConnection: appConnectionService,
+ hsmConnector: hsmConnectorService,
secretSync: secretSyncService,
kmip: kmipService,
kmipOperation: kmipOperationService,
diff --git a/backend/src/server/routes/v1/cert-manager-hsm-connector-router-schemas.ts b/backend/src/server/routes/v1/cert-manager-hsm-connector-router-schemas.ts
new file mode 100644
index 0000000000..0cde73e9a3
--- /dev/null
+++ b/backend/src/server/routes/v1/cert-manager-hsm-connector-router-schemas.ts
@@ -0,0 +1,106 @@
+import { z } from "zod";
+
+import { slugSchema } from "@app/server/lib/schemas";
+import { HsmConnectorCredentialsSchema } from "@app/services/hsm-connector/hsm-connector-fns";
+
+const HSM_CONNECTOR_NAME_MAX = 32;
+const HSM_CONNECTOR_DESCRIPTION_MAX = 256;
+
+const isProvided = (v: unknown) => v !== undefined && v !== null && v !== "";
+
+export const GATEWAY_PICK_MESSAGE = "Exactly one of gatewayId or gatewayPoolId must be set";
+export const gatewayPickRefiner = (data: { gatewayId?: string | null; gatewayPoolId?: string | null }) => {
+ const hasGatewayId = isProvided(data.gatewayId);
+ const hasPool = isProvided(data.gatewayPoolId);
+ return 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 HsmConnectorTestResultSchema = z.object({
+ ok: z.boolean(),
+ members: z
+ .array(
+ z.discriminatedUnion("ok", [
+ z.object({
+ gatewayId: z.string().uuid(),
+ ok: z.literal(true),
+ slotInfo: z.object({
+ manufacturer: z.string(),
+ model: z.string(),
+ firmware: z.string()
+ })
+ }),
+ z.object({
+ gatewayId: z.string().uuid(),
+ ok: z.literal(false),
+ errorCode: z.string(),
+ errorMessage: z.string()
+ })
+ ])
+ )
+ .min(1)
+});
+
+export const CreateBodySchema = z
+ .object({
+ 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(),
+ gatewayPoolId: z.string().uuid().optional(),
+ credentials: HsmConnectorCredentialsSchema
+ })
+ .refine(gatewayPickRefiner, { message: GATEWAY_PICK_MESSAGE, path: ["gatewayId"] });
+
+export const UpdateBodySchema = z
+ .object({
+ name: slugSchema({ min: 1, max: HSM_CONNECTOR_NAME_MAX, field: "name" }).optional(),
+ description: z.string().max(HSM_CONNECTOR_DESCRIPTION_MAX).optional(),
+ gatewayId: z.string().uuid().nullable().optional(),
+ gatewayPoolId: z.string().uuid().nullable().optional(),
+ credentials: HsmConnectorCredentialsSchema.partial().optional()
+ })
+ .refine(
+ (data) => {
+ if (data.gatewayId === undefined && data.gatewayPoolId === undefined) return true;
+ return gatewayPickRefiner({
+ gatewayId: data.gatewayId ?? null,
+ gatewayPoolId: data.gatewayPoolId ?? null
+ });
+ },
+ { message: GATEWAY_PICK_MESSAGE, path: ["gatewayId"] }
+ );
+
+export const ConnectorIdParamSchema = z.object({
+ connectorId: z.string().uuid()
+});
+
+export const LinkedCertificatesQuerySchema = 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(
+ z.object({
+ id: z.string().uuid(),
+ commonName: z.string(),
+ status: z.string(),
+ notAfter: z.date(),
+ hsmKeyLabel: z.string().nullable(),
+ createdAt: z.date()
+ })
+ ),
+ totalCount: z.number()
+});
diff --git a/backend/src/server/routes/v1/cert-manager-hsm-connector-router.ts b/backend/src/server/routes/v1/cert-manager-hsm-connector-router.ts
new file mode 100644
index 0000000000..70a0f75012
--- /dev/null
+++ b/backend/src/server/routes/v1/cert-manager-hsm-connector-router.ts
@@ -0,0 +1,239 @@
+import { z } from "zod";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+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 {
+ ConnectorIdParamSchema,
+ CreateBodySchema,
+ HsmConnectorSanitizedSchema,
+ HsmConnectorTestResultSchema,
+ LinkedCertificatesQuerySchema,
+ LinkedCertificatesResponseSchema,
+ UpdateBodySchema
+} from "./cert-manager-hsm-connector-router-schemas";
+
+export const registerCertManagerHsmConnectorRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "POST",
+ url: "/",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "createHsmConnector",
+ tags: [ApiDocsTags.HsmConnectors],
+ body: CreateBodySchema,
+ 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,
+ name: req.body.name,
+ description: req.body.description,
+ gatewayId: req.body.gatewayId,
+ gatewayPoolId: req.body.gatewayPoolId,
+ credentials: req.body.credentials
+ },
+ req.permission
+ );
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: hsmConnector.projectId,
+ event: {
+ type: EventType.CREATE_HSM_CONNECTOR,
+ metadata: {
+ connectorId: hsmConnector.id,
+ name: hsmConnector.name,
+ gatewayId: hsmConnector.gatewayId,
+ gatewayPoolId: hsmConnector.gatewayPoolId
+ }
+ }
+ });
+ return { hsmConnector };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listHsmConnectors",
+ tags: [ApiDocsTags.HsmConnectors],
+ 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 },
+ req.permission
+ );
+ return { hsmConnectors };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:connectorId",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "getHsmConnector",
+ tags: [ApiDocsTags.HsmConnectors],
+ params: ConnectorIdParamSchema,
+ response: { 200: z.object({ hsmConnector: HsmConnectorSanitizedSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const hsmConnector = await server.services.hsmConnector.getHsmConnectorById(
+ { connectorId: req.params.connectorId },
+ req.permission
+ );
+ return { hsmConnector };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:connectorId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "updateHsmConnector",
+ tags: [ApiDocsTags.HsmConnectors],
+ params: ConnectorIdParamSchema,
+ body: UpdateBodySchema,
+ response: { 200: z.object({ hsmConnector: HsmConnectorSanitizedSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const hsmConnector = await server.services.hsmConnector.updateHsmConnector(
+ {
+ connectorId: req.params.connectorId,
+ name: req.body.name,
+ description: req.body.description,
+ gatewayId: req.body.gatewayId ?? undefined,
+ gatewayPoolId: req.body.gatewayPoolId ?? undefined,
+ credentials: req.body.credentials
+ },
+ req.permission
+ );
+ const fieldsUpdated = Object.keys(req.body).filter((k) => req.body[k as keyof typeof req.body] !== undefined);
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: hsmConnector.projectId,
+ event: {
+ type: EventType.UPDATE_HSM_CONNECTOR,
+ metadata: {
+ connectorId: hsmConnector.id,
+ name: hsmConnector.name,
+ fieldsUpdated
+ }
+ }
+ });
+ return { hsmConnector };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:connectorId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "deleteHsmConnector",
+ tags: [ApiDocsTags.HsmConnectors],
+ params: ConnectorIdParamSchema,
+ 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(
+ { connectorId: req.params.connectorId },
+ req.permission
+ );
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: connector.projectId,
+ event: {
+ type: EventType.DELETE_HSM_CONNECTOR,
+ metadata: { connectorId: result.id, name: connector.name }
+ }
+ });
+ return result;
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:connectorId/test",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "testHsmConnector",
+ tags: [ApiDocsTags.HsmConnectors],
+ params: ConnectorIdParamSchema,
+ 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(
+ { connectorId: req.params.connectorId },
+ req.permission
+ );
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: connector.projectId,
+ event: {
+ type: EventType.TEST_HSM_CONNECTOR,
+ metadata: {
+ connectorId: req.params.connectorId,
+ name: connector.name,
+ ok: result.ok,
+ memberCount: result.members.length
+ }
+ }
+ });
+ return result;
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:connectorId/linked-certificates",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listHsmConnectorLinkedCertificates",
+ tags: [ApiDocsTags.HsmConnectors],
+ params: ConnectorIdParamSchema,
+ querystring: LinkedCertificatesQuerySchema,
+ response: { 200: LinkedCertificatesResponseSchema }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.hsmConnector.listLinkedCertificates(
+ {
+ connectorId: req.params.connectorId,
+ offset: req.query.offset,
+ limit: req.query.limit
+ },
+ req.permission
+ );
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.ts
index 9b6a656a76..dbb685f271 100644
--- a/backend/src/server/routes/v1/index.ts
+++ b/backend/src/server/routes/v1/index.ts
@@ -17,6 +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 { registerCertManagerInstanceRouter } from "./cert-manager-instance-router";
import { registerCaRouter } from "./certificate-authority-router";
import { CERTIFICATE_AUTHORITY_REGISTER_ROUTER_MAP } from "./certificate-authority-routers";
@@ -240,6 +241,7 @@ 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/lifecycle-router.ts b/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts
index c46026490c..d50a76ff6c 100644
--- a/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts
+++ b/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts
@@ -8,6 +8,7 @@ import { openApiHidden, slugSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
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 { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { ApprovalPolicyBodySchema, SignerIdParamsSchema, SignerKeyAlgorithm } from "./schemas";
@@ -32,6 +33,18 @@ export const registerSignerLifecycleRouter = async (server: FastifyZodProvider)
certificateRenewBeforeDays: z.number().int().min(1).max(30).nullable().optional(),
keyAlgorithm: SignerKeyAlgorithm.schema.optional(),
certificateId: z.string().uuid().optional(),
+ certificate: z
+ .object({
+ keySource: z.nativeEnum(CertKeySource).optional().default(CertKeySource.Infisical),
+ 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(),
approvalPolicyId: z.string().uuid().optional(),
members: z
.array(
@@ -68,7 +81,9 @@ export const registerSignerLifecycleRouter = async (server: FastifyZodProvider)
signerId: signer.id,
name: signer.name,
certificateId: signer.certificateId,
- approvalPolicyId: signer.approvalPolicyId
+ approvalPolicyId: signer.approvalPolicyId,
+ keySource: req.body.certificate?.keySource,
+ hsmConnectorId: req.body.certificate?.hsmConnectorId
}
}
});
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.ts
index a344b54e60..b79e856ae3 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
@@ -537,7 +537,7 @@ export const AwsPcaCertificateAuthorityFns = ({
isCancelled
}: {
caId: string;
- profileId: string;
+ profileId?: string;
commonName: string;
altNames?: Array<{ type: CertSubjectAlternativeNameType; value: string }>;
keyUsages?: CertKeyUsage[];
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.ts
index 43d7ccf4af..dd83b5fe6a 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
@@ -1112,7 +1112,7 @@ export const AzureAdCsCertificateAuthorityFns = ({
isCancelled
}: {
caId: string;
- profileId: string;
+ profileId?: string;
commonName: string;
altNames?: string[];
keyUsages?: CertKeyUsage[];
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
index 7d4aebf715..8dcdf75126 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
@@ -73,7 +73,8 @@ describe("CertificateV3Service", () => {
friendlyName: "Test Certificate",
commonName: "test.example.com",
status: "ACTIVE",
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
}),
transaction: vi.fn().mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
const mockTx = {};
@@ -426,7 +427,8 @@ describe("CertificateV3Service", () => {
certificatePolicyId: "policy-123",
revokedAt: null,
revokedBy: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
};
vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
@@ -555,7 +557,8 @@ describe("CertificateV3Service", () => {
revocationReason: null,
pkiSubscriberId: null,
profileId: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
};
const camelCaseRequest = {
@@ -649,7 +652,8 @@ describe("CertificateV3Service", () => {
revocationReason: null,
pkiSubscriberId: null,
profileId: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
});
vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockCertRecord);
@@ -849,7 +853,8 @@ describe("CertificateV3Service", () => {
revocationReason: null,
pkiSubscriberId: null,
profileId: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
};
const mockPolicy = {
@@ -1124,7 +1129,8 @@ describe("CertificateV3Service", () => {
revocationReason: null,
pkiSubscriberId: null,
profileId: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
});
vi.mocked(mockCertificateDAL.updateById).mockResolvedValue({
id: "cert-1",
@@ -1147,7 +1153,8 @@ describe("CertificateV3Service", () => {
revocationReason: null,
pkiSubscriberId: null,
profileId: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
});
vi.mocked(mockCertificateDAL.findById).mockResolvedValue({
id: "cert-1",
@@ -1170,7 +1177,8 @@ describe("CertificateV3Service", () => {
revocationReason: null,
pkiSubscriberId: null,
profileId: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
});
vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
return callback(undefined as any);
@@ -1288,7 +1296,8 @@ describe("CertificateV3Service", () => {
revocationReason: null,
pkiSubscriberId: null,
profileId: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
});
vi.mocked(mockCertificateDAL.updateById).mockResolvedValue({
id: "cert-1",
@@ -1311,7 +1320,8 @@ describe("CertificateV3Service", () => {
revocationReason: null,
pkiSubscriberId: null,
profileId: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
});
vi.mocked(mockCertificateDAL.findById).mockResolvedValue({
id: "cert-1",
@@ -1334,7 +1344,8 @@ describe("CertificateV3Service", () => {
revocationReason: null,
pkiSubscriberId: null,
profileId: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
});
vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
return callback(undefined as any);
@@ -1452,7 +1463,8 @@ describe("CertificateV3Service", () => {
revocationReason: null,
pkiSubscriberId: null,
profileId: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
});
vi.mocked(mockCertificateDAL.updateById).mockResolvedValue({
id: "cert-1",
@@ -1475,7 +1487,8 @@ describe("CertificateV3Service", () => {
revocationReason: null,
pkiSubscriberId: null,
profileId: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
});
vi.mocked(mockCertificateDAL.findById).mockResolvedValue({
id: "cert-1",
@@ -1498,7 +1511,8 @@ describe("CertificateV3Service", () => {
revocationReason: null,
pkiSubscriberId: null,
profileId: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
});
vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
return callback(undefined as any);
@@ -1616,7 +1630,8 @@ describe("CertificateV3Service", () => {
revocationReason: null,
pkiSubscriberId: null,
profileId: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
});
vi.mocked(mockCertificateDAL.updateById).mockResolvedValue({
id: "cert-1",
@@ -1639,7 +1654,8 @@ describe("CertificateV3Service", () => {
revocationReason: null,
pkiSubscriberId: null,
profileId: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
});
vi.mocked(mockCertificateDAL.findById).mockResolvedValue({
id: "cert-1",
@@ -1662,7 +1678,8 @@ describe("CertificateV3Service", () => {
revocationReason: null,
pkiSubscriberId: null,
profileId: null,
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
});
vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
return callback(undefined as any);
@@ -1710,7 +1727,8 @@ describe("CertificateV3Service", () => {
renewalError: null,
keyAlgorithm: "RSA_2048",
signatureAlgorithm: "RSA-SHA256",
- source: "issued"
+ source: "issued",
+ keySource: "infisical"
};
const mockProfile = {
diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.ts
index 03709c15fc..b693de9d89 100644
--- a/backend/src/services/certificate/certificate-service.ts
+++ b/backend/src/services/certificate/certificate-service.ts
@@ -579,6 +579,9 @@ export const certificateServiceFactory = ({
*/
const getCertBody = async ({ id, serialNumber, actorId, actorAuthMethod, actor, actorOrgId }: TGetCertBodyDTO) => {
const cert = id ? await certificateDAL.findById(id) : await certificateDAL.findOne({ serialNumber });
+ if (!cert) {
+ throw new NotFoundError({ message: "Certificate not found" });
+ }
const { permission } = await permissionService.getProjectPermission({
actor,
@@ -940,6 +943,9 @@ export const certificateServiceFactory = ({
actorOrgId
}: TGetCertBundleDTO) => {
const cert = id ? await certificateDAL.findById(id) : await certificateDAL.findOne({ serialNumber });
+ if (!cert) {
+ throw new NotFoundError({ message: "Certificate not found" });
+ }
const { permission } = await permissionService.getProjectPermission({
actor,
diff --git a/backend/src/services/hsm-connector/hsm-connector-dal.ts b/backend/src/services/hsm-connector/hsm-connector-dal.ts
new file mode 100644
index 0000000000..6ed8f90e60
--- /dev/null
+++ b/backend/src/services/hsm-connector/hsm-connector-dal.ts
@@ -0,0 +1,71 @@
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify, selectAllTableCols } from "@app/lib/knex";
+
+export type THsmConnectorDALFactory = ReturnType<typeof hsmConnectorDALFactory>;
+
+export const hsmConnectorDALFactory = (db: TDbClient) => {
+ const hsmConnectorOrm = ormify(db, TableName.HsmConnector);
+
+ const countReferencingCertificates = async (connectorId: string): Promise<number> => {
+ try {
+ const result = await db(TableName.Certificate)
+ .where("hsmConnectorId", connectorId)
+ .count<{ count: string }[]>("id as count")
+ .first();
+ return Number(result?.count ?? 0);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "HsmConnectorDAL.countReferencingCertificates" });
+ }
+ };
+
+ const findByProjectId = async (projectId: string) => {
+ try {
+ return await db
+ .replicaNode()(TableName.HsmConnector)
+ .where("projectId", projectId)
+ .select(selectAllTableCols(TableName.HsmConnector))
+ .orderBy("createdAt", "desc");
+ } catch (error) {
+ throw new DatabaseError({ error, name: "HsmConnectorDAL.findByProjectId" });
+ }
+ };
+
+ const listLinkedCertificates = async (connectorId: string, { offset, limit }: { offset: number; limit: number }) => {
+ try {
+ const baseQuery = db.replicaNode()(TableName.Certificate).where("hsmConnectorId", connectorId);
+
+ const [rows, totalCountResult] = await Promise.all([
+ baseQuery
+ .clone()
+ .select("id", "commonName", "status", "notAfter", "hsmKeyLabel", "createdAt")
+ .orderBy("createdAt", "desc")
+ .limit(limit)
+ .offset(offset),
+ baseQuery.clone().count<{ count: string }[]>("id as count").first()
+ ]);
+
+ return {
+ rows: rows.map((r) => ({
+ id: r.id,
+ commonName: r.commonName,
+ status: r.status,
+ notAfter: r.notAfter,
+ hsmKeyLabel: (r.hsmKeyLabel as string | null) ?? null,
+ createdAt: r.createdAt
+ })),
+ totalCount: Number(totalCountResult?.count ?? 0)
+ };
+ } catch (error) {
+ throw new DatabaseError({ error, name: "HsmConnectorDAL.listLinkedCertificates" });
+ }
+ };
+
+ return {
+ ...hsmConnectorOrm,
+ countReferencingCertificates,
+ findByProjectId,
+ listLinkedCertificates
+ };
+};
diff --git a/backend/src/services/hsm-connector/hsm-connector-fns.ts b/backend/src/services/hsm-connector/hsm-connector-fns.ts
new file mode 100644
index 0000000000..719327da04
--- /dev/null
+++ b/backend/src/services/hsm-connector/hsm-connector-fns.ts
@@ -0,0 +1,81 @@
+import { z } from "zod";
+
+import { KmsDataKey } from "@app/services/kms/kms-types";
+
+import type { THsmConnectorServiceFactoryDep } from "./hsm-connector-service";
+import type { THsmConnectorCredentials, THsmConnectorSanitized } from "./hsm-connector-types";
+
+export const HSM_CREDENTIALS_LIMITS = {
+ slotLabelMax: 128,
+ pinMax: 512,
+ keyNamePrefixMax: 64
+} as const;
+
+export const HsmConnectorCredentialsSchema = z.object({
+ slotLabel: z.string().min(1).max(HSM_CREDENTIALS_LIMITS.slotLabelMax),
+ pin: z.string().min(1).max(HSM_CREDENTIALS_LIMITS.pinMax),
+ keyNamePrefix: z.string().min(1).max(HSM_CREDENTIALS_LIMITS.keyNamePrefixMax).optional()
+});
+
+export type THsmConnectorCredentialsSchemaType = z.infer<typeof HsmConnectorCredentialsSchema>;
+
+export const encryptHsmConnectorCredentials = async ({
+ projectId,
+ credentials,
+ kmsService
+}: {
+ projectId: string;
+ credentials: THsmConnectorCredentials;
+ kmsService: THsmConnectorServiceFactoryDep["kmsService"];
+}): Promise<Buffer> => {
+ const { encryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+ const { cipherTextBlob } = encryptor({
+ plainText: Buffer.from(JSON.stringify(credentials))
+ });
+ return cipherTextBlob;
+};
+
+export const decryptHsmConnectorCredentials = async ({
+ projectId,
+ encryptedCredentials,
+ kmsService
+}: {
+ projectId: string;
+ encryptedCredentials: Buffer;
+ kmsService: THsmConnectorServiceFactoryDep["kmsService"];
+}): Promise<THsmConnectorCredentials> => {
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+ const plainText = decryptor({ cipherTextBlob: encryptedCredentials });
+ return HsmConnectorCredentialsSchema.parse(JSON.parse(plainText.toString()));
+};
+
+export const sanitizeHsmConnector = (args: {
+ row: {
+ id: string;
+ name: string;
+ description?: string | null | undefined;
+ projectId: string;
+ gatewayId?: string | null | undefined;
+ gatewayPoolId?: string | null | undefined;
+ createdAt: Date;
+ 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
+});
diff --git a/backend/src/services/hsm-connector/hsm-connector-routing.ts b/backend/src/services/hsm-connector/hsm-connector-routing.ts
new file mode 100644
index 0000000000..cefc90c0d0
--- /dev/null
+++ b/backend/src/services/hsm-connector/hsm-connector-routing.ts
@@ -0,0 +1,222 @@
+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { GatewayProxyProtocol } from "@app/lib/gateway/types";
+import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { callPkcs11Endpoint, isRetryablePkcs11RpcError, Pkcs11RpcEndpoint } from "@app/lib/gateway-v2/pkcs11-rpc";
+import { logger } from "@app/lib/logger";
+
+import {
+ THsmConnectorCredentials,
+ THsmConnectorTestMemberResult,
+ THsmConnectorTestResult
+} from "./hsm-connector-types";
+
+const PKCS11_POOL_RETRY_LIMIT = 2;
+const TEST_FANOUT_MAX = 10;
+const PKCS11_TARGET_HOST = "pkcs11";
+
+type TGatewayRouting = {
+ gatewayId: string | null | undefined;
+ gatewayPoolId: string | null | undefined;
+};
+
+type THsmConnectorRoutingDeps = {
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "listHealthyGateways">;
+};
+
+const isPkcs11Capable = (capabilities: unknown): boolean => {
+ const caps = (capabilities as Record<string, unknown> | null | undefined) ?? {};
+ return caps.pkcs11 === true;
+};
+
+export const hsmConnectorRoutingFactory = ({ gatewayV2Service, gatewayPoolService }: THsmConnectorRoutingDeps) => {
+ const pickGateway = async (connector: TGatewayRouting, triedGatewayIds: Set<string>): Promise<string> => {
+ if (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."
+ });
+ }
+ return connector.gatewayId;
+ }
+ if (!connector.gatewayPoolId) {
+ throw new BadRequestError({ message: "Connector has neither gatewayId nor gatewayPoolId set." });
+ }
+ const healthy = await gatewayPoolService.listHealthyGateways(connector.gatewayPoolId);
+ const capable = healthy.filter((g) => isPkcs11Capable(g.capabilities) && !triedGatewayIds.has(g.id));
+ if (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."
+ });
+ }
+ return capable[Math.floor(Math.random() * capable.length)].id;
+ };
+
+ const dispatchPkcs11 = async <T>(args: {
+ connector: TGatewayRouting;
+ credentials: THsmConnectorCredentials;
+ endpoint: Pkcs11RpcEndpoint;
+ params: Record<string, unknown>;
+ }): Promise<T> => {
+ const triedGatewayIds = new Set<string>();
+ let lastError: { code: string; message: string } | undefined;
+
+ // Retry across pool members must be sequential: each attempt depends on the
+ // previous attempt's outcome (which gateway failed, whether the error is
+ // retryable, etc.). Parallelising would fire redundant PKCS#11 calls.
+ /* eslint-disable no-await-in-loop */
+ for (let attempt = 0; attempt <= PKCS11_POOL_RETRY_LIMIT; attempt += 1) {
+ const gatewayId = await pickGateway(args.connector, triedGatewayIds);
+ triedGatewayIds.add(gatewayId);
+
+ const conn = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
+ gatewayId,
+ targetHost: PKCS11_TARGET_HOST,
+ targetPort: 0
+ });
+ if (!conn) {
+ throw new NotFoundError({
+ message: `Gateway connection details for gateway ${gatewayId} not found.`
+ });
+ }
+
+ try {
+ const response = await withGatewayV2Proxy(
+ async (port) =>
+ callPkcs11Endpoint<T>({
+ port,
+ endpoint: args.endpoint,
+ body: {
+ slotLabel: args.credentials.slotLabel,
+ pin: args.credentials.pin,
+ params: args.params
+ }
+ }),
+ {
+ protocol: GatewayProxyProtocol.Pkcs11,
+ relayHost: conn.relayHost,
+ gateway: conn.gateway,
+ relay: conn.relay
+ }
+ );
+ if (response.ok) return response.result;
+ lastError = { code: response.errorCode, message: response.errorMessage };
+ const retryable = isRetryablePkcs11RpcError({
+ ok: false,
+ status: response.status,
+ errorCode: response.errorCode,
+ errorMessage: response.errorMessage
+ });
+ if (!args.connector.gatewayPoolId || !retryable) {
+ break;
+ }
+ logger.warn(
+ { attempt, gatewayId, code: response.errorCode },
+ `PKCS#11 RPC failed with retryable error; re-rolling pool [gatewayId=${gatewayId}]`
+ );
+ } catch (err) {
+ lastError = {
+ code: "gateway_unreachable",
+ message: err instanceof Error ? err.message : String(err)
+ };
+ if (!args.connector.gatewayPoolId) break;
+ logger.warn({ attempt, gatewayId, err }, `PKCS#11 RPC threw; re-rolling pool member [gatewayId=${gatewayId}]`);
+ }
+ }
+ /* eslint-enable no-await-in-loop */
+
+ throw new BadRequestError({
+ message:
+ lastError !== undefined
+ ? `PKCS#11 request failed (${lastError.code}): ${lastError.message}`
+ : "PKCS#11 request failed against the HSM gateway."
+ });
+ };
+
+ const testOneGateway = async (
+ gatewayId: string,
+ credentials: THsmConnectorCredentials
+ ): Promise<THsmConnectorTestMemberResult> => {
+ const conn = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
+ gatewayId,
+ targetHost: PKCS11_TARGET_HOST,
+ targetPort: 0
+ });
+ if (!conn) {
+ return { gatewayId, ok: false, errorCode: "gateway_not_found", errorMessage: `Gateway ${gatewayId} not found.` };
+ }
+ try {
+ const response = await withGatewayV2Proxy(
+ async (port) =>
+ callPkcs11Endpoint<{ slotInfo: { manufacturer: string; model: string; firmware: string } }>({
+ port,
+ endpoint: "/v1/test",
+ body: {
+ slotLabel: credentials.slotLabel,
+ pin: credentials.pin,
+ params: {}
+ }
+ }),
+ {
+ protocol: GatewayProxyProtocol.Pkcs11,
+ relayHost: conn.relayHost,
+ gateway: conn.gateway,
+ relay: conn.relay
+ }
+ );
+ if (response.ok) {
+ return { gatewayId, ok: true, slotInfo: response.result.slotInfo };
+ }
+ return { gatewayId, ok: false, errorCode: response.errorCode, errorMessage: response.errorMessage };
+ } catch (err) {
+ return {
+ gatewayId,
+ ok: false,
+ errorCode: "gateway_unreachable",
+ errorMessage: err instanceof Error ? err.message : String(err)
+ };
+ }
+ };
+
+ const runTestRoundTrip = async (args: {
+ gatewayId: string | null;
+ gatewayPoolId: string | null;
+ credentials: THsmConnectorCredentials;
+ }): Promise<THsmConnectorTestResult> => {
+ const targets: string[] = [];
+ if (args.gatewayId) {
+ targets.push(args.gatewayId);
+ } else if (args.gatewayPoolId) {
+ const healthy = await gatewayPoolService.listHealthyGateways(args.gatewayPoolId);
+ for (const g of healthy) {
+ if (isPkcs11Capable(g.capabilities)) targets.push(g.id);
+ }
+ 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."
+ });
+ }
+ }
+
+ let probeTargets = targets;
+ if (targets.length > TEST_FANOUT_MAX) {
+ const buf = [...targets];
+ for (let i = 0; i < TEST_FANOUT_MAX; i += 1) {
+ const j = i + Math.floor(Math.random() * (buf.length - i));
+ [buf[i], buf[j]] = [buf[j], buf[i]];
+ }
+ probeTargets = buf.slice(0, TEST_FANOUT_MAX);
+ }
+
+ const members = await Promise.all(probeTargets.map((gwId) => testOneGateway(gwId, args.credentials)));
+ const ok = members.every((m) => m.ok);
+ return { ok, members };
+ };
+
+ return { dispatchPkcs11, runTestRoundTrip };
+};
+
+export type THsmConnectorRoutingFactory = ReturnType<typeof hsmConnectorRoutingFactory>;
diff --git a/backend/src/services/hsm-connector/hsm-connector-service.ts b/backend/src/services/hsm-connector/hsm-connector-service.ts
new file mode 100644
index 0000000000..f430031500
--- /dev/null
+++ b/backend/src/services/hsm-connector/hsm-connector-service.ts
@@ -0,0 +1,409 @@
+import { ForbiddenError } from "@casl/ability";
+
+import { ActionProjectType } from "@app/db/schemas";
+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ProjectPermissionHsmConnectorActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { HsmKeyAlgorithm } from "@app/services/signer/signer-enums";
+
+import type { THsmConnectorDALFactory } from "./hsm-connector-dal";
+import {
+ decryptHsmConnectorCredentials,
+ encryptHsmConnectorCredentials,
+ HsmConnectorCredentialsSchema,
+ sanitizeHsmConnector
+} from "./hsm-connector-fns";
+import { hsmConnectorRoutingFactory } from "./hsm-connector-routing";
+import type {
+ TCreateHsmConnectorDTO,
+ TDeleteHsmConnectorDTO,
+ TGetHsmConnectorByIdDTO,
+ THsmConnectorCredentials,
+ THsmConnectorSanitized,
+ THsmConnectorServiceActor,
+ THsmConnectorTestResult,
+ TListHsmConnectorsDTO,
+ TTestHsmConnectorDTO,
+ TUpdateHsmConnectorDTO
+} from "./hsm-connector-types";
+
+export type THsmConnectorServiceFactoryDep = {
+ hsmConnectorDAL: THsmConnectorDALFactory;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "listHealthyGateways">;
+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+};
+
+export type THsmConnectorServiceFactory = ReturnType<typeof hsmConnectorServiceFactory>;
+
+export const hsmConnectorServiceFactory = ({
+ hsmConnectorDAL,
+ permissionService,
+ kmsService,
+ gatewayV2Service,
+ gatewayPoolService,
+ licenseService
+}: THsmConnectorServiceFactoryDep) => {
+ const routing = hsmConnectorRoutingFactory({ gatewayV2Service, gatewayPoolService });
+
+ const assertLicense = async (orgId: string) => {
+ const plan = await licenseService.getPlan(orgId);
+ if (!plan.pkiHsm) {
+ throw new BadRequestError({
+ message: "Your plan does not include HSM-backed code signing. Please upgrade to use HSM Connectors."
+ });
+ }
+ };
+
+ const assertProjectPermission = async (
+ actor: THsmConnectorServiceActor,
+ projectId: string,
+ action: ProjectPermissionHsmConnectorActions
+ ) => {
+ await assertLicense(actor.orgId);
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+ ForbiddenError.from(permission).throwUnlessCan(action, ProjectPermissionSub.HsmConnectors);
+ };
+
+ const createHsmConnector = async (
+ dto: TCreateHsmConnectorDTO,
+ actor: THsmConnectorServiceActor
+ ): Promise<THsmConnectorSanitized> => {
+ await assertProjectPermission(actor, dto.projectId, ProjectPermissionHsmConnectorActions.Create);
+
+ if (!dto.gatewayId === !dto.gatewayPoolId) {
+ throw new BadRequestError({
+ message: "Exactly one of gatewayId or gatewayPoolId must be set."
+ });
+ }
+
+ const parsedCreds = HsmConnectorCredentialsSchema.safeParse(dto.credentials);
+ if (!parsedCreds.success) {
+ throw new BadRequestError({ message: `Invalid credentials: ${parsedCreds.error.message}` });
+ }
+
+ const testResult = await routing.runTestRoundTrip({
+ gatewayId: dto.gatewayId ?? null,
+ gatewayPoolId: dto.gatewayPoolId ?? null,
+ credentials: parsedCreds.data
+ });
+ if (!testResult.ok) {
+ const first = testResult.members.find((m) => !m.ok);
+ throw new BadRequestError({
+ message:
+ first && !first.ok
+ ? `Test round trip failed (${first.errorCode}): ${first.errorMessage}`
+ : "Test round trip against the HSM failed."
+ });
+ }
+
+ const encryptedCredentials = await encryptHsmConnectorCredentials({
+ projectId: dto.projectId,
+ credentials: parsedCreds.data,
+ kmsService
+ });
+
+ let row: Awaited<ReturnType<typeof hsmConnectorDAL.create>>;
+ try {
+ row = await hsmConnectorDAL.create({
+ name: dto.name,
+ description: dto.description,
+ projectId: dto.projectId,
+ gatewayId: dto.gatewayId ?? null,
+ gatewayPoolId: dto.gatewayPoolId ?? null,
+ encryptedCredentials
+ });
+ } catch (err) {
+ // 23505 = unique constraint violation: UNIQUE(projectId, name) on hsm_connectors.
+ 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.`
+ });
+ }
+ throw err;
+ }
+
+ return sanitizeHsmConnector({ row, credentials: parsedCreds.data });
+ };
+
+ const listHsmConnectors = async (
+ dto: TListHsmConnectorsDTO,
+ actor: THsmConnectorServiceActor
+ ): Promise<THsmConnectorSanitized[]> => {
+ await assertProjectPermission(actor, dto.projectId, ProjectPermissionHsmConnectorActions.Read);
+
+ const rows = await hsmConnectorDAL.findByProjectId(dto.projectId);
+ return Promise.all(
+ rows.map(async (row) => {
+ const credentials = await decryptHsmConnectorCredentials({
+ projectId: row.projectId,
+ encryptedCredentials: row.encryptedCredentials,
+ kmsService
+ });
+ return sanitizeHsmConnector({ row, credentials });
+ })
+ );
+ };
+
+ const getHsmConnectorById = async (
+ dto: TGetHsmConnectorByIdDTO,
+ actor: THsmConnectorServiceActor
+ ): Promise<THsmConnectorSanitized> => {
+ 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.Read);
+
+ const credentials = await decryptHsmConnectorCredentials({
+ projectId: row.projectId,
+ encryptedCredentials: row.encryptedCredentials,
+ kmsService
+ });
+ return sanitizeHsmConnector({ row, credentials });
+ };
+
+ const updateHsmConnector = async (
+ dto: TUpdateHsmConnectorDTO,
+ actor: THsmConnectorServiceActor
+ ): Promise<THsmConnectorSanitized> => {
+ 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.Edit);
+
+ let nextGatewayId: string | null = row.gatewayId ?? null;
+ let nextGatewayPoolId: string | null = row.gatewayPoolId ?? null;
+ const routingChanged = dto.gatewayId !== undefined || dto.gatewayPoolId !== undefined;
+ if (dto.gatewayId !== undefined) {
+ nextGatewayId = dto.gatewayId ?? null;
+ if (nextGatewayId) nextGatewayPoolId = null;
+ }
+ if (dto.gatewayPoolId !== undefined) {
+ nextGatewayPoolId = dto.gatewayPoolId ?? null;
+ if (nextGatewayPoolId) nextGatewayId = null;
+ }
+ if (!nextGatewayId === !nextGatewayPoolId) {
+ throw new BadRequestError({
+ message: "Exactly one of gatewayId or gatewayPoolId must be set after update."
+ });
+ }
+
+ const currentCreds = await decryptHsmConnectorCredentials({
+ projectId: row.projectId,
+ encryptedCredentials: row.encryptedCredentials,
+ kmsService
+ });
+ const credentialsChanged = dto.credentials !== undefined;
+ const mergedCreds: THsmConnectorCredentials = {
+ slotLabel: dto.credentials?.slotLabel ?? currentCreds.slotLabel,
+ pin: dto.credentials?.pin ?? currentCreds.pin,
+ keyNamePrefix: dto.credentials?.keyNamePrefix ?? currentCreds.keyNamePrefix
+ };
+ const parsedCreds = HsmConnectorCredentialsSchema.safeParse(mergedCreds);
+ if (!parsedCreds.success) {
+ throw new BadRequestError({ message: `Invalid credentials: ${parsedCreds.error.message}` });
+ }
+
+ if (routingChanged || credentialsChanged) {
+ const testResult = await routing.runTestRoundTrip({
+ gatewayId: nextGatewayId,
+ gatewayPoolId: nextGatewayPoolId,
+ credentials: parsedCreds.data
+ });
+ if (!testResult.ok) {
+ const first = testResult.members.find((m) => !m.ok);
+ throw new BadRequestError({
+ message:
+ first && !first.ok
+ ? `Test round trip failed (${first.errorCode}): ${first.errorMessage}`
+ : "Test round trip against the HSM failed."
+ });
+ }
+ }
+
+ const update: Record<string, unknown> = {
+ gatewayId: nextGatewayId,
+ gatewayPoolId: nextGatewayPoolId
+ };
+ if (dto.name !== undefined) update.name = dto.name;
+ if (dto.description !== undefined) update.description = dto.description;
+ if (credentialsChanged) {
+ update.encryptedCredentials = await encryptHsmConnectorCredentials({
+ projectId: row.projectId,
+ credentials: parsedCreds.data,
+ kmsService
+ });
+ }
+
+ const updated = await hsmConnectorDAL.updateById(row.id, update);
+
+ return sanitizeHsmConnector({ row: updated, credentials: parsedCreds.data });
+ };
+
+ const deleteHsmConnector = async (
+ dto: TDeleteHsmConnectorDTO,
+ actor: THsmConnectorServiceActor
+ ): Promise<{ id: string }> => {
+ 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 };
+ };
+
+ const listLinkedCertificates = async (
+ dto: { connectorId: string; offset: number; limit: number },
+ 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.Read);
+ const { rows, totalCount } = await hsmConnectorDAL.listLinkedCertificates(row.id, {
+ offset: dto.offset,
+ limit: dto.limit
+ });
+ return { linkedCertificates: rows, totalCount };
+ };
+
+ const testHsmConnector = async (
+ dto: TTestHsmConnectorDTO,
+ actor: THsmConnectorServiceActor
+ ): Promise<THsmConnectorTestResult> => {
+ 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.Test);
+
+ const credentials = await decryptHsmConnectorCredentials({
+ projectId: row.projectId,
+ encryptedCredentials: row.encryptedCredentials,
+ kmsService
+ });
+
+ return routing.runTestRoundTrip({
+ gatewayId: row.gatewayId ?? null,
+ gatewayPoolId: row.gatewayPoolId ?? null,
+ credentials
+ });
+ };
+
+ const $loadConnector = async (connectorId: string, expectedProjectId: string) => {
+ const row = await hsmConnectorDAL.findById(connectorId);
+ if (!row || row.projectId !== expectedProjectId) {
+ throw new NotFoundError({ message: `HSM Connector ${connectorId} not found.` });
+ }
+ const credentials = await decryptHsmConnectorCredentials({
+ projectId: row.projectId,
+ encryptedCredentials: row.encryptedCredentials,
+ kmsService
+ });
+ return { row, credentials };
+ };
+
+ const generateKeyPair = async (args: {
+ connectorId: string;
+ projectId: string;
+ keyLabel: string;
+ keyAlgorithm: HsmKeyAlgorithm;
+ }): Promise<Buffer> => {
+ const { row, credentials } = await $loadConnector(args.connectorId, args.projectId);
+ const result = await routing.dispatchPkcs11<{ publicKey: string }>({
+ connector: { gatewayId: row.gatewayId, gatewayPoolId: row.gatewayPoolId },
+ credentials,
+ endpoint: "/v1/generate-key-pair",
+ params: { keyLabel: args.keyLabel, keyAlgorithm: args.keyAlgorithm }
+ });
+ return Buffer.from(result.publicKey, "base64");
+ };
+
+ const sign = async (args: {
+ connectorId: string;
+ projectId: string;
+ keyLabel: string;
+ mechanism: string;
+ data: Buffer;
+ isDigest: boolean;
+ }): Promise<Buffer> => {
+ const { row, credentials } = await $loadConnector(args.connectorId, args.projectId);
+ const result = await routing.dispatchPkcs11<{ signature: string }>({
+ connector: { gatewayId: row.gatewayId, gatewayPoolId: row.gatewayPoolId },
+ credentials,
+ endpoint: "/v1/sign",
+ params: {
+ keyLabel: args.keyLabel,
+ mechanism: args.mechanism,
+ data: args.data.toString("base64"),
+ isDigest: args.isDigest
+ }
+ });
+ return Buffer.from(result.signature, "base64");
+ };
+
+ const getPublicKey = async (args: { connectorId: string; projectId: string; keyLabel: string }): Promise<Buffer> => {
+ const { row, credentials } = await $loadConnector(args.connectorId, args.projectId);
+ const result = await routing.dispatchPkcs11<{ publicKey: string }>({
+ connector: { gatewayId: row.gatewayId, gatewayPoolId: row.gatewayPoolId },
+ credentials,
+ endpoint: "/v1/get-public-key",
+ params: { keyLabel: args.keyLabel }
+ });
+ return Buffer.from(result.publicKey, "base64");
+ };
+
+ const assertAttachPermission = async (
+ actor: Pick<THsmConnectorServiceActor, "type" | "id" | "authMethod" | "orgId">,
+ connectorId: string,
+ projectId: string
+ ) => {
+ await assertProjectPermission(
+ actor as THsmConnectorServiceActor,
+ projectId,
+ ProjectPermissionHsmConnectorActions.Attach
+ );
+ const row = await hsmConnectorDAL.findById(connectorId);
+ if (!row || row.projectId !== projectId) {
+ throw new NotFoundError({ message: `HSM Connector ${connectorId} not found.` });
+ }
+ return row;
+ };
+
+ return {
+ createHsmConnector,
+ listHsmConnectors,
+ getHsmConnectorById,
+ updateHsmConnector,
+ deleteHsmConnector,
+ testHsmConnector,
+ listLinkedCertificates,
+ assertAttachPermission,
+ generateKeyPair,
+ sign,
+ getPublicKey
+ };
+};
diff --git a/backend/src/services/hsm-connector/hsm-connector-types.ts b/backend/src/services/hsm-connector/hsm-connector-types.ts
new file mode 100644
index 0000000000..61a1ecaeec
--- /dev/null
+++ b/backend/src/services/hsm-connector/hsm-connector-types.ts
@@ -0,0 +1,71 @@
+import { OrgServiceActor } from "@app/lib/types";
+
+export type THsmConnectorCredentials = {
+ slotLabel: string;
+ pin: string;
+ keyNamePrefix?: string;
+};
+
+export type TCreateHsmConnectorDTO = {
+ name: string;
+ description?: string;
+ projectId: string;
+ gatewayId?: string;
+ gatewayPoolId?: string;
+ credentials: THsmConnectorCredentials;
+};
+
+export type TUpdateHsmConnectorDTO = {
+ connectorId: string;
+ name?: string;
+ description?: string;
+ gatewayId?: string;
+ gatewayPoolId?: string;
+ credentials?: Partial<THsmConnectorCredentials>;
+};
+
+export type TGetHsmConnectorByIdDTO = {
+ connectorId: string;
+};
+
+export type TListHsmConnectorsDTO = {
+ projectId: string;
+};
+
+export type TDeleteHsmConnectorDTO = {
+ connectorId: string;
+};
+
+export type TTestHsmConnectorDTO = {
+ connectorId: string;
+};
+
+export type TPkcs11SlotInfo = {
+ manufacturer: string;
+ model: string;
+ firmware: string;
+};
+
+export type THsmConnectorTestMemberResult =
+ | { gatewayId: string; ok: true; slotInfo: TPkcs11SlotInfo }
+ | { gatewayId: string; ok: false; errorCode: string; errorMessage: string };
+
+export type THsmConnectorTestResult = {
+ ok: boolean;
+ members: THsmConnectorTestMemberResult[];
+};
+
+export type THsmConnectorSanitized = {
+ id: string;
+ name: string;
+ description: string | null;
+ projectId: string;
+ gatewayId: string | null;
+ gatewayPoolId: string | null;
+ slotLabel: string;
+ keyNamePrefix: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+};
+
+export type THsmConnectorServiceActor = OrgServiceActor;
diff --git a/backend/src/services/signer/signer-enums.ts b/backend/src/services/signer/signer-enums.ts
index 629e70e2fc..ba76bb030e 100644
--- a/backend/src/services/signer/signer-enums.ts
+++ b/backend/src/services/signer/signer-enums.ts
@@ -7,6 +7,7 @@ export enum SignerStatus {
}
export enum SigningOperationStatus {
+ Pending = "pending",
Success = "success",
Failed = "failed",
Denied = "denied"
@@ -17,3 +18,15 @@ export enum SignerIssuanceJobStatus {
Completed = "completed",
Failed = "failed"
}
+
+export enum CertKeySource {
+ Infisical = "infisical",
+ Hsm = "hsm"
+}
+
+export enum HsmKeyAlgorithm {
+ RSA_2048 = "RSA_2048",
+ RSA_4096 = "RSA_4096",
+ ECC_P256 = "ECC_P256",
+ ECC_P384 = "ECC_P384"
+}
diff --git a/backend/src/services/signer/signer-issuance-fns.ts b/backend/src/services/signer/signer-issuance-fns.ts
index e3484e3331..47d921ec08 100644
--- a/backend/src/services/signer/signer-issuance-fns.ts
+++ b/backend/src/services/signer/signer-issuance-fns.ts
@@ -4,8 +4,10 @@ import { Knex } from "knex";
import { crypto } from "@app/lib/crypto/cryptography";
import { isPqcAlgorithm } from "@app/lib/crypto/pqc";
+import { buildCsrWithExternalSigner } from "@app/lib/csr/build-csr-with-external-signer";
import { BadRequestError } from "@app/lib/errors";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
+import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
import {
CertExtendedKeyUsage,
@@ -16,9 +18,11 @@ import { TCertificateAuthorityDALFactory } from "@app/services/certificate-autho
import { CaStatus } from "@app/services/certificate-authority/certificate-authority-enums";
import { keyAlgorithmToAlgCfg } from "@app/services/certificate-authority/certificate-authority-fns";
import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service";
+import type { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
+import { CertKeySource, HsmKeyAlgorithm } from "@app/services/signer/signer-enums";
type TIssueSignerCertificateDeps = {
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;
@@ -37,9 +41,9 @@ type TVerifyCodeSigningEkuDeps = {
export const verifyCodeSigningEku = async (
{ certificateBodyDAL, projectDAL, kmsService }: TVerifyCodeSigningEkuDeps,
- { certificateId, projectId }: { certificateId: string; projectId: string }
+ { certificateId, projectId, tx }: { certificateId: string; projectId: string; tx?: Knex }
): Promise<void> => {
- const certBody = await certificateBodyDAL.findOne({ certId: certificateId });
+ const certBody = await certificateBodyDAL.findOne({ certId: certificateId }, tx);
if (!certBody?.encryptedCertificate) {
throw new BadRequestError({
message: "Cannot verify code-signing usage: certificate body is missing."
@@ -146,7 +150,7 @@ export const issueSignerCertificate = async (
await verifyCodeSigningEku(
{ certificateBodyDAL, projectDAL, kmsService },
- { certificateId: signResult.certificateId, projectId: ca.projectId }
+ { certificateId: signResult.certificateId, projectId: ca.projectId, tx }
);
const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
@@ -173,3 +177,232 @@ export const issueSignerCertificate = async (
return { certificateId: signResult.certificateId };
};
+
+type THsmBackedDeps = {
+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;
+ internalCertificateAuthorityService: Pick<TInternalCertificateAuthorityServiceFactory, "signCertFromCa">;
+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;
+ certificateDAL: Pick<TCertificateDALFactory, "updateById">;
+ hsmConnectorService: Pick<THsmConnectorServiceFactory, "generateKeyPair" | "sign">;
+ projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
+ kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;
+};
+
+type THsmBackedInput = {
+ caId: string;
+ projectId: string;
+ commonName: string;
+ certificateTtlDays: number;
+ hsmConnectorId: string;
+ hsmKeyAlgorithm: HsmKeyAlgorithm;
+ tx?: Knex;
+};
+
+export const hsmKeyAlgorithmToCertKeyAlgorithm = (hsmAlg: HsmKeyAlgorithm): CertKeyAlgorithm => {
+ switch (hsmAlg) {
+ case HsmKeyAlgorithm.RSA_2048:
+ return CertKeyAlgorithm.RSA_2048;
+ case HsmKeyAlgorithm.RSA_4096:
+ return CertKeyAlgorithm.RSA_4096;
+ case HsmKeyAlgorithm.ECC_P256:
+ return CertKeyAlgorithm.ECDSA_P256;
+ case HsmKeyAlgorithm.ECC_P384:
+ return CertKeyAlgorithm.ECDSA_P384;
+ default: {
+ const exhaustive: never = hsmAlg;
+ throw new BadRequestError({ message: `Unsupported HSM key algorithm: ${exhaustive as string}` });
+ }
+ }
+};
+
+export const mapCertKeyAlgorithmToHsmKeyAlgorithm = (certAlg: string): HsmKeyAlgorithm => {
+ switch (certAlg) {
+ case CertKeyAlgorithm.RSA_2048:
+ return HsmKeyAlgorithm.RSA_2048;
+ case CertKeyAlgorithm.RSA_4096:
+ return HsmKeyAlgorithm.RSA_4096;
+ case CertKeyAlgorithm.ECDSA_P256:
+ return HsmKeyAlgorithm.ECC_P256;
+ case CertKeyAlgorithm.ECDSA_P384:
+ return HsmKeyAlgorithm.ECC_P384;
+ default:
+ throw new BadRequestError({
+ message: `Cannot route HSM renewal: cert keyAlgorithm "${certAlg}" is not supported by the HSM Connector.`
+ });
+ }
+};
+
+export const issueHsmBackedSignerCertificate = async (
+ deps: THsmBackedDeps,
+ input: THsmBackedInput
+): 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.`
+ });
+ }
+ if (ca.status !== CaStatus.ACTIVE) {
+ throw new BadRequestError({ message: "The selected certificate authority is not active." });
+ }
+ if (!ca.internalCa?.id) {
+ throw new BadRequestError({
+ message: "Internal CA record is missing its internal-CA association; cannot issue a signer certificate from it."
+ });
+ }
+
+ const keyLabel = `infisical-signer-${crypto.nativeCrypto.randomUUID()}`;
+
+ const publicKeySpkiDer = await deps.hsmConnectorService.generateKeyPair({
+ connectorId: input.hsmConnectorId,
+ projectId: input.projectId,
+ keyLabel,
+ keyAlgorithm: input.hsmKeyAlgorithm
+ });
+ const built = await buildCsrWithExternalSigner({
+ publicKeySpkiDer,
+ keyAlgorithm: input.hsmKeyAlgorithm,
+ subjectCommonName: input.commonName,
+ signCallback: async (tbsBytes, mechanism, isDigest) =>
+ deps.hsmConnectorService.sign({
+ connectorId: input.hsmConnectorId,
+ projectId: input.projectId,
+ keyLabel,
+ mechanism,
+ data: tbsBytes,
+ isDigest
+ })
+ });
+
+ const run = async (tx: Knex) => {
+ const issued = await deps.internalCertificateAuthorityService.signCertFromCa({
+ isInternal: true,
+ isFromProfile: true,
+ caId: ca.id,
+ csr: built.csrPem,
+ commonName: input.commonName,
+ ttl: `${input.certificateTtlDays}d`,
+ extendedKeyUsages: [CertExtendedKeyUsage.CODE_SIGNING],
+ tx
+ });
+ if (!issued.certificateId) {
+ throw new BadRequestError({ message: "Certificate authority did not return a certificate id." });
+ }
+ await verifyCodeSigningEku(
+ { certificateBodyDAL: deps.certificateBodyDAL, projectDAL: deps.projectDAL, kmsService: deps.kmsService },
+ { certificateId: issued.certificateId, projectId: ca.projectId, tx }
+ );
+ await deps.certificateDAL.updateById(
+ issued.certificateId,
+ {
+ keySource: CertKeySource.Hsm,
+ hsmConnectorId: input.hsmConnectorId,
+ hsmKeyLabel: keyLabel,
+ hsmPublicKeySpki: publicKeySpkiDer,
+ keyAlgorithm: hsmKeyAlgorithmToCertKeyAlgorithm(input.hsmKeyAlgorithm)
+ },
+ tx
+ );
+ return issued.certificateId;
+ };
+ const certificateId = input.tx ? await run(input.tx) : await deps.projectDAL.transaction(run);
+
+ return { certificateId, hsmKeyLabel: keyLabel };
+};
+
+type THsmBackedRenewInput = {
+ caId: string;
+ projectId: string;
+ commonName: string;
+ certificateTtlDays: number;
+ hsmConnectorId: string;
+ hsmKeyLabel: string;
+ hsmKeyAlgorithm: HsmKeyAlgorithm;
+ expectedPublicKeySpkiDer?: Buffer;
+ tx?: Knex;
+};
+
+type THsmBackedRenewDeps = THsmBackedDeps & {
+ hsmConnectorService: Pick<THsmConnectorServiceFactory, "generateKeyPair" | "sign" | "getPublicKey">;
+};
+
+export const renewHsmBackedSignerCertificate = async (
+ deps: THsmBackedRenewDeps,
+ input: THsmBackedRenewInput
+): 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.` });
+ }
+ if (ca.status !== CaStatus.ACTIVE) {
+ throw new BadRequestError({ message: "The selected certificate authority is not active." });
+ }
+ if (!ca.internalCa?.id) {
+ throw new BadRequestError({
+ message: "Internal CA record is missing its internal-CA association; cannot renew a signer certificate from it."
+ });
+ }
+
+ const publicKeySpkiDer = await deps.hsmConnectorService.getPublicKey({
+ connectorId: input.hsmConnectorId,
+ projectId: input.projectId,
+ keyLabel: input.hsmKeyLabel
+ });
+ if (input.expectedPublicKeySpkiDer) {
+ const stored = input.expectedPublicKeySpkiDer;
+ 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."
+ });
+ }
+ }
+ const built = await buildCsrWithExternalSigner({
+ publicKeySpkiDer,
+ keyAlgorithm: input.hsmKeyAlgorithm,
+ subjectCommonName: input.commonName,
+ signCallback: async (tbsBytes, mechanism, isDigest) =>
+ deps.hsmConnectorService.sign({
+ connectorId: input.hsmConnectorId,
+ projectId: input.projectId,
+ keyLabel: input.hsmKeyLabel,
+ mechanism,
+ data: tbsBytes,
+ isDigest
+ })
+ });
+
+ const run = async (tx: Knex) => {
+ const signResult = await deps.internalCertificateAuthorityService.signCertFromCa({
+ isInternal: true,
+ isFromProfile: true,
+ caId: ca.id,
+ csr: built.csrPem,
+ commonName: input.commonName,
+ ttl: `${input.certificateTtlDays}d`,
+ extendedKeyUsages: [CertExtendedKeyUsage.CODE_SIGNING],
+ tx
+ });
+ if (!signResult.certificateId) {
+ throw new BadRequestError({ message: "Certificate authority did not return a certificate id." });
+ }
+ await verifyCodeSigningEku(
+ { certificateBodyDAL: deps.certificateBodyDAL, projectDAL: deps.projectDAL, kmsService: deps.kmsService },
+ { certificateId: signResult.certificateId, projectId: ca.projectId, tx }
+ );
+ await deps.certificateDAL.updateById(
+ signResult.certificateId,
+ {
+ keySource: CertKeySource.Hsm,
+ hsmConnectorId: input.hsmConnectorId,
+ hsmKeyLabel: input.hsmKeyLabel,
+ keyAlgorithm: hsmKeyAlgorithmToCertKeyAlgorithm(input.hsmKeyAlgorithm)
+ },
+ tx
+ );
+ return signResult.certificateId;
+ };
+ const certificateId = input.tx ? await run(input.tx) : await deps.projectDAL.transaction(run);
+
+ return { certificateId, hsmKeyLabel: input.hsmKeyLabel };
+};
diff --git a/backend/src/services/signer/signer-issuance-service.ts b/backend/src/services/signer/signer-issuance-service.ts
index 44e987d643..759f119f64 100644
--- a/backend/src/services/signer/signer-issuance-service.ts
+++ b/backend/src/services/signer/signer-issuance-service.ts
@@ -4,23 +4,27 @@ import * as x509 from "@peculiar/x509";
import { TPkiSignerCertificateIssuanceJobs } from "@app/db/schemas";
import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
import { crypto } from "@app/lib/crypto/cryptography";
+import { buildCsrWithExternalSigner } from "@app/lib/csr/build-csr-with-external-signer";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";
+import { TCertificateDALFactory } from "../certificate/certificate-dal";
import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-dal";
import { CertExtendedKeyUsage, CertKeyAlgorithm, CertKeyUsage } from "../certificate/certificate-types";
import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";
import { CaStatus, CaType } from "../certificate-authority/certificate-authority-enums";
import { keyAlgorithmToAlgCfg } from "../certificate-authority/certificate-authority-fns";
import { TCertificateIssuanceQueueFactory } from "../certificate-authority/certificate-issuance-queue";
+import { THsmConnectorServiceFactory } from "../hsm-connector/hsm-connector-service";
+import { THsmConnectorServiceActor } from "../hsm-connector/hsm-connector-types";
import { TKmsServiceFactory } from "../kms/kms-service";
import { TProjectDALFactory } from "../project/project-dal";
import { getProjectKmsCertificateKeyId } from "../project/project-fns";
import { TSignerDALFactory } from "./signer-dal";
-import { SignerIssuanceJobStatus, SignerStatus } from "./signer-enums";
+import { CertKeySource, HsmKeyAlgorithm, SignerIssuanceJobStatus, SignerStatus } from "./signer-enums";
import { formatSignerIssuanceErrorReason, isTerminalIssuanceError } from "./signer-issuance-errors";
-import { verifyCodeSigningEku } from "./signer-issuance-fns";
+import { hsmKeyAlgorithmToCertKeyAlgorithm, verifyCodeSigningEku } from "./signer-issuance-fns";
import { TSignerIssuanceJobDALFactory } from "./signer-issuance-job-dal";
const POLL_INTERVAL_PATTERN = "*/15 * * * *"; // every 15 minutes
@@ -38,8 +42,10 @@ type TSignerIssuanceServiceDeps = {
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create" | "updateById">;
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "decryptWithKmsKey" | "generateKmsKey">;
- certificateIssuanceQueue: Pick<TCertificateIssuanceQueueFactory, "azureAdCsFns" | "awsPcaFns">;
+ certificateIssuanceQueue: Pick<TCertificateIssuanceQueueFactory, "awsPcaFns" | "azureAdCsFns">;
cronJob: TCronJobFactory;
+ hsmConnectorService: Pick<THsmConnectorServiceFactory, "generateKeyPair" | "sign" | "assertAttachPermission">;
+ certificateDAL: Pick<TCertificateDALFactory, "updateById">;
};
type TRequestIssuanceInput = {
@@ -49,6 +55,13 @@ type TRequestIssuanceInput = {
commonName: string;
certificateTtlDays: number;
keyAlgorithm?: CertKeyAlgorithm;
+ hsm?: {
+ hsmConnectorId: string;
+ hsmKeyAlgorithm: HsmKeyAlgorithm;
+ hsmKeyLabel?: string;
+ hsmPublicKeySpki?: Buffer;
+ actor?: Pick<THsmConnectorServiceActor, "type" | "id" | "authMethod" | "orgId">;
+ };
};
export const signerIssuanceServiceFactory = ({
@@ -60,9 +73,11 @@ export const signerIssuanceServiceFactory = ({
projectDAL,
kmsService,
certificateIssuanceQueue,
- cronJob
+ cronJob,
+ hsmConnectorService,
+ certificateDAL
}: TSignerIssuanceServiceDeps) => {
- const { azureAdCsFns, awsPcaFns } = certificateIssuanceQueue;
+ const { awsPcaFns, azureAdCsFns } = certificateIssuanceQueue;
const buildCsrForSigner = async (
commonName: string,
@@ -122,6 +137,69 @@ 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);
+ }
+ const reuseExistingKey = Boolean(input.hsm.hsmKeyLabel && input.hsm.hsmPublicKeySpki);
+ const keyLabel = reuseExistingKey
+ ? (input.hsm.hsmKeyLabel as string)
+ : `infisical-signer-${crypto.nativeCrypto.randomUUID()}`;
+ const publicKeySpkiDer = reuseExistingKey
+ ? Buffer.from(input.hsm.hsmPublicKeySpki as Buffer)
+ : await hsmConnectorService.generateKeyPair({
+ connectorId: input.hsm.hsmConnectorId,
+ projectId: input.projectId,
+ keyLabel,
+ keyAlgorithm: input.hsm.hsmKeyAlgorithm
+ });
+ const built = await buildCsrWithExternalSigner({
+ publicKeySpkiDer,
+ keyAlgorithm: input.hsm.hsmKeyAlgorithm,
+ subjectCommonName: input.commonName,
+ signCallback: async (tbs, mech, isDigest) =>
+ hsmConnectorService.sign({
+ connectorId: input.hsm!.hsmConnectorId,
+ projectId: input.projectId,
+ keyLabel,
+ mechanism: mech,
+ data: tbs,
+ isDigest
+ })
+ });
+ 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()
+ });
+
+ void (async () => {
+ try {
+ await processJob(hsmJob.id);
+ } catch (err) {
+ logger.warn(
+ err,
+ `signer issuance: first-attempt HSM-backed job failed, cron will retry [jobId=${hsmJob.id}] [signerId=${input.signerId}]`
+ );
+ }
+ })();
+ return hsmJob;
+ }
+
const keyAlgorithm: CertKeyAlgorithm = input.keyAlgorithm ?? CertKeyAlgorithm.RSA_2048;
const { csrPem, privateKeyPem } = await buildCsrForSigner(input.commonName, keyAlgorithm);
@@ -291,6 +369,26 @@ 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"
+ );
+ await markJobFailed(job, reason);
+ return;
+ }
+ }
+
await signerDAL.transaction(async (tx) => {
await signerDAL.updateById(
job.signerId,
@@ -328,21 +426,23 @@ export const signerIssuanceServiceFactory = ({
let certificateId: string;
if (kind === CaType.AZURE_AD_CS) {
+ if (job.keySource === CertKeySource.Hsm) {
+ throw new BadRequestError({
+ message:
+ "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({
caId: job.caId,
- profileId: undefined as unknown as string,
commonName: job.commonName,
altNames: [],
keyUsages: [CertKeyUsage.DIGITAL_SIGNATURE, CertKeyUsage.KEY_ENCIPHERMENT],
extendedKeyUsages: [CertExtendedKeyUsage.CODE_SIGNING],
validity: { ttl: `${job.certificateTtlDays}d` },
- signatureAlgorithm: undefined,
keyAlgorithm: job.keyAlgorithm as CertKeyAlgorithm,
isRenewal: false,
- originalCertificateId: undefined,
- csr,
isCancelled: async () => false
- } as Parameters<typeof azureAdCsFns.orderCertificateFromProfile>[0]);
+ });
if (!azureResult?.certificateId) {
throw new BadRequestError({ message: "Azure AD CS order returned without a certificate id." });
}
@@ -350,16 +450,13 @@ export const signerIssuanceServiceFactory = ({
} else {
const awsResult = await awsPcaFns.orderCertificateFromProfile({
caId: job.caId,
- profileId: undefined as unknown as string,
commonName: job.commonName,
altNames: [],
keyUsages: [CertKeyUsage.DIGITAL_SIGNATURE, CertKeyUsage.KEY_ENCIPHERMENT],
extendedKeyUsages: [CertExtendedKeyUsage.CODE_SIGNING],
validity: { ttl: `${job.certificateTtlDays}d` },
- signatureAlgorithm: undefined,
keyAlgorithm: job.keyAlgorithm as CertKeyAlgorithm,
isRenewal: false,
- originalCertificateId: undefined,
csr,
isCancelled: async () => false
});
@@ -426,7 +523,6 @@ export const signerIssuanceServiceFactory = ({
return {
requestIssuance,
processJob,
- start,
- _buildCsrForSigner: buildCsrForSigner
+ start
};
};
diff --git a/backend/src/services/signer/signer-service.ts b/backend/src/services/signer/signer-service.ts
index eec9342ff6..459c8a5c43 100644
--- a/backend/src/services/signer/signer-service.ts
+++ b/backend/src/services/signer/signer-service.ts
@@ -23,8 +23,10 @@ import {
import { crypto } from "@app/lib/crypto/cryptography";
import { signingService } from "@app/lib/crypto/sign/signing";
import { AsymmetricKeyAlgorithm, SigningAlgorithm } from "@app/lib/crypto/sign/types";
+import { ecdsaRawRsToDer, mapSigningAlgorithmToPkcs11Mechanism } from "@app/lib/csr/pkcs11-algorithm-map";
import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
+import { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";
import {
TApprovalPolicyDALFactory,
@@ -54,9 +56,14 @@ 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 { SignerStatus, SigningOperationStatus } from "./signer-enums";
+import { CertKeySource, SignerStatus, SigningOperationStatus } from "./signer-enums";
import { formatSignerIssuanceErrorReason } from "./signer-issuance-errors";
-import { issueSignerCertificate } from "./signer-issuance-fns";
+import {
+ issueHsmBackedSignerCertificate,
+ issueSignerCertificate,
+ mapCertKeyAlgorithmToHsmKeyAlgorithm,
+ renewHsmBackedSignerCertificate
+} from "./signer-issuance-fns";
import { TSignerIssuanceServiceFactory } from "./signer-issuance-service";
import {
TCreateSignerDTO,
@@ -106,7 +113,11 @@ const computeEffectiveStatus = (signer: {
type TSignerServiceFactoryDep = {
signerDAL: TSignerDALFactory;
signingOperationDAL: TSigningOperationDALFactory;
- certificateDAL: Pick<TCertificateDALFactory, "findById">;
+ hsmConnectorService: Pick<
+ THsmConnectorServiceFactory,
+ "sign" | "generateKeyPair" | "getPublicKey" | "assertAttachPermission"
+ >;
+ certificateDAL: Pick<TCertificateDALFactory, "findById" | "updateById">;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;
@@ -190,7 +201,8 @@ export const signerServiceFactory = ({
approvalRequestDAL,
approvalRequestGrantsDAL,
membershipDAL,
- membershipRoleDAL
+ membershipRoleDAL,
+ hsmConnectorService
}: TSignerServiceFactoryDep) => {
const $loadSignerResourcePermission = async (
signerId: string,
@@ -292,24 +304,63 @@ export const signerServiceFactory = ({
let issuedCertificateId: string | null = null;
if (usingCa && resolvedCaId && !isExternalCa) {
- const { certificateId } = await issueSignerCertificate(
- {
- certificateAuthorityDAL,
- internalCertificateAuthorityService,
- certificateBodyDAL,
- certificateSecretDAL,
- projectDAL,
- kmsService
- },
- {
- caId: resolvedCaId,
- projectId: dto.projectId,
- commonName: dto.commonName as string,
- certificateTtlDays: dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS,
- keyAlgorithm
+ const certificateInput = dto.certificate;
+ if (certificateInput?.keySource === CertKeySource.Hsm) {
+ if (!certificateInput.hsmConnectorId || !certificateInput.hsmKeyAlgorithm) {
+ throw new BadRequestError({
+ message: "hsmConnectorId and hsmKeyAlgorithm are required when certificate.keySource = 'hsm'."
+ });
}
- );
- issuedCertificateId = certificateId;
+ await hsmConnectorService.assertAttachPermission(
+ {
+ type: dto.actor,
+ id: dto.actorId,
+ authMethod: dto.actorAuthMethod,
+ orgId: dto.actorOrgId
+ },
+ certificateInput.hsmConnectorId,
+ dto.projectId
+ );
+ const { certificateId } = await issueHsmBackedSignerCertificate(
+ {
+ certificateAuthorityDAL,
+ internalCertificateAuthorityService,
+ certificateBodyDAL,
+ certificateDAL,
+ hsmConnectorService,
+ projectDAL,
+ kmsService
+ },
+ {
+ caId: resolvedCaId,
+ projectId: dto.projectId,
+ commonName: dto.commonName as string,
+ certificateTtlDays: dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS,
+ hsmConnectorId: certificateInput.hsmConnectorId,
+ hsmKeyAlgorithm: certificateInput.hsmKeyAlgorithm
+ }
+ );
+ issuedCertificateId = certificateId;
+ } else {
+ const { certificateId } = await issueSignerCertificate(
+ {
+ certificateAuthorityDAL,
+ internalCertificateAuthorityService,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ projectDAL,
+ kmsService
+ },
+ {
+ caId: resolvedCaId,
+ projectId: dto.projectId,
+ commonName: dto.commonName as string,
+ certificateTtlDays: dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS,
+ keyAlgorithm
+ }
+ );
+ issuedCertificateId = certificateId;
+ }
}
const finalCertificateId = usingExistingCert ? (dto.certificateId as string) : issuedCertificateId;
@@ -551,13 +602,29 @@ export const signerServiceFactory = ({
if (usingCa && resolvedCaId && isExternalCa && resolvedCaType) {
try {
+ const certificateInput = dto.certificate;
await signerIssuanceService.requestIssuance({
signerId: result.id,
projectId: dto.projectId,
caId: resolvedCaId,
commonName: dto.commonName as string,
certificateTtlDays: dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS,
- keyAlgorithm
+ keyAlgorithm,
+ hsm:
+ certificateInput?.keySource === CertKeySource.Hsm &&
+ certificateInput.hsmConnectorId &&
+ certificateInput.hsmKeyAlgorithm
+ ? {
+ hsmConnectorId: certificateInput.hsmConnectorId,
+ hsmKeyAlgorithm: certificateInput.hsmKeyAlgorithm,
+ actor: {
+ type: dto.actor,
+ id: dto.actorId,
+ authMethod: dto.actorAuthMethod,
+ orgId: dto.actorOrgId
+ }
+ }
+ : undefined
});
} catch (queueErr) {
logger.error(
@@ -879,6 +946,24 @@ export const signerServiceFactory = ({
(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
+ }
+ }
+ : undefined;
await signerDAL.updateById(dto.signerId, {
status: SignerStatus.Pending,
certificateFailureReason: null
@@ -890,7 +975,8 @@ export const signerServiceFactory = ({
caId: dto.caId,
commonName: nextCommonName,
certificateTtlDays: nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS,
- keyAlgorithm: reissueKeyAlgorithm
+ keyAlgorithm: reissueKeyAlgorithm,
+ hsm: reissueHsm
});
return await signerDAL.findById(dto.signerId);
} catch (queueErr) {
@@ -906,23 +992,62 @@ export const signerServiceFactory = ({
}
try {
- const { certificateId } = await issueSignerCertificate(
- {
- certificateAuthorityDAL,
- internalCertificateAuthorityService,
- certificateBodyDAL,
- certificateSecretDAL,
- projectDAL,
- kmsService
- },
- {
- caId: dto.caId,
- projectId: signer.projectId,
- commonName: nextCommonName,
- certificateTtlDays: nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS,
- keyAlgorithm: reissueKeyAlgorithm
- }
- );
+ 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;
+ } else {
+ const result = await issueSignerCertificate(
+ {
+ certificateAuthorityDAL,
+ internalCertificateAuthorityService,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ projectDAL,
+ kmsService
+ },
+ {
+ caId: dto.caId,
+ projectId: signer.projectId,
+ commonName: nextCommonName,
+ certificateTtlDays: nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS,
+ keyAlgorithm: reissueKeyAlgorithm
+ }
+ );
+ certificateId = result.certificateId;
+ }
return await signerDAL.updateById(dto.signerId, {
certificateId,
@@ -1036,30 +1161,49 @@ export const signerServiceFactory = ({
const dataHash = crypto.nativeCrypto.createHash("sha256").update(dataBuffer).digest("hex");
- const { certPrivateKey } = await getCertificateCredentials({
- certId: signer.certificateId,
- projectId,
- certificateSecretDAL,
- projectDAL,
- kmsService
- });
+ const certificate = await certificateDAL.findById(signer.certificateId);
+ if (!certificate) {
+ throw new NotFoundError({ message: `Signer certificate ${signer.certificateId} not found` });
+ }
+ const isHsmBacked = certificate.keySource === CertKeySource.Hsm;
- const privateKeyObject = crypto.nativeCrypto.createPrivateKey({
- key: certPrivateKey,
- format: "pem",
- type: "pkcs8"
- });
+ let certPrivateKey: Buffer | undefined;
+ let keyAlgorithm: AsymmetricKeyAlgorithm;
+
+ if (isHsmBacked) {
+ if (!certificate.keyAlgorithm) {
+ throw new BadRequestError({
+ message: "HSM-backed certificate is missing keyAlgorithm; re-issue the certificate."
+ });
+ }
+ keyAlgorithm = certificate.keyAlgorithm as AsymmetricKeyAlgorithm;
+ } else {
+ const creds = await getCertificateCredentials({
+ certId: signer.certificateId,
+ projectId,
+ certificateSecretDAL,
+ projectDAL,
+ kmsService
+ });
+ certPrivateKey = Buffer.from(creds.certPrivateKey);
+ const privateKeyObject = crypto.nativeCrypto.createPrivateKey({
+ key: creds.certPrivateKey,
+ format: "pem",
+ type: "pkcs8"
+ });
+ keyAlgorithm = getKeyAlgorithmFamily(privateKeyObject);
+ }
- const keyAlgorithm = getKeyAlgorithmFamily(privateKeyObject);
validateSigningAlgorithmForKey(dto.signingAlgorithm, keyAlgorithm);
const requiresApproval = signer.approvalPolicyId ? (await $countPolicySteps(signer.approvalPolicyId)) > 0 : false;
- const result = await projectDAL.transaction(async (tx) => {
- let grantId: string | null = null;
- let matchedGrantAttrs: TCodeSigningGrantAttributes | null = null;
+ let grantId: string | null = null;
+ let matchedGrantAttrs: TCodeSigningGrantAttributes | null = null;
+ let pendingOperationId: string | null = null;
- if (requiresApproval) {
+ if (requiresApproval) {
+ ({ grantId, matchedGrantAttrs, pendingOperationId } = await projectDAL.transaction(async (tx) => {
const [userGrants, identityGrants] = await Promise.all([
approvalRequestGrantsDAL.find(
{
@@ -1140,22 +1284,61 @@ export const signerServiceFactory = ({
});
}
- grantId = matchingGrant.id;
- matchedGrantAttrs = matchingGrant.attributes as TCodeSigningGrantAttributes | null;
- }
+ const pendingOp = await signingOperationDAL.create(
+ {
+ signerId: dto.signerId,
+ projectId,
+ status: SigningOperationStatus.Pending,
+ signingAlgorithm: dto.signingAlgorithm,
+ dataHash,
+ actorType: dto.actor,
+ actorId: dto.actorId,
+ actorName: dto.actorName ?? null,
+ approvalGrantId: matchingGrant.id,
+ clientMetadata: dto.clientMetadata ?? null
+ },
+ tx
+ );
- let signatureBuffer: Buffer;
+ return {
+ grantId: matchingGrant.id,
+ matchedGrantAttrs: matchingGrant.attributes as TCodeSigningGrantAttributes | null,
+ pendingOperationId: pendingOp.id
+ };
+ }));
+ }
- try {
- const privateKeyPem = Buffer.from(certPrivateKey);
+ let signatureBuffer: Buffer;
+ try {
+ if (isHsmBacked) {
+ // ECDSA signatures arrive as raw r||s; convert to ASN.1 DER for X.509 / JCE consumers.
+ const mech = mapSigningAlgorithmToPkcs11Mechanism(dto.signingAlgorithm, dto.isDigest);
+ let raw = await hsmConnectorService.sign({
+ connectorId: certificate.hsmConnectorId as string,
+ projectId,
+ keyLabel: certificate.hsmKeyLabel as string,
+ mechanism: mech.mechanism,
+ data: dataBuffer,
+ isDigest: dto.isDigest
+ });
+ if (mech.isEcdsa) raw = ecdsaRawRsToDer(raw);
+ signatureBuffer = raw;
+ } else {
+ const privateKeyPem = certPrivateKey as Buffer;
const svc = signingService(keyAlgorithm);
signatureBuffer = await svc.sign(dataBuffer, privateKeyPem, dto.signingAlgorithm, dto.isDigest);
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : "Unknown signing error";
- logger.error(error, `Code signing failed for signer '${signer.name}'`);
-
- await signingOperationDAL.create(
- {
+ }
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : "Unknown signing error";
+ logger.error(error, `Code signing failed for signer '${signer.name}'`);
+ try {
+ if (pendingOperationId) {
+ await signingOperationDAL.updateById(pendingOperationId, {
+ status: SigningOperationStatus.Failed,
+ errorMessage: errorMessage.substring(0, 255)
+ });
+ } else {
+ await signingOperationDAL.create({
signerId: dto.signerId,
projectId,
status: SigningOperationStatus.Failed,
@@ -1167,29 +1350,35 @@ export const signerServiceFactory = ({
approvalGrantId: grantId,
clientMetadata: dto.clientMetadata ?? null,
errorMessage: errorMessage.substring(0, 255)
+ });
+ }
+ } catch (writeErr) {
+ logger.warn(writeErr, "Failed to record signing-operation failure row");
+ }
+ throw error;
+ }
+
+ await projectDAL.transaction(async (tx) => {
+ if (pendingOperationId) {
+ await signingOperationDAL.updateById(pendingOperationId, { status: SigningOperationStatus.Success }, tx);
+ } else {
+ await signingOperationDAL.create(
+ {
+ signerId: dto.signerId,
+ projectId,
+ status: SigningOperationStatus.Success,
+ signingAlgorithm: dto.signingAlgorithm,
+ dataHash,
+ actorType: dto.actor,
+ actorId: dto.actorId,
+ actorName: dto.actorName ?? null,
+ approvalGrantId: grantId,
+ clientMetadata: dto.clientMetadata ?? null
},
tx
);
-
- throw error;
}
- await signingOperationDAL.create(
- {
- signerId: dto.signerId,
- projectId,
- status: SigningOperationStatus.Success,
- signingAlgorithm: dto.signingAlgorithm,
- dataHash,
- actorType: dto.actor,
- actorId: dto.actorId,
- actorName: dto.actorName ?? null,
- approvalGrantId: grantId,
- clientMetadata: dto.clientMetadata ?? null
- },
- tx
- );
-
if (grantId && matchedGrantAttrs?.maxSignings) {
const newCount = await signingOperationDAL.countByGrantId(grantId, tx);
if (newCount >= matchedGrantAttrs.maxSignings) {
@@ -1198,17 +1387,15 @@ export const signerServiceFactory = ({
}
await signerDAL.updateById(dto.signerId, { lastSignedAt: new Date() }, tx);
-
- return {
- signature: signatureBuffer.toString("base64"),
- signingAlgorithm: dto.signingAlgorithm,
- signerId: dto.signerId,
- signerName: signer.name,
- projectId
- };
});
- return result;
+ return {
+ signature: signatureBuffer.toString("base64"),
+ signingAlgorithm: dto.signingAlgorithm,
+ signerId: dto.signerId,
+ signerName: signer.name,
+ projectId
+ };
};
const getPublicKey = async (dto: TGetPublicKeyDTO) => {
@@ -1371,6 +1558,16 @@ export const signerServiceFactory = ({
const renewKeyAlgorithm: CertKeyAlgorithm = (signer.keyAlgorithm as CertKeyAlgorithm) ?? CertKeyAlgorithm.RSA_2048;
if (isExternal) {
+ const autoRenewCert = signer.certificateId ? await certificateDAL.findById(signer.certificateId) : null;
+ const autoRenewHsm =
+ autoRenewCert?.keySource === CertKeySource.Hsm && autoRenewCert.hsmConnectorId && autoRenewCert.keyAlgorithm
+ ? {
+ hsmConnectorId: autoRenewCert.hsmConnectorId,
+ hsmKeyAlgorithm: mapCertKeyAlgorithmToHsmKeyAlgorithm(autoRenewCert.keyAlgorithm),
+ hsmKeyLabel: autoRenewCert.hsmKeyLabel ?? undefined,
+ hsmPublicKeySpki: autoRenewCert.hsmPublicKeySpki ?? undefined
+ }
+ : undefined;
await signerDAL.updateById(signer.id, {
status: SignerStatus.Pending,
certificateFailureReason: null
@@ -1382,7 +1579,8 @@ export const signerServiceFactory = ({
caId: signer.caId,
commonName: signer.commonName,
certificateTtlDays: ttlDays,
- keyAlgorithm: renewKeyAlgorithm
+ keyAlgorithm: renewKeyAlgorithm,
+ hsm: autoRenewHsm
});
} catch (err) {
await signerDAL.updateById(signer.id, {
@@ -1398,23 +1596,52 @@ export const signerServiceFactory = ({
}
try {
- const { certificateId } = await issueSignerCertificate(
- {
- certificateAuthorityDAL,
- internalCertificateAuthorityService,
- certificateBodyDAL,
- certificateSecretDAL,
- projectDAL,
- kmsService
- },
- {
- caId: signer.caId,
- projectId: signer.projectId,
- commonName: signer.commonName,
- certificateTtlDays: ttlDays,
- keyAlgorithm: renewKeyAlgorithm
- }
- );
+ const existingCert = signer.certificateId ? await certificateDAL.findById(signer.certificateId) : null;
+ const renewIsHsm = existingCert?.keySource === CertKeySource.Hsm;
+ let certificateId: string;
+ if (renewIsHsm && existingCert?.hsmConnectorId && existingCert.hsmKeyLabel && existingCert.keyAlgorithm) {
+ const result = await renewHsmBackedSignerCertificate(
+ {
+ certificateAuthorityDAL,
+ internalCertificateAuthorityService,
+ certificateBodyDAL,
+ certificateDAL,
+ hsmConnectorService,
+ projectDAL,
+ kmsService
+ },
+ {
+ caId: signer.caId,
+ projectId: signer.projectId,
+ commonName: signer.commonName,
+ certificateTtlDays: ttlDays,
+ hsmConnectorId: existingCert.hsmConnectorId,
+ hsmKeyLabel: existingCert.hsmKeyLabel,
+ expectedPublicKeySpkiDer: existingCert.hsmPublicKeySpki ?? undefined,
+ hsmKeyAlgorithm: mapCertKeyAlgorithmToHsmKeyAlgorithm(existingCert.keyAlgorithm)
+ }
+ );
+ certificateId = result.certificateId;
+ } else {
+ const result = await issueSignerCertificate(
+ {
+ certificateAuthorityDAL,
+ internalCertificateAuthorityService,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ projectDAL,
+ kmsService
+ },
+ {
+ caId: signer.caId,
+ projectId: signer.projectId,
+ commonName: signer.commonName,
+ certificateTtlDays: ttlDays,
+ keyAlgorithm: renewKeyAlgorithm
+ }
+ );
+ certificateId = result.certificateId;
+ }
await signerDAL.updateById(signer.id, {
certificateId,
status: SignerStatus.Active,
diff --git a/backend/src/services/signer/signer-types.ts b/backend/src/services/signer/signer-types.ts
index 1415d499b8..4bb1622569 100644
--- a/backend/src/services/signer/signer-types.ts
+++ b/backend/src/services/signer/signer-types.ts
@@ -2,7 +2,7 @@ import { SigningAlgorithm } from "@app/lib/crypto/sign/types";
import { TProjectPermission } from "@app/lib/types";
import { CertKeyAlgorithm } from "../certificate/certificate-types";
-import { SignerStatus, SigningOperationStatus } from "./signer-enums";
+import { CertKeySource, HsmKeyAlgorithm, SignerStatus, SigningOperationStatus } from "./signer-enums";
type TActorPermission = Omit<TProjectPermission, "projectId">;
@@ -17,6 +17,12 @@ export type TCreateSignerApprovalPolicyInput = {
constraints?: TSignerPolicyConstraints;
};
+export type TSignerCertificateInput = {
+ keySource?: CertKeySource;
+ hsmConnectorId?: string;
+ hsmKeyAlgorithm?: HsmKeyAlgorithm;
+};
+
export type TCreateSignerDTO = {
name: string;
description?: string;
@@ -29,6 +35,7 @@ export type TCreateSignerDTO = {
approvalPolicyId?: string;
members?: TCreateSignerMemberInput[];
approvalPolicy?: TCreateSignerApprovalPolicyInput;
+ certificate?: TSignerCertificateInput;
} & TProjectPermission;
export type TUpdateSignerDTO = {
diff --git a/backend/src/services/signer/signing-operation-dal.ts b/backend/src/services/signer/signing-operation-dal.ts
index 8ca12b9ce9..4bfba802e4 100644
--- a/backend/src/services/signer/signing-operation-dal.ts
+++ b/backend/src/services/signer/signing-operation-dal.ts
@@ -114,10 +114,17 @@ export const signingOperationDALFactory = (db: TDbClient) => {
}
};
+ const PENDING_RESERVATION_WINDOW_MS = 5 * 60 * 1000;
const countByGrantId = async (approvalGrantId: string, tx?: Knex) => {
try {
+ const cutoff = new Date(Date.now() - PENDING_RESERVATION_WINDOW_MS);
const [result] = await (tx || db)(TableName.PkiSigningOperations)
- .where({ approvalGrantId, status: SigningOperationStatus.Success })
+ .where({ approvalGrantId })
+ .andWhere((qb) => {
+ void qb.where({ status: SigningOperationStatus.Success }).orWhere((p) => {
+ void p.where({ status: SigningOperationStatus.Pending }).andWhere("createdAt", ">=", cutoff);
+ });
+ })
.count("* as count");
return Number((result as unknown as { count: string | number }).count);
} catch (error) {
diff --git a/docs/docs.json b/docs/docs.json
index 9abcb0e6ab..39ff11f777 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -896,7 +896,8 @@
"pages": [
"documentation/platform/pki/settings/policies",
"documentation/platform/pki/settings/profiles",
- "documentation/platform/pki/settings/certificate-cleanup"
+ "documentation/platform/pki/settings/certificate-cleanup",
+ "documentation/platform/pki/settings/hsm-connectors"
]
}
]
diff --git a/docs/documentation/platform/pki/code-signing/signers.mdx b/docs/documentation/platform/pki/code-signing/signers.mdx
index 43fde21d8a..43c76708de 100644
--- a/docs/documentation/platform/pki/code-signing/signers.mdx
+++ b/docs/documentation/platform/pki/code-signing/signers.mdx
@@ -63,8 +63,11 @@ 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). |
| **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`. |
+ | **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**. |
| **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. |
@@ -93,6 +96,19 @@ In **Certificate Manager → Code Signing → Signers**, click **Create Signer**
</Step>
</Steps>
+## HSM-backed Signers
+
+When you pick **Key source = HSM-backed** on the Certificate step, two extra fields appear:
+
+| 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`. |
+
+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.
+
## Signer statuses
| Status | Meaning |
@@ -135,7 +151,7 @@ Open the Signer and choose **Options → Edit settings**. The edit sheet walks y
To change any of them on an Active Signer: swap the CA (reissues with the new CN/Validity if you also fix those before going Active again) or, for **Key algorithm**, create a new Signer with the algorithm you want.
<Note>
- Renewals always issue a new certificate from the same CA with a fresh key pair. Old artifacts remain valid under the old certificate; new sign operations use the new one.
+ Renewals always issue a new certificate from the same CA with a fresh key pair. Old artifacts remain valid under the old certificate. New sign operations use the new one.
</Note>
Press **Save** to apply the changes.
@@ -157,15 +173,18 @@ To sign with a Signer, pick the integration that matches your tooling:
No. Every Signer has its own certificate. If you want different teams or different approval workflows against the same CA, create one Signer per team or workflow. Each gets its own certificate from that CA.
</Accordion>
<Accordion title="What's the difference between Disable and Delete?">
- **Disable** is reversible. The Signer, its members, its policy, its history, and the certificate are all preserved; sign calls just get rejected. Re-enable to resume.
+ **Disable** is reversible. The Signer, its members, its policy, its history, and the certificate are all preserved, and sign calls just get rejected. Re-enable to resume.
**Delete** is permanent. The Signer and everything attached to it (members, policy, access records, audit log) is removed. The certificate object remains in the inventory unless you delete that separately.
</Accordion>
<Accordion title="Why is my new Signer stuck in Pending?">
- External CAs (AWS Private CA, Azure AD CS) issue asynchronously. Infisical polls the CA in the background and flips the Signer to **Active** once the certificate is delivered. If it stays Pending for more than a few minutes, hover the badge; the failure reason appears there once the polling job gives up.
+ External CAs (AWS Private CA, Azure AD CS) issue asynchronously. Infisical polls the CA in the background and flips the Signer to **Active** once the certificate is delivered. If it stays Pending for more than a few minutes, hover the badge. The failure reason appears there once the polling job gives up.
</Accordion>
<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 doesn't invalidate past signatures.
+ 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>
</AccordionGroup>
@@ -175,6 +194,9 @@ To sign with a Signer, pick the integration that matches your tooling:
<Card title="Approvals" icon="check-double" href="/documentation/platform/pki/code-signing/approvals">
Add approval steps and per-approval limits to a Signer.
</Card>
+ <Card title="HSM Connectors" icon="shield-halved" href="/documentation/platform/pki/settings/hsm-connectors">
+ Route the Signer's key operations to your own HSM.
+ </Card>
<Card title="PKCS#11 Module" icon="plug" href="/documentation/platform/pki/code-signing/pkcs11-module">
Use jarsigner, cosign, osslsigncode, and friends with this Signer.
</Card>
diff --git a/docs/documentation/platform/pki/settings/hsm-connectors.mdx b/docs/documentation/platform/pki/settings/hsm-connectors.mdx
new file mode 100644
index 0000000000..ecd9e5076d
--- /dev/null
+++ b/docs/documentation/platform/pki/settings/hsm-connectors.mdx
@@ -0,0 +1,157 @@
+---
+title: "HSM Connectors"
+sidebarTitle: "HSM Connectors"
+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.
+
+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.
+
+## How it fits together
+
+```mermaid
+sequenceDiagram
+ participant Caller as Caller<br/>
+ participant Infisical as Infisical
+ participant Gateway as Gateway<br/>(--pkcs11-module)
+ participant HSM as Your HSM<br/>
+
+ Caller->>Infisical: Operation that uses an HSM Connector
+ Infisical->>Gateway: PKCS#11 request
+ Gateway->>HSM: C_* call via vendor driver
+ HSM-->>Gateway: Result
+ Gateway-->>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>`.
+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.
+
+<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.
+
+ 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.
+
+ 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).
+ </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.
+
+ <Tabs>
+ <Tab title="Linux (Production)">
+ ```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>
+ ```
+
+ The systemd unit captures the `--pkcs11-module` flag, so restarts pick up the same driver.
+ </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>
+
+ 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.
+ </Step>
+
+ <Step title="(Optional) Add the Gateway to a Pool">
+ For high availability, deploy two or more PKCS#11-enabled Gateways and add them to the same [Gateway Pool](/documentation/platform/gateways/gateway-pools). HSM Connectors that target the pool route each request to a randomly chosen, healthy, PKCS#11-capable member. Non-capable members in the same pool are silently skipped.
+ </Step>
+</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.
+</Note>
+
+## Create an HSM Connector
+
+Once you have a PKCS#11-enabled Gateway running and heartbeating, create the Connector in Cert Manager.
+
+In **Certificate Manager > Settings > HSM Connectors**, click **Add HSM Connector**. The wizard walks you through three steps.
+
+<Steps>
+ <Step title="Basics">
+ | Field | Description |
+ |-------|-------------|
+ | **Name** | Slug-friendly identifier (lowercase, dashes). Example: `fortanix-prod`. |
+ | **Description** | Optional. Context for your team. Example: *Fortanix DSM, production keys*. |
+ </Step>
+
+ <Step title="Reached from">
+ Pick how Infisical reaches 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.
+
+ 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`.
+ </Step>
+
+ <Step title="Access">
+ Supply the credentials Infisical uses to authenticate to the HSM slot through the Gateway.
+
+ | Field | Description |
+ |-------|-------------|
+ | **Slot label** | The PKCS#11 token label of the slot to use. For example, `Fortanix Token`. Find it with `pkcs11-tool --module <driver> --list-slots`. |
+ | **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.
+ </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>
+ <Accordion title="What happens to keys on the HSM when I delete a referencing resource?">
+ Nothing. Infisical removes its reference to the key label. The actual key object remains on your HSM. Delete it through your HSM's own tooling if you want to free the slot.
+ </Accordion>
+ <Accordion title="Can I route HSM traffic through the same Gateway that serves my databases or app connections?">
+ Yes. Append `--pkcs11-module` to the start command of an existing Gateway and that Gateway will serve HSM operations alongside its other traffic. Restart is required for the driver to load.
+ </Accordion>
+ <Accordion title="Does a Gateway Pool need every member to be PKCS#11-capable?">
+ No. 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`.
+ </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.
+ </Accordion>
+</AccordionGroup>
+
+## What's next?
+
+<CardGroup cols={2}>
+ <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.
+ </Card>
+</CardGroup>
diff --git a/frontend/src/const/routes.ts b/frontend/src/const/routes.ts
index c328f65da0..49c32b2cc7 100644
--- a/frontend/src/const/routes.ts
+++ b/frontend/src/const/routes.ts
@@ -343,6 +343,10 @@ export const ROUTE_PATHS = Object.freeze({
"/organizations/$orgId/projects/cert-manager/$projectId/certificate-policies/$policyId",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificate-policies/$policyId"
),
+ HsmConnectorDetailsByIDPage: setRoute(
+ "/organizations/$orgId/projects/cert-manager/$projectId/hsm-connectors/$connectorId",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/hsm-connectors/$connectorId"
+ ),
SubscribersPage: setRoute(
"/organizations/$orgId/projects/cert-manager/$projectId/subscribers",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/subscribers"
diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.ts
index 7aecff4d37..36a9d58279 100644
--- a/frontend/src/context/ProjectPermissionContext/types.ts
+++ b/frontend/src/context/ProjectPermissionContext/types.ts
@@ -241,6 +241,15 @@ export enum ProjectPermissionAppConnectionActions {
RotateCredentials = "rotate-credentials"
}
+export enum ProjectPermissionHsmConnectorActions {
+ Read = "read-hsm-connectors",
+ Create = "create-hsm-connectors",
+ Edit = "edit-hsm-connectors",
+ Delete = "delete-hsm-connectors",
+ Test = "test-hsm-connectors",
+ Attach = "attach-hsm-connectors"
+}
+
export enum PermissionConditionOperators {
$IN = "$in",
$ALL = "$all",
@@ -452,6 +461,7 @@ export enum ProjectPermissionSub {
SecretScanningConfigs = "secret-scanning-configs",
SecretEventSubscriptions = "secret-event-subscriptions",
AppConnections = "app-connections",
+ HsmConnectors = "hsm-connectors",
PamFolders = "pam-folders",
PamResources = "pam-resources",
PamDomains = "pam-domains",
@@ -739,6 +749,7 @@ export type ProjectPermissionSet =
| (ForcedSubject<ProjectPermissionSub.AppConnections> & AppConnectionSubjectFields)
)
]
+ | [ProjectPermissionHsmConnectorActions, ProjectPermissionSub.HsmConnectors]
| [ProjectPermissionActions, ProjectPermissionSub.PamFolders]
| [
ProjectPermissionActions,
diff --git a/frontend/src/hooks/api/gateways-v2/types.ts b/frontend/src/hooks/api/gateways-v2/types.ts
index 797b376242..50fcc5c575 100644
--- a/frontend/src/hooks/api/gateways-v2/types.ts
+++ b/frontend/src/hooks/api/gateways-v2/types.ts
@@ -12,6 +12,7 @@ export type TGatewayV2 = {
name: string;
id: string;
} | null;
+ capabilities?: Record<string, unknown>;
};
export type GatewayAwsAuthConfig = {
diff --git a/frontend/src/hooks/api/gateways/types.ts b/frontend/src/hooks/api/gateways/types.ts
index 6a3f2d673d..29f6441528 100644
--- a/frontend/src/hooks/api/gateways/types.ts
+++ b/frontend/src/hooks/api/gateways/types.ts
@@ -11,6 +11,8 @@ export type TGateway = {
name: string;
id: string;
};
+ isV1?: boolean;
+ capabilities?: Record<string, unknown>;
};
export type TUpdateGatewayDTO = {
diff --git a/frontend/src/hooks/api/hsmConnectors/index.ts b/frontend/src/hooks/api/hsmConnectors/index.ts
new file mode 100644
index 0000000000..177955438b
--- /dev/null
+++ b/frontend/src/hooks/api/hsmConnectors/index.ts
@@ -0,0 +1,3 @@
+export * from "./mutations";
+export * from "./queries";
+export * from "./types";
diff --git a/frontend/src/hooks/api/hsmConnectors/mutations.tsx b/frontend/src/hooks/api/hsmConnectors/mutations.tsx
new file mode 100644
index 0000000000..8c81c4f13b
--- /dev/null
+++ b/frontend/src/hooks/api/hsmConnectors/mutations.tsx
@@ -0,0 +1,73 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { hsmConnectorKeys } from "./queries";
+import {
+ TCreateHsmConnectorPayload,
+ THsmConnector,
+ THsmConnectorTestResult,
+ TUpdateHsmConnectorPayload
+} from "./types";
+
+export const useCreateHsmConnector = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async (payload: TCreateHsmConnectorPayload) => {
+ const { data } = await apiRequest.post<{ hsmConnector: THsmConnector }>(
+ "/api/v1/cert-manager/hsm-connectors",
+ payload
+ );
+ return data.hsmConnector;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: hsmConnectorKeys.list() });
+ }
+ });
+};
+
+export const useUpdateHsmConnector = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ connectorId, ...patch }: TUpdateHsmConnectorPayload) => {
+ const { data } = await apiRequest.patch<{ hsmConnector: THsmConnector }>(
+ `/api/v1/cert-manager/hsm-connectors/${connectorId}`,
+ patch
+ );
+ return data.hsmConnector;
+ },
+ onSuccess: (_data, variables) => {
+ queryClient.invalidateQueries({ queryKey: hsmConnectorKeys.list() });
+ queryClient.invalidateQueries({ queryKey: hsmConnectorKeys.byId(variables.connectorId) });
+ queryClient.invalidateQueries({
+ queryKey: hsmConnectorKeys.linkedCertificatesAll(variables.connectorId)
+ });
+ }
+ });
+};
+
+export const useDeleteHsmConnector = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ connectorId }: { connectorId: string }) => {
+ const { data } = await apiRequest.delete<{ id: string }>(
+ `/api/v1/cert-manager/hsm-connectors/${connectorId}`
+ );
+ return data;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: hsmConnectorKeys.all });
+ }
+ });
+};
+
+export const useTestHsmConnector = () => {
+ return useMutation({
+ mutationFn: async ({ connectorId }: { connectorId: string }) => {
+ const { data } = await apiRequest.post<THsmConnectorTestResult>(
+ `/api/v1/cert-manager/hsm-connectors/${connectorId}/test`
+ );
+ return data;
+ }
+ });
+};
diff --git a/frontend/src/hooks/api/hsmConnectors/queries.tsx b/frontend/src/hooks/api/hsmConnectors/queries.tsx
new file mode 100644
index 0000000000..ea1a0aeecb
--- /dev/null
+++ b/frontend/src/hooks/api/hsmConnectors/queries.tsx
@@ -0,0 +1,77 @@
+import { useQuery, UseQueryOptions } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { THsmConnector, THsmConnectorLinkedCertificate } from "./types";
+
+export const hsmConnectorKeys = {
+ all: ["hsm-connectors"] as const,
+ list: () => [...hsmConnectorKeys.all, "list"] 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
+};
+
+export const useListHsmConnectors = (
+ options?: Omit<UseQueryOptions<THsmConnector[]>, "queryKey" | "queryFn">
+) => {
+ return useQuery({
+ queryKey: hsmConnectorKeys.list(),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ hsmConnectors: THsmConnector[] }>(
+ "/api/v1/cert-manager/hsm-connectors"
+ );
+ return data.hsmConnectors;
+ },
+ ...options
+ });
+};
+
+export const useGetHsmConnectorById = (
+ connectorId: string | undefined,
+ options?: Omit<UseQueryOptions<THsmConnector>, "queryKey" | "queryFn">
+) => {
+ return useQuery({
+ ...options,
+ queryKey: hsmConnectorKeys.byId(connectorId ?? ""),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ hsmConnector: THsmConnector }>(
+ `/api/v1/cert-manager/hsm-connectors/${connectorId}`
+ );
+ return data.hsmConnector;
+ },
+ enabled: Boolean(connectorId) && (options?.enabled ?? true)
+ });
+};
+
+export const useListHsmConnectorLinkedCertificates = (
+ connectorId: string | undefined,
+ pagination?: { offset?: number; limit?: number },
+ options?: Omit<
+ UseQueryOptions<{ linkedCertificates: THsmConnectorLinkedCertificate[]; totalCount: number }>,
+ "queryKey" | "queryFn"
+ >
+) => {
+ const { offset = 0, limit = 20 } = pagination || {};
+
+ return useQuery({
+ ...options,
+ queryKey: hsmConnectorKeys.linkedCertificates(connectorId ?? "", { offset, limit }),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{
+ linkedCertificates: THsmConnectorLinkedCertificate[];
+ totalCount: number;
+ }>(`/api/v1/cert-manager/hsm-connectors/${connectorId}/linked-certificates`, {
+ params: { offset, limit }
+ });
+ return {
+ linkedCertificates: data.linkedCertificates ?? [],
+ totalCount: data.totalCount ?? 0
+ };
+ },
+ placeholderData: (prev) => prev,
+ enabled: Boolean(connectorId) && (options?.enabled ?? true)
+ });
+};
diff --git a/frontend/src/hooks/api/hsmConnectors/types.ts b/frontend/src/hooks/api/hsmConnectors/types.ts
new file mode 100644
index 0000000000..327b6b5110
--- /dev/null
+++ b/frontend/src/hooks/api/hsmConnectors/types.ts
@@ -0,0 +1,66 @@
+import { CertStatus } from "@app/hooks/api/certificates/enums";
+
+export type THsmConnector = {
+ id: string;
+ name: string;
+ description: string | null;
+ projectId: string;
+ gatewayId: string | null;
+ gatewayPoolId: string | null;
+ slotLabel: string;
+ keyNamePrefix: string | null;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type TCreateHsmConnectorPayload = {
+ name: string;
+ description?: string;
+ gatewayId?: string;
+ gatewayPoolId?: string;
+ credentials: {
+ slotLabel: string;
+ pin: string;
+ keyNamePrefix?: string;
+ };
+};
+
+export type TUpdateHsmConnectorPayload = {
+ connectorId: string;
+ name?: string;
+ description?: string;
+ gatewayId?: string;
+ gatewayPoolId?: string;
+ credentials?: {
+ slotLabel?: string;
+ pin?: string;
+ keyNamePrefix?: string;
+ };
+};
+
+export type THsmConnectorTestMemberResult =
+ | {
+ gatewayId: string;
+ ok: true;
+ slotInfo: { manufacturer: string; model: string; firmware: string };
+ }
+ | {
+ gatewayId: string;
+ ok: false;
+ errorCode: string;
+ errorMessage: string;
+ };
+
+export type THsmConnectorTestResult = {
+ ok: boolean;
+ members: THsmConnectorTestMemberResult[];
+};
+
+export type THsmConnectorLinkedCertificate = {
+ id: string;
+ commonName: string;
+ status: CertStatus;
+ notAfter: string;
+ hsmKeyLabel: string | null;
+ createdAt: string;
+};
diff --git a/frontend/src/hooks/api/signers/types.ts b/frontend/src/hooks/api/signers/types.ts
index e871dc3af8..f570e8038a 100644
--- a/frontend/src/hooks/api/signers/types.ts
+++ b/frontend/src/hooks/api/signers/types.ts
@@ -19,6 +19,18 @@ export enum SignerKeyAlgorithm {
ECDSA_P521 = "EC_secp521r1"
}
+export enum CertKeySource {
+ Infisical = "infisical",
+ Hsm = "hsm"
+}
+
+export enum HsmKeyAlgorithm {
+ RSA_2048 = "RSA_2048",
+ RSA_4096 = "RSA_4096",
+ ECC_P256 = "ECC_P256",
+ ECC_P384 = "ECC_P384"
+}
+
export const signerKeyAlgorithmLabels: Record<SignerKeyAlgorithm, string> = {
[SignerKeyAlgorithm.RSA_2048]: "RSA-2048",
[SignerKeyAlgorithm.RSA_3072]: "RSA-3072",
@@ -54,12 +66,14 @@ export const getSignerStatusBadgeVariant = (status: SignerStatus) => {
};
export enum SigningOperationStatus {
+ Pending = "pending",
Success = "success",
Failed = "failed",
Denied = "denied"
}
export const signingOperationStatusLabels: Record<SigningOperationStatus, string> = {
+ [SigningOperationStatus.Pending]: "Pending",
[SigningOperationStatus.Success]: "Success",
[SigningOperationStatus.Failed]: "Failed",
[SigningOperationStatus.Denied]: "Denied"
@@ -230,6 +244,12 @@ export type TCreateSignerApprovalPolicyInput = {
constraints?: { maxSignings?: number | null; maxWindowDuration?: string | null };
};
+export type TSignerCertificateInput = {
+ keySource?: CertKeySource;
+ hsmConnectorId?: string;
+ hsmKeyAlgorithm?: HsmKeyAlgorithm;
+};
+
export type TCreateSignerDTO = {
projectId: string;
name: string;
@@ -243,6 +263,7 @@ export type TCreateSignerDTO = {
approvalPolicyId?: string;
members?: TCreateSignerMemberInput[];
approvalPolicy?: TCreateSignerApprovalPolicyInput;
+ certificate?: TSignerCertificateInput;
};
export type TUpdateSignerDTO = {
diff --git a/frontend/src/hooks/api/subscriptions/types.ts b/frontend/src/hooks/api/subscriptions/types.ts
index 4d73a7d354..a8d0b15e78 100644
--- a/frontend/src/hooks/api/subscriptions/types.ts
+++ b/frontend/src/hooks/api/subscriptions/types.ts
@@ -63,6 +63,7 @@ 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/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
index 214d0cad9a..5d1e096d78 100644
--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
@@ -70,7 +70,10 @@ const Page = () => {
from: ROUTE_PATHS.CertManager.CertificateDetailsByIDPage.id
});
const { certificateId } = params as { certificateId: string };
- const { fromApplication } = useSearch({ strict: false }) as { fromApplication?: string };
+ const { fromApplication, fromHsmConnector } = useSearch({ strict: false }) as {
+ fromApplication?: string;
+ fromHsmConnector?: string;
+ };
const { data: certificateData, isLoading } = useGetCertificateById(certificateId);
const certificate = certificateData?.certificate;
const isInventoryView = !fromApplication;
@@ -265,7 +268,7 @@ const Page = () => {
} else {
pageBody = (
<div className="mx-auto mb-6 w-full max-w-8xl">
- {fromApplication ? (
+ {fromApplication && (
<Link
to="/organizations/$orgId/projects/cert-manager/$projectId/applications/$applicationName"
params={{
@@ -279,7 +282,22 @@ const Page = () => {
<ChevronLeftIcon size={16} />
Go back to Application
</Link>
- ) : (
+ )}
+ {!fromApplication && fromHsmConnector && (
+ <Link
+ to="/organizations/$orgId/projects/cert-manager/$projectId/hsm-connectors/$connectorId"
+ params={{
+ orgId: currentOrg.id,
+ projectId,
+ connectorId: fromHsmConnector
+ }}
+ className="mb-4 flex w-fit items-center gap-x-1 text-sm text-mineshaft-400 transition duration-100 hover:text-mineshaft-400/80"
+ >
+ <ChevronLeftIcon size={16} />
+ HSM Connector
+ </Link>
+ )}
+ {!fromApplication && !fromHsmConnector && (
<Link
to="/organizations/$orgId/projects/cert-manager/$projectId/inventory"
params={{
diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/route.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/route.tsx
index 90ecc9209f..a6944f9e94 100644
--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/route.tsx
+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/route.tsx
@@ -5,7 +5,8 @@ import { z } from "zod";
import { CertificateDetailsByIDPage } from "./CertificateDetailsByIDPage";
const CertificateDetailsByIDPageQuerySchema = z.object({
- fromApplication: z.string().optional()
+ fromApplication: z.string().optional(),
+ fromHsmConnector: z.string().uuid().optional()
});
export const Route = createFileRoute(
diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx
index 6807bc66ae..5cbc624c4c 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx
@@ -2,6 +2,7 @@ import { Controller, useForm } from "react-hook-form";
import { Link, useParams } from "@tanstack/react-router";
import {
+ Badge,
Field,
FieldContent,
FieldDescription,
@@ -17,22 +18,61 @@ import {
SelectValue
} from "@app/components/v3";
import { ROUTE_PATHS } from "@app/const/routes";
-import { SignerKeyAlgorithm, signerKeyAlgorithmLabels } from "@app/hooks/api/signers";
+import { useProjectPermission, useSubscription } from "@app/context";
+import {
+ ProjectPermissionHsmConnectorActions,
+ ProjectPermissionSub
+} from "@app/context/ProjectPermissionContext/types";
+import {
+ CertKeySource,
+ HsmKeyAlgorithm,
+ SignerKeyAlgorithm,
+ signerKeyAlgorithmLabels
+} from "@app/hooks/api/signers";
import { CertificateForm } from "./schemas";
import { CaGroup, CaOption } from "./types";
+const HSM_KEY_ALGORITHM_LABELS: Record<HsmKeyAlgorithm, string> = {
+ [HsmKeyAlgorithm.RSA_2048]: "RSA 2048",
+ [HsmKeyAlgorithm.RSA_4096]: "RSA 4096",
+ [HsmKeyAlgorithm.ECC_P256]: "ECDSA P-256",
+ [HsmKeyAlgorithm.ECC_P384]: "ECDSA P-384"
+};
+
+export type HsmConnectorOption = { id: string; name: string; slotLabel: string };
+
type CertificateStepProps = {
form: ReturnType<typeof useForm<CertificateForm>>;
caOptions: CaOption[];
isCasLoading: boolean;
+ hsmConnectorOptions: HsmConnectorOption[];
+ isHsmConnectorsLoading: boolean;
};
-export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateStepProps) => {
+export const CertificateStep = ({
+ form,
+ caOptions,
+ isCasLoading,
+ hsmConnectorOptions,
+ isHsmConnectorsLoading
+}: CertificateStepProps) => {
const { orgId, projectId } = useParams({ strict: false }) as {
orgId?: string;
projectId?: string;
};
+
+ const { subscription } = useSubscription();
+ const isHsmLicensed = Boolean(subscription?.pkiHsm);
+ const { permission } = useProjectPermission();
+ const canAttachHsm = permission.can(
+ ProjectPermissionHsmConnectorActions.Attach,
+ ProjectPermissionSub.HsmConnectors
+ );
+
+ const keySource = form.watch("keySource");
+ const isHsm = keySource === CertKeySource.Hsm;
+
return (
<FieldGroup>
<Controller
@@ -101,36 +141,145 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateSt
</Field>
)}
/>
+
<Controller
- name="keyAlgorithm"
+ name="keySource"
control={form.control}
- render={({ field, fieldState: { error } }) => (
+ render={({ field }) => (
<Field>
<FieldLabel>
- Key algorithm <span className="text-danger">*</span>
+ Key source <span className="text-danger">*</span>
</FieldLabel>
<FieldContent>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
- <SelectContent>
- {Object.values(SignerKeyAlgorithm).map((value) => (
- <SelectItem key={value} value={value}>
- {signerKeyAlgorithmLabels[value]}
- </SelectItem>
- ))}
+ <SelectContent position="popper">
+ <SelectItem value={CertKeySource.Infisical}>Infisical-managed key</SelectItem>
+ <SelectItem value={CertKeySource.Hsm} disabled={!isHsmLicensed || !canAttachHsm}>
+ <div className="flex items-center gap-2">
+ HSM-backed key
+ {!isHsmLicensed && <Badge variant="info">Enterprise</Badge>}
+ {isHsmLicensed && !canAttachHsm && (
+ <Badge variant="warning">Permission required</Badge>
+ )}
+ </div>
+ </SelectItem>
</SelectContent>
</Select>
<FieldDescription>
- Algorithm used to generate the signer&apos;s private key. RSA is widely compatible,
- ECDSA produces smaller signatures and is faster.
+ {field.value === CertKeySource.Hsm
+ ? "The keypair is generated on a Hardware Security Module and every signature is performed there."
+ : "Infisical generates and manages the keypair for you."}
</FieldDescription>
- <FieldError errors={[error]} />
</FieldContent>
</Field>
)}
/>
+
+ {!isHsm && (
+ <Controller
+ name="keyAlgorithm"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Key algorithm <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {Object.values(SignerKeyAlgorithm).map((value) => (
+ <SelectItem key={value} value={value}>
+ {signerKeyAlgorithmLabels[value]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ Algorithm used to generate the signer&apos;s private key. RSA is widely
+ compatible, ECDSA produces smaller signatures and is faster.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ )}
+
+ {isHsm && (
+ <>
+ <Controller
+ name="hsmConnectorId"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ HSM Connector <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <FilterableSelect<HsmConnectorOption>
+ isLoading={isHsmConnectorsLoading}
+ options={hsmConnectorOptions}
+ value={hsmConnectorOptions.find((o) => o.id === field.value) ?? null}
+ onChange={(selected) => {
+ const opt = selected as HsmConnectorOption | null;
+ field.onChange(opt?.id ?? null);
+ }}
+ getOptionLabel={(opt) => `${opt.name} (slot ${opt.slotLabel})`}
+ getOptionValue={(opt) => opt.id}
+ placeholder="Select an HSM Connector..."
+ noOptionsMessage={() =>
+ hsmConnectorOptions.length === 0
+ ? "No HSM Connectors configured. Add one in Cert Manager Settings → HSM Connectors."
+ : "No match."
+ }
+ isError={Boolean(error)}
+ />
+ <FieldDescription>
+ The HSM on which Infisical will generate the signing key.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ name="hsmKeyAlgorithm"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ HSM key algorithm <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {Object.values(HsmKeyAlgorithm).map((value) => (
+ <SelectItem key={value} value={value}>
+ {HSM_KEY_ALGORITHM_LABELS[value]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ Algorithm the HSM will generate for this signer&apos;s keypair.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ </>
+ )}
+
<Controller
name="certificateTtlDays"
control={form.control}
diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx
index adcd05c1b6..b2bc737fc1 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx
@@ -15,13 +15,20 @@ import {
StepperList,
StepperStep
} from "@app/components/v3";
-import { useOrganization, useUser } from "@app/context";
+import { useOrganization, useSubscription, useUser } from "@app/context";
import { useListCasByProjectId } from "@app/hooks/api/ca";
import { CaStatus, CaType } from "@app/hooks/api/ca/enums";
+import { useListHsmConnectors } from "@app/hooks/api/hsmConnectors";
import { useGetOrganizationGroups } from "@app/hooks/api/organization";
import { useListProjectIdentityMemberships } from "@app/hooks/api/projectIdentityMembership";
import { ProjectType } from "@app/hooks/api/projects/types";
-import { SignerKeyAlgorithm, SignerMemberRole, useCreateSigner } from "@app/hooks/api/signers";
+import {
+ CertKeySource,
+ HsmKeyAlgorithm,
+ SignerKeyAlgorithm,
+ SignerMemberRole,
+ useCreateSigner
+} from "@app/hooks/api/signers";
import { useGetOrgUsers } from "@app/hooks/api/users";
import { PkiDocsUrls } from "../../../pki-docs-urls";
@@ -61,6 +68,10 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
limit: 1000
});
const groupsQuery = useGetOrganizationGroups(orgId);
+ const { subscription } = useSubscription();
+ const { data: hsmConnectors = [], isPending: isHsmConnectorsLoading } = useListHsmConnectors({
+ enabled: Boolean(subscription?.pkiHsm)
+ });
const createSigner = useCreateSigner();
@@ -103,6 +114,16 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
return groups.map((g) => ({ value: g.id, label: g.name }));
}, [groupsQuery.data]);
+ const hsmConnectorOptions = useMemo(
+ () =>
+ hsmConnectors.map((c) => ({
+ id: c.id,
+ name: c.name,
+ slotLabel: c.slotLabel
+ })),
+ [hsmConnectors]
+ );
+
const basicsForm = useForm<BasicsForm>({
resolver: zodResolver(basicsSchema),
values: { name: state.name, description: state.description || undefined }
@@ -115,7 +136,10 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
commonName: state.commonName,
certificateTtlDays: state.certificateTtlDays,
certificateRenewBeforeDays: state.certificateRenewBeforeDays,
- keyAlgorithm: state.keyAlgorithm
+ keyAlgorithm: state.keyAlgorithm,
+ keySource: state.keySource,
+ hsmConnectorId: state.hsmConnectorId,
+ hsmKeyAlgorithm: state.hsmKeyAlgorithm
}
});
@@ -128,7 +152,10 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
commonName: "",
certificateTtlDays: 365,
certificateRenewBeforeDays: null,
- keyAlgorithm: SignerKeyAlgorithm.RSA_2048
+ keyAlgorithm: SignerKeyAlgorithm.RSA_2048,
+ keySource: CertKeySource.Infisical,
+ hsmConnectorId: null,
+ hsmKeyAlgorithm: HsmKeyAlgorithm.RSA_2048
});
};
@@ -157,6 +184,15 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
}
: undefined;
+ const certificate =
+ state.keySource === CertKeySource.Hsm && state.hsmConnectorId
+ ? {
+ keySource: CertKeySource.Hsm,
+ hsmConnectorId: state.hsmConnectorId,
+ hsmKeyAlgorithm: state.hsmKeyAlgorithm
+ }
+ : undefined;
+
await createSigner.mutateAsync({
projectId,
name: state.name,
@@ -171,7 +207,8 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
id: m.id,
role: m.role
})),
- approvalPolicy
+ approvalPolicy,
+ certificate
});
handleClose(false);
@@ -185,6 +222,8 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
}
};
+ const isLast = step === STEPS.length - 1;
+
const goNext = async () => {
if (step === 0) {
const ok = await basicsForm.trigger();
@@ -204,7 +243,10 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
commonName: values.commonName,
certificateTtlDays: values.certificateTtlDays,
certificateRenewBeforeDays: values.certificateRenewBeforeDays,
- keyAlgorithm: values.keyAlgorithm
+ keyAlgorithm: values.keyAlgorithm,
+ keySource: values.keySource,
+ hsmConnectorId: values.hsmConnectorId ?? null,
+ hsmKeyAlgorithm: values.hsmKeyAlgorithm
}));
setStep(2);
return;
@@ -230,7 +272,6 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
state.policySteps.length > 0;
const currentStep = STEPS[step];
- const isLast = step === STEPS.length - 1;
const ctaLabel = isLast ? "Create Signer" : "Continue";
const firstEmptyPolicyStepIndex = state.policySteps.findIndex(
(s) => s.approverUserIds.length + s.approverGroupIds.length === 0
@@ -246,7 +287,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
<SheetHeader className="border-b">
<SheetTitle>
<div className="flex w-full items-start gap-2">
- <div className="flex h-10 w-10 items-center justify-center rounded-md bg-warning/10 text-warning">
+ <div className="flex h-10 w-10 items-center justify-center rounded-md bg-project/10 text-project">
<ShieldIcon className="h-5 w-5" />
</div>
<div>
@@ -301,6 +342,8 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
form={certificateForm}
caOptions={caOptions}
isCasLoading={cas.isPending}
+ hsmConnectorOptions={hsmConnectorOptions}
+ isHsmConnectorsLoading={isHsmConnectorsLoading}
/>
)}
{step === 2 && (
diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts
index 9f5b6b1785..35612bc788 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-import { SignerKeyAlgorithm } from "@app/hooks/api/signers";
+import { CertKeySource, HsmKeyAlgorithm, SignerKeyAlgorithm } from "@app/hooks/api/signers";
import { slugSchema } from "@app/lib/schemas";
export const basicsSchema = z.object({
@@ -31,7 +31,10 @@ export const certificateSchema = z
])
)
.default(null),
- keyAlgorithm: z.nativeEnum(SignerKeyAlgorithm).default(SignerKeyAlgorithm.RSA_2048)
+ keyAlgorithm: z.nativeEnum(SignerKeyAlgorithm).default(SignerKeyAlgorithm.RSA_2048),
+ keySource: z.nativeEnum(CertKeySource).default(CertKeySource.Infisical),
+ hsmConnectorId: z.string().uuid().optional().nullable(),
+ hsmKeyAlgorithm: z.nativeEnum(HsmKeyAlgorithm).default(HsmKeyAlgorithm.RSA_2048)
})
.refine(
(data) =>
@@ -41,5 +44,9 @@ export const certificateSchema = z
message: "Renew before must be less than the certificate validity (days).",
path: ["certificateRenewBeforeDays"]
}
- );
+ )
+ .refine((data) => data.keySource !== CertKeySource.Hsm || Boolean(data.hsmConnectorId), {
+ message: "Pick an HSM Connector.",
+ path: ["hsmConnectorId"]
+ });
export type CertificateForm = z.infer<typeof certificateSchema>;
diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts
index 4bf7bf16d5..92c3901516 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts
@@ -1,4 +1,9 @@
-import { SignerKeyAlgorithm, SignerMemberRole } from "@app/hooks/api/signers";
+import {
+ CertKeySource,
+ HsmKeyAlgorithm,
+ SignerKeyAlgorithm,
+ SignerMemberRole
+} from "@app/hooks/api/signers";
import { PkiDocsUrls } from "../../../pki-docs-urls";
@@ -41,6 +46,9 @@ export type WizardState = {
certificateTtlDays: number;
certificateRenewBeforeDays: number | null;
keyAlgorithm: SignerKeyAlgorithm;
+ keySource: CertKeySource;
+ hsmConnectorId: string | null;
+ hsmKeyAlgorithm: HsmKeyAlgorithm;
pendingMembers: PendingMember[];
policySteps: PolicyStep[];
maxSignings: number | null;
@@ -55,6 +63,9 @@ export const INITIAL_WIZARD_STATE: WizardState = {
certificateTtlDays: 365,
certificateRenewBeforeDays: null,
keyAlgorithm: SignerKeyAlgorithm.RSA_2048,
+ keySource: CertKeySource.Infisical,
+ hsmConnectorId: null,
+ hsmKeyAlgorithm: HsmKeyAlgorithm.RSA_2048,
pendingMembers: [],
policySteps: [],
maxSignings: null,
@@ -89,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.",
+ "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).",
docsUrl: PkiDocsUrls.codeSigning.signers.certificate
},
{
diff --git a/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/HsmConnectorDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/HsmConnectorDetailsByIDPage.tsx
new file mode 100644
index 0000000000..6f896f88e2
--- /dev/null
+++ b/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/HsmConnectorDetailsByIDPage.tsx
@@ -0,0 +1,143 @@
+import { useState } from "react";
+import { Helmet } from "react-helmet";
+import { Link, useNavigate, useParams } from "@tanstack/react-router";
+import { ChevronLeftIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { ProjectPermissionCan } from "@app/components/permissions";
+import { AccessRestrictedBanner, PageHeader } from "@app/components/v2";
+import { ROUTE_PATHS } from "@app/const/routes";
+import { useOrganization, useProject } from "@app/context";
+import {
+ ProjectPermissionHsmConnectorActions,
+ ProjectPermissionSub
+} from "@app/context/ProjectPermissionContext/types";
+import { useGetHsmConnectorById, useTestHsmConnector } from "@app/hooks/api/hsmConnectors";
+import { ProjectType } from "@app/hooks/api/projects/types";
+
+import { DeleteHsmConnectorDialog } from "../SettingsPage/components/HsmConnectorsTab/DeleteHsmConnectorDialog";
+import { EditHsmConnectorSheet } from "../SettingsPage/components/HsmConnectorsTab/EditHsmConnectorSheet";
+import { HsmConnectorLinkedCertsSection, HsmConnectorOverviewSection } from "./components";
+
+const Page = () => {
+ const { currentProject } = useProject();
+ const { currentOrg } = useOrganization();
+ const navigate = useNavigate();
+ const { connectorId } = useParams({
+ from: ROUTE_PATHS.CertManager.HsmConnectorDetailsByIDPage.id
+ });
+
+ const { data: connector } = useGetHsmConnectorById(connectorId);
+ const testMutation = useTestHsmConnector();
+
+ const [isEditOpen, setIsEditOpen] = useState(false);
+ const [isDeleteOpen, setIsDeleteOpen] = useState(false);
+
+ const projectId = currentProject?.id || "";
+
+ const navigateBackToList = () => {
+ navigate({
+ to: "/organizations/$orgId/projects/cert-manager/$projectId/settings",
+ params: { orgId: currentOrg.id, projectId },
+ search: { selectedTab: "hsm-connectors" }
+ });
+ };
+
+ const handleTest = async () => {
+ if (!connector) return;
+ try {
+ const result = await testMutation.mutateAsync({ connectorId: connector.id });
+ if (result.ok) {
+ createNotification({
+ type: "success",
+ text: "HSM Connector verified. Gateway reached the HSM and the slot is online."
+ });
+ } else {
+ const failed = result.members.find((m) => !m.ok);
+ createNotification({
+ type: "error",
+ text:
+ failed && !failed.ok
+ ? `Verify failed (${failed.errorCode}): ${failed.errorMessage}`
+ : "Verify against the HSM failed."
+ });
+ }
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: err instanceof Error ? err.message : "Failed to verify HSM Connector"
+ });
+ }
+ };
+
+ return (
+ <div className="mx-auto flex flex-col justify-between bg-bunker-800 text-white">
+ {connector && (
+ <ProjectPermissionCan
+ I={ProjectPermissionHsmConnectorActions.Read}
+ a={ProjectPermissionSub.HsmConnectors}
+ >
+ {(isAllowed) =>
+ isAllowed ? (
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <Link
+ to="/organizations/$orgId/projects/cert-manager/$projectId/settings"
+ params={{ orgId: currentOrg.id, projectId }}
+ search={{ selectedTab: "hsm-connectors" }}
+ className="mb-4 flex items-center gap-x-2 text-sm text-mineshaft-400"
+ >
+ <ChevronLeftIcon className="size-4" />
+ HSM Connectors
+ </Link>
+ <PageHeader
+ scope={ProjectType.CertificateManager}
+ description={connector.description || "Hardware security module connector"}
+ title={connector.name}
+ />
+ <div className="flex flex-col gap-5 lg:flex-row">
+ <div className="w-full lg:max-w-[24rem]">
+ <HsmConnectorOverviewSection
+ connector={connector}
+ onTest={handleTest}
+ onEdit={() => setIsEditOpen(true)}
+ onDelete={() => setIsDeleteOpen(true)}
+ isTesting={testMutation.isPending}
+ />
+ </div>
+ <div className="flex flex-1 flex-col gap-y-5">
+ <HsmConnectorLinkedCertsSection connectorId={connector.id} />
+ </div>
+ </div>
+
+ <EditHsmConnectorSheet
+ connector={isEditOpen ? connector : null}
+ onClose={() => setIsEditOpen(false)}
+ />
+
+ <DeleteHsmConnectorDialog
+ connector={isDeleteOpen ? connector : null}
+ onClose={() => setIsDeleteOpen(false)}
+ onDeleted={navigateBackToList}
+ />
+ </div>
+ ) : (
+ <div className="container mx-auto flex h-full items-center justify-center">
+ <AccessRestrictedBanner />
+ </div>
+ )
+ }
+ </ProjectPermissionCan>
+ )}
+ </div>
+ );
+};
+
+export const HsmConnectorDetailsByIDPage = () => (
+ <>
+ <Helmet>
+ <title>HSM Connectors</title>
+ <link rel="icon" href="/infisical.ico" />
+ </Helmet>
+ <Page />
+ </>
+);
diff --git a/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/HsmConnectorLinkedCertsSection.tsx b/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/HsmConnectorLinkedCertsSection.tsx
new file mode 100644
index 0000000000..1d2afe4fa4
--- /dev/null
+++ b/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/HsmConnectorLinkedCertsSection.tsx
@@ -0,0 +1,137 @@
+import { useState } from "react";
+import { useNavigate } from "@tanstack/react-router";
+import { format } from "date-fns";
+
+import {
+ Badge,
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ Pagination,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} 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";
+
+type Props = { connectorId: string };
+
+export const HsmConnectorLinkedCertsSection = ({ connectorId }: Props) => {
+ const [page, setPage] = useState(1);
+ const [perPage, setPerPage] = useState(20);
+ const { data, isPending } = useListHsmConnectorLinkedCertificates(connectorId, {
+ offset: (page - 1) * perPage,
+ limit: perPage
+ });
+ const linked = data?.linkedCertificates ?? [];
+ const totalCount = data?.totalCount ?? 0;
+ const navigate = useNavigate();
+ const { currentProject } = useProject();
+ const { currentOrg } = useOrganization();
+
+ const handlePerPageChange = (newPerPage: number) => {
+ setPerPage(newPerPage);
+ setPage(1);
+ };
+
+ const openCert = (certificateId: string) => {
+ if (!currentProject?.id || !currentOrg?.id) return;
+ navigate({
+ to: "/organizations/$orgId/projects/cert-manager/$projectId/certificates/$certificateId",
+ params: { orgId: currentOrg.id, projectId: currentProject.id, certificateId },
+ search: { fromHsmConnector: connectorId }
+ });
+ };
+
+ return (
+ <Card className="w-full">
+ <CardHeader className="border-b">
+ <CardTitle>Linked certificates</CardTitle>
+ <CardDescription>
+ Certificates that use this HSM Connector as their key source. Delete is blocked while any
+ of these exist. Re-issue them with a different key source or retire them first.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ {isPending && <Skeleton className="h-24" />}
+ {!isPending && linked.length === 0 && (
+ <Empty className="border border-solid">
+ <EmptyHeader>
+ <EmptyTitle>No certificates linked</EmptyTitle>
+ <EmptyDescription>
+ No certificate currently uses this connector. It is safe to delete.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ )}
+ {!isPending && linked.length > 0 && (
+ <>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Common name</TableHead>
+ <TableHead>Status</TableHead>
+ <TableHead>HSM key label</TableHead>
+ <TableHead>Expires</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {linked.map((c) => (
+ <TableRow
+ key={c.id}
+ className="cursor-pointer hover:bg-mineshaft-700"
+ onClick={() => openCert(c.id)}
+ >
+ <TableCell className="font-medium">{c.commonName}</TableCell>
+ <TableCell>
+ <Badge variant={c.status === CertStatus.ACTIVE ? "success" : "outline"}>
+ {c.status}
+ </Badge>
+ </TableCell>
+ <TableCell className="max-w-[14rem] font-mono text-xs">
+ {c.hsmKeyLabel ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="block truncate">{c.hsmKeyLabel}</span>
+ </TooltipTrigger>
+ <TooltipContent>{c.hsmKeyLabel}</TooltipContent>
+ </Tooltip>
+ ) : (
+ "-"
+ )}
+ </TableCell>
+ <TableCell>
+ {c.notAfter ? format(new Date(c.notAfter), "MMM d, yyyy") : "-"}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ <Pagination
+ count={totalCount}
+ page={page}
+ perPage={perPage}
+ onChangePage={setPage}
+ onChangePerPage={handlePerPageChange}
+ />
+ </>
+ )}
+ </CardContent>
+ </Card>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/HsmConnectorOverviewSection.tsx b/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/HsmConnectorOverviewSection.tsx
new file mode 100644
index 0000000000..149658e035
--- /dev/null
+++ b/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/HsmConnectorOverviewSection.tsx
@@ -0,0 +1,207 @@
+import { useQuery } from "@tanstack/react-query";
+import { format } from "date-fns";
+import {
+ CheckCircle2Icon,
+ CheckIcon,
+ CopyIcon,
+ MoreHorizontalIcon,
+ PencilIcon,
+ Trash2Icon
+} from "lucide-react";
+
+import { ProjectPermissionCan } from "@app/components/permissions";
+import {
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ Detail,
+ DetailGroup,
+ DetailLabel,
+ DetailValue,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ IconButton,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import {
+ ProjectPermissionHsmConnectorActions,
+ ProjectPermissionSub
+} from "@app/context/ProjectPermissionContext/types";
+import { useTimedReset } from "@app/hooks";
+import { useListGatewayPools } from "@app/hooks/api/gateway-pools";
+import { gatewaysQueryKeys } from "@app/hooks/api/gateways/queries";
+import { THsmConnector } from "@app/hooks/api/hsmConnectors";
+
+type Props = {
+ connector: THsmConnector;
+ onTest: () => void;
+ onEdit: () => void;
+ onDelete: () => void;
+ isTesting: boolean;
+};
+
+export const HsmConnectorOverviewSection = ({
+ connector,
+ onTest,
+ onEdit,
+ onDelete,
+ isTesting
+}: Props) => {
+ const [, isCopying, setCopyText] = useTimedReset<string>({
+ initialState: "Copy ID to clipboard"
+ });
+ const [, isMenuIdCopied, setMenuCopyState] = useTimedReset<string>({ initialState: "Copy" });
+
+ const { data: gateways = [] } = useQuery(gatewaysQueryKeys.list());
+ const { data: pools = [] } = useListGatewayPools();
+
+ const reachedFromLabel = (() => {
+ if (connector.gatewayId) {
+ const g = gateways.find((x) => x.id === connector.gatewayId);
+ return g?.name ?? "(deleted)";
+ }
+ if (connector.gatewayPoolId) {
+ const p = pools.find((x) => x.id === connector.gatewayPoolId);
+ return p?.name ?? "(deleted)";
+ }
+ return "-";
+ })();
+
+ return (
+ <Card className="w-full">
+ <CardHeader className="border-b">
+ <CardTitle>Details</CardTitle>
+ <CardAction>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton variant="ghost" size="xs" aria-label="Connector options">
+ <MoreHorizontalIcon className="size-4" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={() => {
+ navigator.clipboard.writeText(connector.id);
+ setMenuCopyState("Copied");
+ }}
+ >
+ {isMenuIdCopied ? <CheckIcon /> : <CopyIcon />}
+ Copy Connector ID
+ </DropdownMenuItem>
+ <ProjectPermissionCan
+ I={ProjectPermissionHsmConnectorActions.Test}
+ a={ProjectPermissionSub.HsmConnectors}
+ >
+ {(canTest) => (
+ <DropdownMenuItem isDisabled={!canTest || isTesting} onClick={onTest}>
+ <CheckCircle2Icon />
+ {isTesting ? "Verifying..." : "Verify"}
+ </DropdownMenuItem>
+ )}
+ </ProjectPermissionCan>
+ <ProjectPermissionCan
+ I={ProjectPermissionHsmConnectorActions.Edit}
+ a={ProjectPermissionSub.HsmConnectors}
+ >
+ {(canEdit) => (
+ <DropdownMenuItem isDisabled={!canEdit} onClick={onEdit}>
+ <PencilIcon />
+ Edit Details
+ </DropdownMenuItem>
+ )}
+ </ProjectPermissionCan>
+ <ProjectPermissionCan
+ I={ProjectPermissionHsmConnectorActions.Delete}
+ a={ProjectPermissionSub.HsmConnectors}
+ >
+ {(canDelete) => (
+ <DropdownMenuItem variant="danger" isDisabled={!canDelete} onClick={onDelete}>
+ <Trash2Icon />
+ Delete Connector
+ </DropdownMenuItem>
+ )}
+ </ProjectPermissionCan>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ <DetailGroup>
+ <Detail>
+ <DetailLabel>Name</DetailLabel>
+ <DetailValue>{connector.name}</DetailValue>
+ </Detail>
+
+ <Detail>
+ <DetailLabel>Connector ID</DetailLabel>
+ <DetailValue className="flex items-center gap-x-1">
+ <span className="break-all">{connector.id}</span>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="xs"
+ aria-label="Copy connector ID"
+ onClick={() => {
+ navigator.clipboard.writeText(connector.id);
+ setCopyText("Copied");
+ }}
+ >
+ {isCopying ? <CheckIcon /> : <CopyIcon />}
+ </IconButton>
+ </TooltipTrigger>
+ <TooltipContent>{isCopying ? "Copied" : "Copy ID to clipboard"}</TooltipContent>
+ </Tooltip>
+ </DetailValue>
+ </Detail>
+
+ {connector.description && (
+ <Detail>
+ <DetailLabel>Description</DetailLabel>
+ <DetailValue>{connector.description}</DetailValue>
+ </Detail>
+ )}
+
+ <Detail>
+ <DetailLabel>Reached from</DetailLabel>
+ <DetailValue>{reachedFromLabel}</DetailValue>
+ </Detail>
+
+ <Detail>
+ <DetailLabel>Slot label</DetailLabel>
+ <DetailValue>{connector.slotLabel}</DetailValue>
+ </Detail>
+
+ <Detail>
+ <DetailLabel>Key label prefix</DetailLabel>
+ <DetailValue>{connector.keyNamePrefix || "-"}</DetailValue>
+ </Detail>
+
+ {connector.createdAt && (
+ <Detail>
+ <DetailLabel>Created</DetailLabel>
+ <DetailValue>
+ {format(new Date(connector.createdAt), "MMM d, yyyy 'at' h:mm a")}
+ </DetailValue>
+ </Detail>
+ )}
+
+ {connector.updatedAt && (
+ <Detail>
+ <DetailLabel>Last updated</DetailLabel>
+ <DetailValue>
+ {format(new Date(connector.updatedAt), "MMM d, yyyy 'at' h:mm a")}
+ </DetailValue>
+ </Detail>
+ )}
+ </DetailGroup>
+ </CardContent>
+ </Card>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/index.ts b/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/index.ts
new file mode 100644
index 0000000000..fc880391f4
--- /dev/null
+++ b/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/index.ts
@@ -0,0 +1,2 @@
+export { HsmConnectorLinkedCertsSection } from "./HsmConnectorLinkedCertsSection";
+export { HsmConnectorOverviewSection } from "./HsmConnectorOverviewSection";
diff --git a/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/route.tsx b/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/route.tsx
new file mode 100644
index 0000000000..5c4d31f6aa
--- /dev/null
+++ b/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/route.tsx
@@ -0,0 +1,27 @@
+import { createFileRoute, linkOptions } from "@tanstack/react-router";
+
+import { HsmConnectorDetailsByIDPage } from "./HsmConnectorDetailsByIDPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/hsm-connectors/$connectorId"
+)({
+ component: HsmConnectorDetailsByIDPage,
+ beforeLoad: ({ context, params }) => {
+ return {
+ breadcrumbs: [
+ ...context.breadcrumbs,
+ {
+ label: "HSM Connectors",
+ link: linkOptions({
+ to: "/organizations/$orgId/projects/cert-manager/$projectId/settings",
+ params: {
+ orgId: params.orgId,
+ projectId: params.projectId
+ },
+ search: { selectedTab: "hsm-connectors" }
+ })
+ }
+ ]
+ };
+ }
+});
diff --git a/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx b/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx
index 3c21af838d..25de731c6e 100644
--- a/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx
+++ b/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx
@@ -4,11 +4,15 @@ import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ProjectPermissionCan } from "@app/components/permissions";
import { PageHeader, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
import { ProjectPermissionSub } from "@app/context";
-import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";
+import {
+ ProjectPermissionAppConnectionActions,
+ ProjectPermissionHsmConnectorActions
+} from "@app/context/ProjectPermissionContext/types";
import { ProjectType } from "@app/hooks/api/projects/types";
import { AppConnectionsTab } from "./components/AppConnectionsTab";
import { CertificateCleanupTab } from "./components/CertificateCleanupTab";
+import { HsmConnectorsTab } from "./components/HsmConnectorsTab";
export const SettingsPage = () => {
const { orgId, projectId } = useParams({ strict: false });
@@ -25,7 +29,7 @@ export const SettingsPage = () => {
<PageHeader
scope={ProjectType.CertificateManager}
title="Settings"
- description="Configure app connections and cleanup rules."
+ description="Configure app connections, HSM connectors, and cleanup rules."
/>
<Tabs
@@ -42,6 +46,9 @@ export const SettingsPage = () => {
<Tab variant="project" value="app-connections">
App Connections
</Tab>
+ <Tab variant="project" value="hsm-connectors">
+ HSM Connectors
+ </Tab>
<Tab variant="project" value="cleanup">
Cleanup
</Tab>
@@ -57,6 +64,16 @@ export const SettingsPage = () => {
</ProjectPermissionCan>
</TabPanel>
+ <TabPanel value="hsm-connectors">
+ <ProjectPermissionCan
+ renderGuardBanner
+ I={ProjectPermissionHsmConnectorActions.Read}
+ a={ProjectPermissionSub.HsmConnectors}
+ >
+ <HsmConnectorsTab />
+ </ProjectPermissionCan>
+ </TabPanel>
+
<TabPanel value="cleanup">
<CertificateCleanupTab />
</TabPanel>
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/AccessStep.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/AccessStep.tsx
new file mode 100644
index 0000000000..16bbe5bebf
--- /dev/null
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/AccessStep.tsx
@@ -0,0 +1,87 @@
+import { Controller, useForm } from "react-hook-form";
+
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ Input
+} from "@app/components/v3";
+
+import { AccessForm } from "./schemas";
+
+type Props = { form: ReturnType<typeof useForm<AccessForm>> };
+
+export const AccessStep = ({ form }: Props) => (
+ <FieldGroup>
+ <Controller
+ name="slotLabel"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Slot label <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input {...field} placeholder="production-signing" isError={Boolean(error)} />
+ <FieldDescription>
+ The PKCS#11 token label of the slot on the HSM where signing keys will live. Ask your
+ HSM administrator if you are not sure.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ name="pin"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ PIN <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ type="password"
+ placeholder="Enter the slot PIN"
+ autoComplete="new-password"
+ isError={Boolean(error)}
+ />
+ <FieldDescription>
+ The PIN Infisical uses to log in to that slot through the Gateway.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ name="keyNamePrefix"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>Key label prefix</FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ value={field.value ?? ""}
+ placeholder="infisical-"
+ isError={Boolean(error)}
+ />
+ <FieldDescription>
+ Prepended to the label of every key Infisical creates on this HSM. Makes them easy to
+ identify in your HSM tooling.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ </FieldGroup>
+);
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.tsx
new file mode 100644
index 0000000000..091d5fdf3c
--- /dev/null
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/BasicsStep.tsx
@@ -0,0 +1,60 @@
+import { Controller, useForm } from "react-hook-form";
+
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ Input,
+ TextArea
+} from "@app/components/v3";
+
+import { BasicsForm } from "./schemas";
+
+type Props = { form: ReturnType<typeof useForm<BasicsForm>> };
+
+export const BasicsStep = ({ form }: Props) => (
+ <FieldGroup>
+ <Controller
+ name="name"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Name <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input {...field} placeholder="fortanix-prod" isError={Boolean(error)} />
+ <FieldDescription>
+ A descriptive name so you can identify this connector later. Lowercase letters,
+ numbers, and dashes.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ name="description"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>Description</FieldLabel>
+ <FieldContent>
+ <TextArea
+ {...field}
+ value={field.value ?? ""}
+ placeholder="What this HSM is used for (e.g. production macOS code-signing keys)."
+ rows={3}
+ isError={Boolean(error)}
+ />
+ <FieldDescription>Optional. Context for your team.</FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ </FieldGroup>
+);
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.tsx
new file mode 100644
index 0000000000..96e4f315a3
--- /dev/null
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx
@@ -0,0 +1,338 @@
+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 { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ IconButton,
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ Stepper,
+ StepperList,
+ StepperStep,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} 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";
+
+import { AccessStep } from "./AccessStep";
+import { BasicsStep } from "./BasicsStep";
+import { HostStep, ReachedFromOption } from "./HostStep";
+import {
+ AccessForm,
+ accessSchema,
+ BasicsForm,
+ basicsSchema,
+ HostForm,
+ hostSchema
+} 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 = {
+ isOpen: boolean;
+ onOpenChange: (open: boolean) => void;
+};
+
+export const CreateHsmConnectorWizard = ({ 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();
+ const createMutation = useCreateHsmConnector();
+
+ const reachedFromOptions: ReachedFromOption[] = useMemo(() => {
+ const gatewayOptions: ReachedFromOption[] = gateways
+ .filter((g) => !g.isV1)
+ .filter((g) => g.capabilities?.pkcs11 === true)
+ .map((g) => ({ value: `gateway:${g.id}`, label: g.name, group: "gateway" as const }));
+ const poolOptions: ReachedFromOption[] = pools.map((p) => ({
+ value: `pool:${p.id}`,
+ label: p.name,
+ group: "pool" as const
+ }));
+ return [...gatewayOptions, ...poolOptions];
+ }, [gateways, pools]);
+
+ const basicsForm = useForm<BasicsForm>({
+ resolver: zodResolver(basicsSchema),
+ values: { name: state.name, description: state.description.trim() || undefined }
+ });
+ const hostForm = useForm<HostForm>({
+ resolver: zodResolver(hostSchema),
+ values: { reachedFrom: state.reachedFrom }
+ });
+ const accessForm = useForm<AccessForm>({
+ resolver: zodResolver(accessSchema),
+ values: {
+ slotLabel: state.slotLabel,
+ pin: state.pin,
+ keyNamePrefix: state.keyNamePrefix || undefined
+ }
+ });
+
+ const reset = () => {
+ setStep(0);
+ setState(INITIAL_WIZARD_STATE);
+ basicsForm.reset({ name: "", description: undefined });
+ hostForm.reset({ reachedFrom: "" });
+ accessForm.reset({ slotLabel: "", pin: "", keyNamePrefix: "infisical-" });
+ };
+
+ const handleClose = (open: boolean) => {
+ if (!open && submitting) return;
+ if (!open) reset();
+ onOpenChange(open);
+ };
+
+ const onCreate = async (finalState: WizardState) => {
+ setSubmitting(true);
+ try {
+ const [kind, id] = finalState.reachedFrom.split(":");
+ await createMutation.mutateAsync({
+ name: finalState.name,
+ description: finalState.description.trim() || undefined,
+ gatewayId: kind === "gateway" ? id : undefined,
+ gatewayPoolId: kind === "pool" ? id : undefined,
+ credentials: {
+ slotLabel: finalState.slotLabel,
+ pin: finalState.pin,
+ keyNamePrefix: finalState.keyNamePrefix?.trim() || undefined
+ }
+ });
+ createNotification({
+ type: "success",
+ text: `HSM Connector "${finalState.name}" created and verified.`
+ });
+ handleClose(false);
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: err instanceof Error ? err.message : "Failed to create HSM Connector"
+ });
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ const goNext = async () => {
+ if (step === 0) {
+ const ok = await basicsForm.trigger();
+ if (!ok) return;
+ const values = basicsForm.getValues();
+ setState((prev) => ({
+ ...prev,
+ name: values.name,
+ description: values.description ?? ""
+ }));
+ setStep(1);
+ return;
+ }
+ if (step === 1) {
+ const ok = await hostForm.trigger();
+ if (!ok) return;
+ const values = hostForm.getValues();
+ setState((prev) => ({ ...prev, reachedFrom: values.reachedFrom }));
+ setStep(2);
+ return;
+ }
+ if (step === 2) {
+ const ok = await accessForm.trigger();
+ if (!ok) return;
+ const values = accessForm.getValues();
+ const finalState: WizardState = {
+ ...state,
+ slotLabel: values.slotLabel,
+ pin: values.pin,
+ keyNamePrefix: values.keyNamePrefix ?? ""
+ };
+ setState(finalState);
+ await onCreate(finalState);
+ }
+ };
+
+ const goBack = () => {
+ if (step > 0) setStep((s) => s - 1);
+ };
+
+ const dirty = step > 0 || state.name !== "";
+ const currentStep = STEPS[step];
+ const isLast = step === STEPS.length - 1;
+ const ctaLabel = isLast ? "Add HSM Connector" : "Continue";
+
+ return (
+ <Sheet open={isOpen} onOpenChange={handleClose}>
+ <SheetContent className="flex h-full max-h-full flex-col gap-y-0 sm:max-w-[1500px]">
+ <SheetHeader className="border-b">
+ <SheetTitle>
+ <div className="flex w-full items-start gap-2">
+ <div className="flex h-10 w-10 items-center justify-center rounded-md bg-project/10 text-project">
+ <ShieldCheckIcon className="h-5 w-5" />
+ </div>
+ <div>
+ <div className="flex items-center gap-x-2 text-mineshaft-300">
+ 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.
+ </p>
+ </div>
+ </div>
+ </SheetTitle>
+ </SheetHeader>
+
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className="flex min-h-0 flex-1 overflow-hidden">
+ <aside className="flex w-60 shrink-0 flex-col border-r border-border px-5 py-6">
+ <p className="mb-5 text-[11px] font-medium tracking-wider text-muted uppercase">
+ Setup steps
+ </p>
+ <Stepper
+ activeStep={step}
+ orientation="vertical"
+ onStepChange={(i) => {
+ if (i < step) setStep(i);
+ }}
+ >
+ <StepperList>
+ {STEPS.map((s, i) => (
+ <StepperStep
+ key={s.name}
+ index={i}
+ title={s.name}
+ description={s.shortDescription}
+ />
+ ))}
+ </StepperList>
+ </Stepper>
+ </aside>
+
+ <div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">
+ <div className="mb-6">
+ <h2 className="text-lg font-semibold text-foreground">{currentStep.title}</h2>
+ <p className="mt-1 text-sm text-muted">{currentStep.subtitle}</p>
+ </div>
+
+ {step === 0 && <BasicsStep form={basicsForm} />}
+ {step === 1 && (
+ <HostStep
+ form={hostForm}
+ options={reachedFromOptions}
+ isLoading={isGatewaysLoading || isPoolsLoading}
+ />
+ )}
+ {step === 2 && <AccessStep form={accessForm} />}
+ </div>
+
+ <aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">
+ <div>
+ <p className="text-[11px] font-medium tracking-wider text-muted uppercase">
+ Step {step + 1} · {currentStep.rightLabel}
+ </p>
+ <p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>
+ <p className="mt-2 text-sm leading-relaxed text-muted">
+ {currentStep.rightDescription}
+ </p>
+ </div>
+
+ <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="text-muted">
+ Run this on a machine that can reach your HSM. Use your vendor&apos;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:{" "}
+ <a
+ href="https://infisical.com/docs/documentation/platform/pki/code-signing/hsm-connectors"
+ target="_blank"
+ rel="noreferrer"
+ className="text-primary hover:underline"
+ >
+ HSM Connectors docs
+ </a>
+ .
+ </p>
+ </div>
+ )}
+ {isLast && (
+ <p className="text-xs leading-relaxed text-muted">
+ Infisical runs a Verify against your HSM before saving. A wrong PIN, slot, or
+ unreachable Gateway will surface here.
+ </p>
+ )}
+ </div>
+ </aside>
+ </div>
+
+ <div className="flex shrink-0 items-center justify-between gap-3 border-t border-border px-6 py-4">
+ <span className="text-xs text-muted">{dirty ? "Unsaved changes" : ""}</span>
+ <div className="flex items-center gap-3">
+ <span className="text-xs text-muted">
+ Step {step + 1} of {STEPS.length}
+ </span>
+ {step > 0 && (
+ <Button variant="outline" onClick={goBack}>
+ Back
+ </Button>
+ )}
+ <Button variant="project" onClick={goNext} isPending={submitting}>
+ {ctaLabel}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </SheetContent>
+ </Sheet>
+ );
+};
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.tsx
new file mode 100644
index 0000000000..b9e6cf3366
--- /dev/null
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/HostStep.tsx
@@ -0,0 +1,88 @@
+import { Controller, useForm } from "react-hook-form";
+import { ServerIcon } from "lucide-react";
+
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ FilterableSelect
+} from "@app/components/v3";
+
+import { HostForm } from "./schemas";
+
+export type ReachedFromOption = {
+ value: string;
+ label: string;
+ group: "gateway" | "pool";
+};
+
+type Props = {
+ form: ReturnType<typeof useForm<HostForm>>;
+ options: ReachedFromOption[];
+ isLoading: boolean;
+};
+
+export const HostStep = ({ form, options, isLoading }: Props) => (
+ <FieldGroup>
+ <Controller
+ name="reachedFrom"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Reached from <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <FilterableSelect<ReachedFromOption>
+ isLoading={isLoading}
+ options={options}
+ value={options.find((o) => o.value === field.value) ?? null}
+ onChange={(selected) => {
+ const opt = selected as ReachedFromOption | null;
+ field.onChange(opt?.value ?? "");
+ }}
+ getOptionLabel={(opt) => opt.label}
+ getOptionValue={(opt) => opt.value}
+ groupBy={options.length > 0 ? "group" : undefined}
+ getGroupHeaderLabel={
+ options.length > 0
+ ? (group: ReachedFromOption["group"]) =>
+ group === "gateway" ? "Gateways" : "Gateway Pools"
+ : undefined
+ }
+ placeholder="Select a Gateway..."
+ noOptionsMessage={() => "No PKCS#11-enabled Gateways found."}
+ isError={Boolean(error)}
+ />
+ <FieldDescription>
+ The Infisical Gateway that will reach the HSM over PKCS#11.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ {!isLoading && options.length === 0 && (
+ <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&apos;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
+ </pre>
+ <p className="text-muted">The Gateway will appear here as soon as it heartbeats.</p>
+ </div>
+ </div>
+ </div>
+ )}
+ </FieldGroup>
+);
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/index.ts b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/index.ts
new file mode 100644
index 0000000000..2ccc572bff
--- /dev/null
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/index.ts
@@ -0,0 +1 @@
+export { CreateHsmConnectorWizard } from "./CreateHsmConnectorWizard";
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/schemas.ts b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/schemas.ts
new file mode 100644
index 0000000000..dc44b91014
--- /dev/null
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/schemas.ts
@@ -0,0 +1,21 @@
+import { z } from "zod";
+
+import { slugSchema } from "@app/lib/schemas";
+
+export const basicsSchema = z.object({
+ name: slugSchema({ min: 1, max: 32, field: "Name" }),
+ description: z.string().trim().max(256).optional()
+});
+export type BasicsForm = z.infer<typeof basicsSchema>;
+
+export const hostSchema = z.object({
+ reachedFrom: z.string().min(1, "Pick a Gateway that can reach your HSM")
+});
+export type HostForm = z.infer<typeof hostSchema>;
+
+export const accessSchema = z.object({
+ slotLabel: z.string().min(1, "Slot label is required").max(128),
+ pin: z.string().min(1, "PIN is required").max(512),
+ keyNamePrefix: z.string().trim().max(64).optional()
+});
+export type AccessForm = z.infer<typeof accessSchema>;
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.ts
new file mode 100644
index 0000000000..dce4765598
--- /dev/null
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/types.ts
@@ -0,0 +1,56 @@
+export type WizardState = {
+ name: string;
+ description: string;
+ reachedFrom: string;
+ slotLabel: string;
+ pin: string;
+ keyNamePrefix: string;
+};
+
+export const INITIAL_WIZARD_STATE: WizardState = {
+ name: "",
+ description: "",
+ reachedFrom: "",
+ slotLabel: "",
+ pin: "",
+ keyNamePrefix: "infisical-"
+};
+
+export type WizardStep = {
+ name: string;
+ shortDescription: string;
+ title: string;
+ subtitle: string;
+ rightLabel: string;
+ rightDescription: string;
+};
+
+export const STEPS: WizardStep[] = [
+ {
+ name: "Basics",
+ shortDescription: "Name and description",
+ title: "Basics",
+ 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."
+ },
+ {
+ 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",
+ 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."
+ },
+ {
+ name: "Access",
+ shortDescription: "Slot and PIN",
+ title: "Access",
+ subtitle: "How Infisical signs in to your HSM.",
+ rightLabel: "ACCESS",
+ 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/DeleteHsmConnectorDialog.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/DeleteHsmConnectorDialog.tsx
new file mode 100644
index 0000000000..211c4581d0
--- /dev/null
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/DeleteHsmConnectorDialog.tsx
@@ -0,0 +1,74 @@
+import { TrashIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogMedia,
+ AlertDialogTitle
+} from "@app/components/v3";
+import { THsmConnector, useDeleteHsmConnector } from "@app/hooks/api/hsmConnectors";
+
+type Props = {
+ connector: THsmConnector | null;
+ onClose: () => void;
+ onDeleted?: () => void;
+};
+
+export const DeleteHsmConnectorDialog = ({ connector, onClose, onDeleted }: Props) => {
+ const deleteMutation = useDeleteHsmConnector();
+ const isOpen = Boolean(connector);
+
+ const handleConfirm = async () => {
+ if (!connector) return;
+ try {
+ await deleteMutation.mutateAsync({ connectorId: connector.id });
+ createNotification({ type: "success", text: `HSM Connector "${connector.name}" deleted.` });
+ onClose();
+ onDeleted?.();
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: err instanceof Error ? err.message : "Failed to delete HSM Connector"
+ });
+ }
+ };
+
+ return (
+ <AlertDialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogMedia>
+ <TrashIcon className="h-5 w-5 text-danger" />
+ </AlertDialogMedia>
+ <AlertDialogTitle>Delete HSM Connector</AlertDialogTitle>
+ <AlertDialogDescription>
+ {connector ? (
+ <>
+ Are you sure you want to delete{" "}
+ <span className="font-mono text-mineshaft-100">{connector.name}</span>? Any
+ certificate that references this connector will block the deletion, and the HSM key
+ on your HSM is not touched.
+ </>
+ ) : null}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={deleteMutation.isPending}>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="danger"
+ onClick={handleConfirm}
+ disabled={deleteMutation.isPending}
+ >
+ {deleteMutation.isPending ? "Deleting..." : "Delete"}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/EditHsmConnectorSheet.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/EditHsmConnectorSheet.tsx
new file mode 100644
index 0000000000..a0fb47aeda
--- /dev/null
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/EditHsmConnectorSheet.tsx
@@ -0,0 +1,349 @@
+import { useEffect, useMemo } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useQuery } from "@tanstack/react-query";
+import { ShieldCheckIcon } from "lucide-react";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ FilterableSelect,
+ Input,
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ TextArea
+} from "@app/components/v3";
+import { useListGatewayPools } from "@app/hooks/api/gateway-pools";
+import { gatewaysQueryKeys } from "@app/hooks/api/gateways/queries";
+import { THsmConnector, useUpdateHsmConnector } from "@app/hooks/api/hsmConnectors";
+import { slugSchema } from "@app/lib/schemas";
+
+const editSchema = z.object({
+ name: slugSchema({ min: 1, max: 32, field: "Name" }),
+ description: z.string().trim().max(256).optional(),
+ reachedFrom: z.string().min(1, "Pick a Gateway that can reach your HSM"),
+ slotLabel: z.string().min(1, "Slot label is required").max(128),
+ keyNamePrefix: z.string().trim().max(64).optional(),
+ pin: z.string().max(512).optional()
+});
+type EditForm = z.infer<typeof editSchema>;
+
+type ReachedFromOption = { value: string; label: string; group: "gateway" | "pool" };
+
+type Props = {
+ connector: THsmConnector | null;
+ onClose: () => void;
+};
+
+export const EditHsmConnectorSheet = ({ connector, onClose }: Props) => {
+ const isOpen = Boolean(connector);
+ const updateMutation = useUpdateHsmConnector();
+
+ const { data: gateways = [] } = useQuery(gatewaysQueryKeys.list());
+ const { data: pools = [] } = useListGatewayPools();
+
+ const reachedFromOptions: ReachedFromOption[] = useMemo(() => {
+ const currentValue = (() => {
+ if (connector?.gatewayId) return `gateway:${connector.gatewayId}`;
+ if (connector?.gatewayPoolId) return `pool:${connector.gatewayPoolId}`;
+ return "";
+ })();
+ const gatewayOptions: ReachedFromOption[] = gateways
+ .filter((g) => !g.isV1)
+ .filter((g) => g.capabilities?.pkcs11 === true)
+ .map((g) => ({ value: `gateway:${g.id}`, label: g.name, group: "gateway" as const }));
+ const poolOptions: ReachedFromOption[] = pools.map((p) => ({
+ value: `pool:${p.id}`,
+ label: p.name,
+ group: "pool" as const
+ }));
+ const options = [...gatewayOptions, ...poolOptions];
+ const currentIncluded = options.some((o) => o.value === currentValue);
+ if (!currentIncluded && connector && currentValue) {
+ let label = "";
+ if (connector.gatewayId) {
+ const g = gateways.find((x) => x.id === connector.gatewayId);
+ label = g?.name ? `${g.name} (offline)` : `${connector.gatewayId} (offline)`;
+ } else if (connector.gatewayPoolId) {
+ const p = pools.find((x) => x.id === connector.gatewayPoolId);
+ label = p?.name ?? connector.gatewayPoolId;
+ }
+ return [
+ {
+ value: currentValue,
+ label,
+ group: connector.gatewayId ? ("gateway" as const) : ("pool" as const)
+ },
+ ...options
+ ];
+ }
+ return options;
+ }, [gateways, pools, connector]);
+
+ const form = useForm<EditForm>({
+ resolver: zodResolver(editSchema),
+ defaultValues: {
+ name: "",
+ description: "",
+ reachedFrom: "",
+ slotLabel: "",
+ keyNamePrefix: "infisical-",
+ pin: ""
+ }
+ });
+
+ useEffect(() => {
+ if (!connector) return;
+ let reachedFrom = "";
+ if (connector.gatewayId) reachedFrom = `gateway:${connector.gatewayId}`;
+ else if (connector.gatewayPoolId) reachedFrom = `pool:${connector.gatewayPoolId}`;
+ form.reset({
+ name: connector.name,
+ description: connector.description ?? "",
+ reachedFrom,
+ slotLabel: connector.slotLabel,
+ keyNamePrefix: connector.keyNamePrefix ?? "",
+ pin: ""
+ });
+ }, [connector, form]);
+
+ const onSubmit = async (values: EditForm) => {
+ if (!connector) return;
+ const [kind, id] = values.reachedFrom.split(":");
+ const credentialsPatch: Record<string, string> = {};
+ if (values.slotLabel !== connector.slotLabel) credentialsPatch.slotLabel = values.slotLabel;
+ if ((values.keyNamePrefix ?? "") !== (connector.keyNamePrefix ?? ""))
+ credentialsPatch.keyNamePrefix = values.keyNamePrefix ?? "";
+ if (values.pin && values.pin.length > 0) credentialsPatch.pin = values.pin;
+
+ try {
+ await updateMutation.mutateAsync({
+ connectorId: connector.id,
+ name: values.name !== connector.name ? values.name : undefined,
+ description:
+ (values.description ?? "") !== (connector.description ?? "")
+ ? (values.description ?? "")
+ : undefined,
+ gatewayId: kind === "gateway" ? id : undefined,
+ gatewayPoolId: kind === "pool" ? id : undefined,
+ credentials: Object.keys(credentialsPatch).length > 0 ? credentialsPatch : undefined
+ });
+ createNotification({ type: "success", text: `HSM Connector "${values.name}" updated.` });
+ onClose();
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: err instanceof Error ? err.message : "Failed to update HSM Connector"
+ });
+ }
+ };
+
+ return (
+ <Sheet open={isOpen} onOpenChange={(open) => !open && onClose()}>
+ <SheetContent className="flex h-full max-h-full flex-col gap-y-0 sm:max-w-[1100px]">
+ <SheetHeader className="border-b">
+ <SheetTitle>
+ <div className="flex w-full items-start gap-2">
+ <div className="flex h-10 w-10 items-center justify-center rounded-md bg-warning/10 text-warning">
+ <ShieldCheckIcon className="h-5 w-5" />
+ </div>
+ <div>
+ <div className="flex items-center gap-x-2 text-mineshaft-300">
+ Edit HSM Connector
+ </div>
+ <p className="text-sm leading-4 text-mineshaft-400">
+ Update name, description, Gateway, slot label, key label prefix, or rotate the
+ PIN. Changes to the PIN, slot, or Gateway re-run a Verify before saving.
+ </p>
+ </div>
+ </div>
+ </SheetTitle>
+ </SheetHeader>
+
+ <form className="flex min-h-0 flex-1 flex-col" onSubmit={form.handleSubmit(onSubmit)}>
+ <div className="flex min-h-0 flex-1 overflow-hidden">
+ <div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">
+ <FieldGroup>
+ <Controller
+ name="name"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Connector name <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input {...field} isError={Boolean(error)} />
+ <FieldDescription>Lowercase letters, numbers, and dashes.</FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ name="description"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>Description</FieldLabel>
+ <FieldContent>
+ <TextArea
+ {...field}
+ value={field.value ?? ""}
+ rows={2}
+ isError={Boolean(error)}
+ />
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ name="reachedFrom"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Reached from <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <FilterableSelect<ReachedFromOption>
+ options={reachedFromOptions}
+ value={reachedFromOptions.find((o) => o.value === field.value) ?? null}
+ onChange={(selected) => {
+ const opt = selected as ReachedFromOption | null;
+ field.onChange(opt?.value ?? "");
+ }}
+ getOptionLabel={(opt) => opt.label}
+ getOptionValue={(opt) => opt.value}
+ groupBy={reachedFromOptions.length > 0 ? "group" : undefined}
+ getGroupHeaderLabel={
+ reachedFromOptions.length > 0
+ ? (group: ReachedFromOption["group"]) =>
+ group === "gateway" ? "Gateways" : "Gateway Pools"
+ : undefined
+ }
+ placeholder="Select a Gateway..."
+ noOptionsMessage={() => "No PKCS#11-enabled Gateways found."}
+ isError={Boolean(error)}
+ />
+ <FieldDescription>
+ The Infisical Gateway (or pool) that will reach the HSM over PKCS#11.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ name="slotLabel"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Slot label <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input {...field} isError={Boolean(error)} />
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ name="keyNamePrefix"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>Key label prefix</FieldLabel>
+ <FieldContent>
+ <Input {...field} value={field.value ?? ""} isError={Boolean(error)} />
+ <FieldDescription>
+ Prepended to the label of every key Infisical creates on this HSM.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ name="pin"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>PIN</FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ value={field.value ?? ""}
+ type="password"
+ placeholder="••••••••"
+ autoComplete="new-password"
+ isError={Boolean(error)}
+ />
+ <FieldDescription>
+ Leave blank to keep the current PIN. Type a new value to rotate it.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ </FieldGroup>
+ </div>
+
+ <aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">
+ <div className="mb-auto">
+ <p className="text-[11px] font-medium tracking-wider text-muted uppercase">
+ Editing
+ </p>
+ <p className="mt-4 text-sm font-semibold text-foreground">What you can change</p>
+ <ul className="mt-2 space-y-2 text-sm leading-relaxed text-muted">
+ <li>
+ <span className="font-medium text-foreground">Name and description.</span>{" "}
+ Display only. No effect on the HSM.
+ </li>
+ <li>
+ <span className="font-medium text-foreground">Gateway.</span> Switch to a
+ different Gateway or Gateway Pool if you moved the HSM or added a new one.
+ </li>
+ <li>
+ <span className="font-medium text-foreground">Slot and PIN.</span> Rotate the
+ PIN or point to a different slot on the same HSM.
+ </li>
+ </ul>
+ <div className="mt-6 rounded-md border border-border bg-mineshaft-800 p-3 text-xs text-muted">
+ If you change the PIN, slot, or Gateway, Infisical re-runs a Verify against the
+ HSM before saving. A bad PIN or unreachable Gateway will surface here.
+ </div>
+ </div>
+ </aside>
+ </div>
+
+ <div className="flex shrink-0 items-center justify-end gap-3 border-t border-border px-6 py-4">
+ <Button type="button" variant="outline" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button type="submit" variant="project" isPending={updateMutation.isPending}>
+ Save changes
+ </Button>
+ </div>
+ </form>
+ </SheetContent>
+ </Sheet>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/HsmConnectorsTab.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/HsmConnectorsTab.tsx
new file mode 100644
index 0000000000..55f98c7e98
--- /dev/null
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/HsmConnectorsTab.tsx
@@ -0,0 +1,311 @@
+import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { useNavigate, useParams } from "@tanstack/react-router";
+import { format } from "date-fns";
+import {
+ CheckCircle2Icon,
+ CheckIcon,
+ CopyIcon,
+ MoreHorizontalIcon,
+ PencilIcon,
+ PlusIcon,
+ SearchIcon,
+ Trash2Icon
+} from "lucide-react";
+
+import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
+import { createNotification } from "@app/components/notifications";
+import { ProjectPermissionCan } from "@app/components/permissions";
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import { useSubscription } from "@app/context";
+import {
+ ProjectPermissionHsmConnectorActions,
+ ProjectPermissionSub
+} from "@app/context/ProjectPermissionContext/types";
+import { useTimedReset } from "@app/hooks";
+import { useListGatewayPools } from "@app/hooks/api/gateway-pools";
+import { gatewaysQueryKeys } from "@app/hooks/api/gateways/queries";
+import {
+ THsmConnector,
+ useListHsmConnectors,
+ useTestHsmConnector
+} from "@app/hooks/api/hsmConnectors";
+
+import { CreateHsmConnectorWizard } from "./CreateHsmConnectorWizard";
+import { DeleteHsmConnectorDialog } from "./DeleteHsmConnectorDialog";
+import { EditHsmConnectorSheet } from "./EditHsmConnectorSheet";
+
+export const HsmConnectorsTab = () => {
+ const navigate = useNavigate();
+ const { orgId, projectId } = useParams({ strict: false });
+ const { subscription } = useSubscription();
+ const isLicensed = Boolean(subscription?.pkiHsm);
+ const [addOpen, setAddOpen] = useState(false);
+ const [testingId, setTestingId] = useState<string | null>(null);
+ const [editing, setEditing] = useState<THsmConnector | null>(null);
+ const [deleting, setDeleting] = useState<THsmConnector | null>(null);
+ const [search, setSearch] = useState("");
+ const [copiedId, , setCopiedId] = useTimedReset<string>({ initialState: "" });
+ const [upgradeOpen, setUpgradeOpen] = useState(false);
+
+ const openDetail = (connectorId: string) => {
+ if (!orgId || !projectId) return;
+ navigate({
+ to: "/organizations/$orgId/projects/cert-manager/$projectId/hsm-connectors/$connectorId",
+ params: { orgId, projectId, connectorId }
+ });
+ };
+
+ const { data: connectors = [], isPending } = useListHsmConnectors({ enabled: isLicensed });
+ const testMutation = useTestHsmConnector();
+
+ const { data: gateways = [] } = useQuery({ ...gatewaysQueryKeys.list(), enabled: isLicensed });
+ const { data: pools = [] } = useListGatewayPools();
+
+ const filtered = useMemo(() => {
+ const q = search.trim().toLowerCase();
+ if (!q) return connectors;
+ return connectors.filter(
+ (c) =>
+ c.name.toLowerCase().includes(q) ||
+ c.slotLabel.toLowerCase().includes(q) ||
+ (c.description ?? "").toLowerCase().includes(q)
+ );
+ }, [connectors, search]);
+
+ if (!isLicensed) {
+ return (
+ <div>
+ <div className="rounded-md border border-yellow-500/30 bg-yellow-500/5 p-8 text-center">
+ <div className="mb-3 text-2xl">&#x1f6e1;&#xfe0f;</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.
+ </p>
+ <Button onClick={() => setUpgradeOpen(true)}>Upgrade to Enterprise</Button>
+ </div>
+ <UpgradePlanModal
+ isOpen={upgradeOpen}
+ onOpenChange={setUpgradeOpen}
+ text="To use HSM Connectors, upgrade to Infisical's Enterprise plan."
+ />
+ </div>
+ );
+ }
+
+ const reachedFromLabel = (c: THsmConnector) => {
+ if (c.gatewayId) {
+ const g = gateways.find((x) => x.id === c.gatewayId);
+ return g?.name ?? c.gatewayId;
+ }
+ if (c.gatewayPoolId) {
+ const p = pools.find((x) => x.id === c.gatewayPoolId);
+ return p?.name ?? c.gatewayPoolId;
+ }
+ return "-";
+ };
+
+ const handleTest = async (id: string) => {
+ setTestingId(id);
+ try {
+ const result = await testMutation.mutateAsync({ connectorId: id });
+ if (result.ok) {
+ createNotification({
+ type: "success",
+ text: "HSM Connector verified. Gateway reached the HSM and the slot is online."
+ });
+ } else {
+ const firstFailed = result.members.find((m) => !m.ok);
+ createNotification({
+ type: "error",
+ text:
+ firstFailed && !firstFailed.ok
+ ? `Verify failed (${firstFailed.errorCode}): ${firstFailed.errorMessage}`
+ : "Verify against the HSM failed."
+ });
+ }
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: err instanceof Error ? err.message : "Failed to verify HSM Connector"
+ });
+ } finally {
+ setTestingId(null);
+ }
+ };
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>HSM Connectors</CardTitle>
+ <CardDescription>
+ Hardware security modules that hold your signing keys, reached through your hosts.
+ </CardDescription>
+ <CardAction>
+ <ProjectPermissionCan
+ I={ProjectPermissionHsmConnectorActions.Create}
+ a={ProjectPermissionSub.HsmConnectors}
+ >
+ {(isAllowed) => (
+ <Button onClick={() => setAddOpen(true)} variant="project" isDisabled={!isAllowed}>
+ <PlusIcon />
+ Add HSM Connector
+ </Button>
+ )}
+ </ProjectPermissionCan>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ <div className="mb-4 flex gap-2">
+ <InputGroup className="flex-1">
+ <InputGroupAddon>
+ <SearchIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search HSM Connectors by name..."
+ />
+ </InputGroup>
+ </div>
+ {isPending ? (
+ <Skeleton className="h-24" />
+ ) : (
+ <>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Name</TableHead>
+ <TableHead>Reached from</TableHead>
+ <TableHead>Slot</TableHead>
+ <TableHead>Created</TableHead>
+ <TableHead className="w-[60px]" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {filtered.map((c) => (
+ <TableRow
+ key={c.id}
+ className="cursor-pointer hover:bg-mineshaft-700"
+ onClick={() => openDetail(c.id)}
+ >
+ <TableCell>{c.name}</TableCell>
+ <TableCell>{reachedFromLabel(c)}</TableCell>
+ <TableCell>{c.slotLabel}</TableCell>
+ <TableCell>{format(new Date(c.createdAt), "MMM d, yyyy")}</TableCell>
+ <TableCell onClick={(e) => e.stopPropagation()} className="cursor-default">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton aria-label="Actions" variant="ghost">
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={() => {
+ navigator.clipboard.writeText(c.id);
+ setCopiedId(c.id);
+ }}
+ >
+ {copiedId === c.id ? <CheckIcon /> : <CopyIcon />}
+ Copy Connector ID
+ </DropdownMenuItem>
+ <ProjectPermissionCan
+ I={ProjectPermissionHsmConnectorActions.Test}
+ a={ProjectPermissionSub.HsmConnectors}
+ >
+ {(isAllowed) => (
+ <DropdownMenuItem
+ isDisabled={!isAllowed || testingId === c.id}
+ onClick={() => handleTest(c.id)}
+ >
+ <CheckCircle2Icon />
+ {testingId === c.id ? "Verifying..." : "Verify"}
+ </DropdownMenuItem>
+ )}
+ </ProjectPermissionCan>
+ <ProjectPermissionCan
+ I={ProjectPermissionHsmConnectorActions.Edit}
+ a={ProjectPermissionSub.HsmConnectors}
+ >
+ {(isAllowed) => (
+ <DropdownMenuItem
+ isDisabled={!isAllowed}
+ onClick={() => setEditing(c)}
+ >
+ <PencilIcon />
+ Edit Details
+ </DropdownMenuItem>
+ )}
+ </ProjectPermissionCan>
+ <ProjectPermissionCan
+ I={ProjectPermissionHsmConnectorActions.Delete}
+ a={ProjectPermissionSub.HsmConnectors}
+ >
+ {(isAllowed) => (
+ <DropdownMenuItem
+ variant="danger"
+ isDisabled={!isAllowed}
+ onClick={() => setDeleting(c)}
+ >
+ <Trash2Icon />
+ Delete Connector
+ </DropdownMenuItem>
+ )}
+ </ProjectPermissionCan>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ {filtered.length === 0 && (
+ <Empty className="border border-solid">
+ <EmptyHeader>
+ <EmptyTitle>No HSM Connectors</EmptyTitle>
+ <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."}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ )}
+ </>
+ )}
+ </CardContent>
+ <CreateHsmConnectorWizard 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/SettingsPage/components/HsmConnectorsTab/index.ts b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/index.ts
new file mode 100644
index 0000000000..31073c76a3
--- /dev/null
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/index.ts
@@ -0,0 +1 @@
+export { HsmConnectorsTab } from "./HsmConnectorsTab";
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
index 24b7b98b81..c5fcfd7eb5 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
@@ -21,6 +21,7 @@ import {
ProjectPermissionDynamicSecretActions,
ProjectPermissionGroupActions,
ProjectPermissionHoneyTokenActions,
+ ProjectPermissionHsmConnectorActions,
ProjectPermissionIdentityActions,
ProjectPermissionInsightsActions,
ProjectPermissionKmipActions,
@@ -193,6 +194,15 @@ const AppConnectionPolicyActionSchema = z.object({
[ProjectPermissionAppConnectionActions.RotateCredentials]: z.boolean().optional()
});
+const HsmConnectorPolicyActionSchema = z.object({
+ [ProjectPermissionHsmConnectorActions.Read]: z.boolean().optional(),
+ [ProjectPermissionHsmConnectorActions.Create]: z.boolean().optional(),
+ [ProjectPermissionHsmConnectorActions.Edit]: z.boolean().optional(),
+ [ProjectPermissionHsmConnectorActions.Delete]: z.boolean().optional(),
+ [ProjectPermissionHsmConnectorActions.Test]: z.boolean().optional(),
+ [ProjectPermissionHsmConnectorActions.Attach]: z.boolean().optional()
+});
+
const KmipPolicyActionSchema = z.object({
[ProjectPermissionKmipActions.ReadClients]: z.boolean().optional(),
[ProjectPermissionKmipActions.CreateClients]: z.boolean().optional(),
@@ -693,6 +703,7 @@ export const projectRoleFormSchema = z.object({
})
.array()
.default([]),
+ [ProjectPermissionSub.HsmConnectors]: HsmConnectorPolicyActionSchema.array().default([]),
[ProjectPermissionSub.PkiSyncs]: PkiSyncPolicyActionSchema.extend({
inverted: z.boolean().optional(),
conditions: ConditionSchema
@@ -1093,6 +1104,7 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
ProjectPermissionSub.PkiSyncs,
ProjectPermissionSub.SecretEventSubscriptions,
ProjectPermissionSub.AppConnections,
+ ProjectPermissionSub.HsmConnectors,
ProjectPermissionSub.PamFolders,
ProjectPermissionSub.PamResources,
ProjectPermissionSub.PamDomains,
@@ -1513,6 +1525,25 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
return;
}
+ if (subject === ProjectPermissionSub.HsmConnectors) {
+ const canRead = action.includes(ProjectPermissionHsmConnectorActions.Read);
+ const canCreate = action.includes(ProjectPermissionHsmConnectorActions.Create);
+ const canEdit = action.includes(ProjectPermissionHsmConnectorActions.Edit);
+ const canDelete = action.includes(ProjectPermissionHsmConnectorActions.Delete);
+ const canTest = action.includes(ProjectPermissionHsmConnectorActions.Test);
+ const canAttach = action.includes(ProjectPermissionHsmConnectorActions.Attach);
+
+ if (!formVal[subject]) formVal[subject] = [{}];
+
+ if (canRead) formVal[subject]![0][ProjectPermissionHsmConnectorActions.Read] = true;
+ if (canCreate) formVal[subject]![0][ProjectPermissionHsmConnectorActions.Create] = true;
+ if (canEdit) formVal[subject]![0][ProjectPermissionHsmConnectorActions.Edit] = true;
+ if (canDelete) formVal[subject]![0][ProjectPermissionHsmConnectorActions.Delete] = true;
+ if (canTest) formVal[subject]![0][ProjectPermissionHsmConnectorActions.Test] = true;
+ if (canAttach) formVal[subject]![0][ProjectPermissionHsmConnectorActions.Attach] = true;
+ return;
+ }
+
if (subject === ProjectPermissionSub.PkiDiscovery) {
const canRead = action.includes(ProjectPermissionPkiDiscoveryActions.Read);
const canCreate = action.includes(ProjectPermissionPkiDiscoveryActions.Create);
@@ -3244,6 +3275,43 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {
}
]
},
+ [ProjectPermissionSub.HsmConnectors]: {
+ title: "HSM Connectors",
+ description: "Manage HSM Connectors that bridge Infisical to your HSM",
+ actions: [
+ {
+ label: "Read",
+ value: ProjectPermissionHsmConnectorActions.Read,
+ description: "View HSM Connectors and their configuration (PIN is never returned)"
+ },
+ {
+ label: "Create",
+ value: ProjectPermissionHsmConnectorActions.Create,
+ description: "Create a new HSM Connector"
+ },
+ {
+ label: "Update",
+ value: ProjectPermissionHsmConnectorActions.Edit,
+ description: "Edit name, description, key name prefix, routing, or rotate the PIN"
+ },
+ {
+ label: "Delete",
+ value: ProjectPermissionHsmConnectorActions.Delete,
+ description: "Delete an HSM Connector (blocked if any certificate references it)"
+ },
+ {
+ label: "Verify",
+ value: ProjectPermissionHsmConnectorActions.Test,
+ description: "Verify the connector reaches the HSM through the gateway"
+ },
+ {
+ label: "Attach",
+ value: ProjectPermissionHsmConnectorActions.Attach,
+ description:
+ "Attach an HSM Connector when issuing a certificate (mints a fresh keypair on the HSM)"
+ }
+ ]
+ },
[ProjectPermissionSub.PamFolders]: {
title: "Folders",
description: "Organize PAM resources into folders",
@@ -3584,7 +3652,8 @@ const CertificateManagerPermissionSubjects = (enabled = false) => ({
[ProjectPermissionSub.Certificates]: enabled,
[ProjectPermissionSub.PkiDiscovery]: enabled,
[ProjectPermissionSub.PkiCertificateInstallations]: enabled,
- [ProjectPermissionSub.CodeSigners]: enabled
+ [ProjectPermissionSub.CodeSigners]: enabled,
+ [ProjectPermissionSub.HsmConnectors]: enabled
});
const SshPermissionSubjects = (enabled = false) => ({
diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.ts
index 0cc193320d..1012df91e0 100644
--- a/frontend/src/routeTree.gen.ts
+++ b/frontend/src/routeTree.gen.ts
@@ -173,6 +173,7 @@ import { Route as pamPamSessionsByIDPageRouteImport } from './pages/pam/PamSessi
import { Route as pamApprovalRequestDetailPageRouteImport } from './pages/pam/ApprovalRequestDetailPage/route'
import { Route as certManagerPkiSubscriberDetailsByIDPageRouteImport } from './pages/cert-manager/PkiSubscriberDetailsByIDPage/route'
import { Route as certManagerPkiSyncDetailsByIDPageRouteImport } from './pages/cert-manager/PkiSyncDetailsByIDPage/route'
+import { Route as certManagerHsmConnectorDetailsByIDPageRouteImport } from './pages/cert-manager/HsmConnectorDetailsByIDPage/route'
import { Route as certManagerDiscoveryDetailsByIDPageRouteImport } from './pages/cert-manager/DiscoveryDetailsByIDPage/route'
import { Route as certManagerSignerDetailPageRouteImport } from './pages/cert-manager/SignerDetailPage/route'
import { Route as certManagerCertificateDetailsByIDPageRouteImport } from './pages/cert-manager/CertificateDetailsByIDPage/route'
@@ -1872,6 +1873,13 @@ const certManagerPkiSyncDetailsByIDPageRouteRoute =
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutIntegrationsRoute,
} as any)
+const certManagerHsmConnectorDetailsByIDPageRouteRoute =
+ certManagerHsmConnectorDetailsByIDPageRouteImport.update({
+ id: '/hsm-connectors/$connectorId',
+ path: '/hsm-connectors/$connectorId',
+ getParentRoute: () => certManagerLayoutRoute,
+ } as any)
+
const certManagerDiscoveryDetailsByIDPageRouteRoute =
certManagerDiscoveryDetailsByIDPageRouteImport.update({
id: '/$discoveryId',
@@ -4111,6 +4119,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof certManagerDiscoveryDetailsByIDPageRouteImport
parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutDiscoveryImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/hsm-connectors/$connectorId': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/hsm-connectors/$connectorId'
+ path: '/hsm-connectors/$connectorId'
+ fullPath: '/organizations/$orgId/projects/cert-manager/$projectId/hsm-connectors/$connectorId'
+ preLoaderRoute: typeof certManagerHsmConnectorDetailsByIDPageRouteImport
+ parentRoute: typeof certManagerLayoutImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/integrations/$syncId': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/integrations/$syncId'
path: '/$syncId'
@@ -5295,6 +5310,7 @@ interface certManagerLayoutRouteChildren {
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutSubscribersRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutSubscribersRouteWithChildren
certManagerCertAuthDetailsByIDPageRouteRoute: typeof certManagerCertAuthDetailsByIDPageRouteRoute
certManagerCertificateDetailsByIDPageRouteRoute: typeof certManagerCertificateDetailsByIDPageRouteRoute
+ certManagerHsmConnectorDetailsByIDPageRouteRoute: typeof certManagerHsmConnectorDetailsByIDPageRouteRoute
projectGroupDetailsByIDPageRouteCertManagerRoute: typeof projectGroupDetailsByIDPageRouteCertManagerRoute
projectIdentityDetailsByIDPageRouteCertManagerRoute: typeof projectIdentityDetailsByIDPageRouteCertManagerRoute
projectMemberDetailsByIDPageRouteCertManagerRoute: typeof projectMemberDetailsByIDPageRouteCertManagerRoute
@@ -5341,6 +5357,8 @@ const certManagerLayoutRouteChildren: certManagerLayoutRouteChildren = {
certManagerCertAuthDetailsByIDPageRouteRoute,
certManagerCertificateDetailsByIDPageRouteRoute:
certManagerCertificateDetailsByIDPageRouteRoute,
+ certManagerHsmConnectorDetailsByIDPageRouteRoute:
+ certManagerHsmConnectorDetailsByIDPageRouteRoute,
projectGroupDetailsByIDPageRouteCertManagerRoute:
projectGroupDetailsByIDPageRouteCertManagerRoute,
projectIdentityDetailsByIDPageRouteCertManagerRoute:
@@ -6663,6 +6681,7 @@ export interface FileRoutesByFullPath {
'/organizations/$orgId/projects/cert-manager/$projectId/certificates/$certificateId': typeof certManagerCertificateDetailsByIDPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/code-signing/$signerId': typeof certManagerSignerDetailPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/discovery/$discoveryId': typeof certManagerDiscoveryDetailsByIDPageRouteRoute
+ '/organizations/$orgId/projects/cert-manager/$projectId/hsm-connectors/$connectorId': typeof certManagerHsmConnectorDetailsByIDPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/integrations/$syncId': typeof certManagerPkiSyncDetailsByIDPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/subscribers/$subscriberName': typeof certManagerPkiSubscriberDetailsByIDPageRouteRoute
'/organizations/$orgId/projects/pam/$projectId/approvals/$approvalRequestId': typeof pamApprovalRequestDetailPageRouteRoute
@@ -6941,6 +6960,7 @@ export interface FileRoutesByTo {
'/organizations/$orgId/projects/cert-manager/$projectId/certificates/$certificateId': typeof certManagerCertificateDetailsByIDPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/code-signing/$signerId': typeof certManagerSignerDetailPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/discovery/$discoveryId': typeof certManagerDiscoveryDetailsByIDPageRouteRoute
+ '/organizations/$orgId/projects/cert-manager/$projectId/hsm-connectors/$connectorId': typeof certManagerHsmConnectorDetailsByIDPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/integrations/$syncId': typeof certManagerPkiSyncDetailsByIDPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/subscribers/$subscriberName': typeof certManagerPkiSubscriberDetailsByIDPageRouteRoute
'/organizations/$orgId/projects/pam/$projectId/approvals/$approvalRequestId': typeof pamApprovalRequestDetailPageRouteRoute
@@ -7252,6 +7272,7 @@ export interface FileRoutesById {
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificates/$certificateId': typeof certManagerCertificateDetailsByIDPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/code-signing/$signerId': typeof certManagerSignerDetailPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/discovery/$discoveryId': typeof certManagerDiscoveryDetailsByIDPageRouteRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/hsm-connectors/$connectorId': typeof certManagerHsmConnectorDetailsByIDPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/integrations/$syncId': typeof certManagerPkiSyncDetailsByIDPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/subscribers/$subscriberName': typeof certManagerPkiSubscriberDetailsByIDPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/approvals/$approvalRequestId': typeof pamApprovalRequestDetailPageRouteRoute
@@ -7558,6 +7579,7 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/cert-manager/$projectId/certificates/$certificateId'
| '/organizations/$orgId/projects/cert-manager/$projectId/code-signing/$signerId'
| '/organizations/$orgId/projects/cert-manager/$projectId/discovery/$discoveryId'
+ | '/organizations/$orgId/projects/cert-manager/$projectId/hsm-connectors/$connectorId'
| '/organizations/$orgId/projects/cert-manager/$projectId/integrations/$syncId'
| '/organizations/$orgId/projects/cert-manager/$projectId/subscribers/$subscriberName'
| '/organizations/$orgId/projects/pam/$projectId/approvals/$approvalRequestId'
@@ -7835,6 +7857,7 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/cert-manager/$projectId/certificates/$certificateId'
| '/organizations/$orgId/projects/cert-manager/$projectId/code-signing/$signerId'
| '/organizations/$orgId/projects/cert-manager/$projectId/discovery/$discoveryId'
+ | '/organizations/$orgId/projects/cert-manager/$projectId/hsm-connectors/$connectorId'
| '/organizations/$orgId/projects/cert-manager/$projectId/integrations/$syncId'
| '/organizations/$orgId/projects/cert-manager/$projectId/subscribers/$subscriberName'
| '/organizations/$orgId/projects/pam/$projectId/approvals/$approvalRequestId'
@@ -8144,6 +8167,7 @@ export interface FileRouteTypes {
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificates/$certificateId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/code-signing/$signerId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/discovery/$discoveryId'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/hsm-connectors/$connectorId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/integrations/$syncId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/subscribers/$subscriberName'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/approvals/$approvalRequestId'
@@ -8857,6 +8881,7 @@ export const routeTree = rootRoute
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/subscribers",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/ca/$caId",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificates/$certificateId",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/hsm-connectors/$connectorId",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/groups/$groupId",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/identities/$identityId",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/members/$membershipId",
@@ -9438,6 +9463,10 @@ export const routeTree = rootRoute
"filePath": "cert-manager/DiscoveryDetailsByIDPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/discovery"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/hsm-connectors/$connectorId": {
+ "filePath": "cert-manager/HsmConnectorDetailsByIDPage/route.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout"
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/integrations/$syncId": {
"filePath": "cert-manager/PkiSyncDetailsByIDPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/integrations"
diff --git a/frontend/src/routes.ts b/frontend/src/routes.ts
index 67a970536d..2964dd4489 100644
--- a/frontend/src/routes.ts
+++ b/frontend/src/routes.ts
@@ -313,6 +313,7 @@ const certManagerRoutes = route("/organizations/$orgId/projects/cert-manager/$pr
route("/$policyId", "cert-manager/CertificatePolicyDetailsByIDPage/route.tsx")
]),
route("/certificates/$certificateId", "cert-manager/CertificateDetailsByIDPage/route.tsx"),
+ route("/hsm-connectors/$connectorId", "cert-manager/HsmConnectorDetailsByIDPage/route.tsx"),
route("/pki-collections/$collectionId", "cert-manager/PkiCollectionDetailsByIDPage/routes.tsx"),
route("/integrations", [
index("cert-manager/IntegrationsListPage/route.tsx"),