Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(pki): support ML-DSA keys for HSM-backed internal CAs
Carlos Monastyrski56d806580eca
diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.tsindex 7fa3945120..2fe48aa528 100644--- a/backend/src/ee/routes/v2/gateway-router.ts+++ b/backend/src/ee/routes/v2/gateway-router.ts@@ -137,6 +137,7 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {capabilities: z.object({pkcs11: z.boolean().optional(),+ pkcs11MlDsa: z.boolean().optional(),sessionLogMaskingBuiltInDetection: z.boolean().optional(),clickhouseNativeProtocol: z.boolean().optional(),certificateScan: z.boolean().optional(),diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.tsindex 0157562c71..b3de3cd03c 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts@@ -1055,6 +1055,7 @@ export const gatewayV2ServiceFactory = ({orgPermission: OrgServiceActor;capabilities?: {pkcs11?: boolean;+ pkcs11MlDsa?: boolean;sessionLogMaskingBuiltInDetection?: boolean;clickhouseNativeProtocol?: boolean;certificateScan?: boolean;diff --git a/backend/src/lib/csr/pkcs11-algorithm-map.ts b/backend/src/lib/csr/pkcs11-algorithm-map.tsindex aa3bb1ab87..74aac3a93d 100644--- a/backend/src/lib/csr/pkcs11-algorithm-map.ts+++ b/backend/src/lib/csr/pkcs11-algorithm-map.ts@@ -9,7 +9,8 @@ export enum Pkcs11Mechanism {Sha512RsaPkcs = "CKM_SHA512_RSA_PKCS",Ecdsa = "CKM_ECDSA",EcdsaSha256 = "CKM_ECDSA_SHA256",- EcdsaSha384 = "CKM_ECDSA_SHA384"+ EcdsaSha384 = "CKM_ECDSA_SHA384",+ MlDsa = "CKM_ML_DSA"}export type Pkcs11SigningMechanism = {diff --git a/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.test.ts b/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.test.tsindex 5a9a39b25b..9b3d6e612d 100644--- a/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.test.ts+++ b/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.test.ts@@ -443,7 +443,7 @@ describe("AWS KMS CA key source", () => {keySource: CertKeySource.Hsm,projectId: "project",caName: "root-ca",- keyAlgorithm: CertKeyAlgorithm.ML_DSA_65,+ keyAlgorithm: CertKeyAlgorithm.ECDSA_P521,input: { hsmConnectorId: "connector" }})).rejects.toThrow(/not supported for HSM-backed/);diff --git a/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.ts b/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.tsindex 4088420c59..4590e3ba22 100644--- a/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.ts+++ b/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.ts@@ -16,7 +16,7 @@ import { ProjectType } from "@app/db/schemas";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { CustomAWSHasher } from "@app/lib/aws/hashing";import { crypto } from "@app/lib/crypto/cryptography";-import { getPqcCrypto, isPqcAlgorithm } from "@app/lib/crypto/pqc";+import { isPqcAlgorithm } from "@app/lib/crypto/pqc";import { bufferToArrayBuffer } from "@app/lib/csr/pkcs11-algorithm-map";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";@@ -32,7 +32,12 @@ import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TProjectDALFactory } from "@app/services/project/project-dal";-import { algorithmHashName, buildExternalCaSigner, createEphemeralKeyCache } from "../ca-signer";+import {+ algorithmHashName,+ buildExternalCaSigner,+ buildPqcExternalCaSigner,+ createEphemeralKeyCache+} from "../ca-signer";import { keyAlgorithmToAlgCfg } from "../certificate-authority-fns";import {AWS_KMS_KEY_SPEC_BY_ALGORITHM,@@ -205,17 +210,12 @@ export const awsKmsCaKeySourceFactory = ({const keyAlgCfg = keyAlgorithmToAlgCfg(keyAlgorithm);if (isPqcAlgorithm(keyAlgorithm)) {- const pqcCrypto = getPqcCrypto();- const caPublicKey = await pqcCrypto.subtle.importKey("spki", publicKeySpki, keyAlgCfg, true, ["verify"]);const rawPublicKey = new Uint8Array(AsnConvert.parse(publicKeySpki, SubjectPublicKeyInfo).subjectPublicKey);- return buildExternalCaSigner({- caPublicKey,- signingAlgorithm: keyAlgCfg,- generateEphemeralKey: () =>- ephemeralKeys(keyAlgCfg, () =>- pqcCrypto.subtle.generateKey(keyAlgCfg as RsaHashedKeyGenParams, true, ["sign", "verify"])- ),+ return buildPqcExternalCaSigner({+ keyAlgCfg,+ publicKeySpki,+ ephemeralKeys,signTbs: (tbs) =>sign(computeMlDsaExternalMu(rawPublicKey, tbs),diff --git a/backend/src/services/certificate-authority/ca-key-source/hsm-ca-key-source.test.ts b/backend/src/services/certificate-authority/ca-key-source/hsm-ca-key-source.test.tsnew file mode 100644index 0000000000..268b7e85d0--- /dev/null+++ b/backend/src/services/certificate-authority/ca-key-source/hsm-ca-key-source.test.ts@@ -0,0 +1,136 @@+import { execFileSync } from "node:child_process";+import { webcrypto } from "node:crypto";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import * as x509 from "@peculiar/x509";++import { crypto } from "@app/lib/crypto/cryptography";+import { initializePqcSupport } from "@app/lib/crypto/pqc";+import {+ opensslDerivePublicKey,+ opensslGenpkey,+ opensslSign,+ verifyPqcOpenSSLAvailability+} from "@app/lib/crypto/pqc/pqc-openssl";+import { BadRequestError } from "@app/lib/errors";+import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";++import { hsmCaKeySourceFactory } from "./hsm-ca-key-source";++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }+}));++const PQC_OPENSSL_BIN = process.env.PQC_OPENSSL_BIN_PATH || "/opt/openssl-pqc/bin/openssl";+const PQC_OPENSSL_LIB = process.env.PQC_OPENSSL_LIB_PATH || "/opt/openssl-pqc/lib64:/opt/openssl-pqc/lib";++const runPqcOpenssl = (args: (dir: string) => string[], files: Record<string, Buffer | string>) => {+ const dir = mkdtempSync(join(tmpdir(), "hsm-ca-"));+ try {+ Object.entries(files).forEach(([name, content]) => writeFileSync(join(dir, name), content));+ const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("OPENSSL_")));+ return execFileSync(PQC_OPENSSL_BIN, args(dir), {+ env: { ...env, LD_LIBRARY_PATH: [PQC_OPENSSL_LIB, process.env.LD_LIBRARY_PATH].filter(Boolean).join(":") }+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+};++type TSignCall = { mechanism: string; isDigest: boolean; data: Buffer };++const fakeMlDsaHsm = async (algorithm: string) => {+ const privateKeyDer = await opensslGenpkey(algorithm);+ const publicKeySpkiDer = await opensslDerivePublicKey(privateKeyDer);+ const generateCalls: Record<string, unknown>[] = [];+ const signCalls: TSignCall[] = [];+ const hsmConnectorService = {+ assertAttachPermission: vi.fn(),+ generateKeyPair: vi.fn(async (args: Record<string, unknown>) => {+ generateCalls.push(args);+ return { keyLabel: "ca-root-abcde", keyId: "0a0b", publicKeySpkiDer };+ }),+ sign: vi.fn(async ({ mechanism, isDigest, data }: TSignCall) => {+ signCalls.push({ mechanism, isDigest, data });+ return opensslSign(privateKeyDer, data);+ })+ };+ return { hsmConnectorService, generateCalls, signCalls };+};++describe("HSM CA key source", () => {+ let isOpensslAvailable = false;++ beforeAll(async () => {+ await crypto.initialize({} as never, {} as never, {} as never);+ isOpensslAvailable = await verifyPqcOpenSSLAvailability();+ });++ test("explains an ML-DSA key the Gateway or HSM cannot create", async () => {+ const provider = hsmCaKeySourceFactory({+ hsmConnectorService: {+ generateKeyPair: vi.fn(async () => {+ throw new BadRequestError({+ message: "PKCS#11 request failed (mechanism_invalid): Mechanism not supported by this HSM"+ });+ })+ } as never,+ hsmConnectorDAL: { findById: vi.fn() } as never+ });++ await expect(+ provider.createKey({+ projectId: "project",+ caName: "root",+ keyAlgorithm: CertKeyAlgorithm.ML_DSA_44,+ input: { hsmConnectorId: "connector" }+ })+ ).rejects.toThrow(/could not create an ML-DSA-44 key\. Update the Gateway to v0\.44\.10 or later/);+ });++ test("ML-DSA certificates signed through the HSM with CKM_ML_DSA verify against the HSM public key", async ({+ skip+ }) => {+ if (!isOpensslAvailable) skip();+ await initializePqcSupport();+ try {+ const { hsmConnectorService, generateCalls, signCalls } = await fakeMlDsaHsm("ML-DSA-65");+ const provider = hsmCaKeySourceFactory({+ hsmConnectorService: hsmConnectorService as never,+ hsmConnectorDAL: { findById: vi.fn() } as never+ });++ const reference = await provider.createKey({+ projectId: "project",+ caName: "root",+ keyAlgorithm: CertKeyAlgorithm.ML_DSA_65,+ input: { hsmConnectorId: "connector" }+ });+ const signer = await provider.buildSigner({+ projectId: "project",+ keyAlgorithm: CertKeyAlgorithm.ML_DSA_65,+ reference+ });+ const certificate = await signer.createCertificate({+ subject: "CN=Root CA",+ issuer: "CN=Root CA",+ serialNumber: "01",+ notBefore: new Date(),+ notAfter: new Date(Date.now() + 86_400_000),+ publicKey: signer.caPublicKey+ });++ expect(generateCalls[0]).toMatchObject({ keyAlgorithm: "ML_DSA_65" });+ expect(signCalls[0]).toMatchObject({ mechanism: "CKM_ML_DSA", isDigest: false });+ const verified = runPqcOpenssl(+ (dir) => ["verify", "-check_ss_sig", "-CAfile", join(dir, "cert.pem"), join(dir, "cert.pem")],+ { "cert.pem": certificate.toString("pem") }+ ).toString();+ expect(verified).toContain("OK");+ } finally {+ x509.cryptoProvider.set(webcrypto as unknown as Crypto);+ }+ });+});diff --git a/backend/src/services/certificate-authority/ca-key-source/hsm-ca-key-source.ts b/backend/src/services/certificate-authority/ca-key-source/hsm-ca-key-source.tsindex 36fb4a51a1..826708b8b4 100644--- a/backend/src/services/certificate-authority/ca-key-source/hsm-ca-key-source.ts+++ b/backend/src/services/certificate-authority/ca-key-source/hsm-ca-key-source.ts@@ -1,11 +1,24 @@import { crypto } from "@app/lib/crypto/cryptography";+import { isPqcAlgorithm } from "@app/lib/crypto/pqc";+import { bufferToArrayBuffer, Pkcs11Mechanism } from "@app/lib/csr/pkcs11-algorithm-map";import { BadRequestError } from "@app/lib/errors";+import { isPkcs11Error, Pkcs11ErrorCode } from "@app/lib/gateway-v2/pkcs11-rpc";import { alphaNumericNanoId } from "@app/lib/nanoid";import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";import { THsmConnectorDALFactory } from "@app/services/hsm-connector/hsm-connector-dal";+import {+ certKeyAlgorithmToHsmKeyAlgorithm,+ HSM_ML_DSA_MIN_GATEWAY_VERSION+} from "@app/services/hsm-connector/hsm-connector-fns";import { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";-import { buildHsmCaSigner, caKeyAlgorithmToHsmShape, createEphemeralKeyCache } from "../ca-signer";+import {+ buildHsmCaSigner,+ buildPqcExternalCaSigner,+ caKeyAlgorithmToHsmShape,+ createEphemeralKeyCache+} from "../ca-signer";+import { keyAlgorithmToAlgCfg } from "../certificate-authority-fns";import { TExternalCaKeyInput, TExternalCaKeyProvider } from "./ca-key-source-types";type THsmCaKeySourceDep = {@@ -32,7 +45,10 @@ export const hsmCaKeySourceFactory = ({CertKeyAlgorithm.RSA_2048,CertKeyAlgorithm.RSA_4096,CertKeyAlgorithm.ECDSA_P256,- CertKeyAlgorithm.ECDSA_P384+ CertKeyAlgorithm.ECDSA_P384,+ CertKeyAlgorithm.ML_DSA_44,+ CertKeyAlgorithm.ML_DSA_65,+ CertKeyAlgorithm.ML_DSA_87],assertCanUse: async ({ actor, projectId, input }) => {@@ -41,12 +57,27 @@ export const hsmCaKeySourceFactory = ({createKey: async ({ projectId, caName, keyAlgorithm, input }) => {const hsmConnectorId = requireHsmConnectorId(input);- const generated = await hsmConnectorService.generateKeyPair({- connectorId: hsmConnectorId,- projectId,- keyLabel: `ca-${caName}-${alphaNumericNanoId(5)}`,- keyAlgorithm: caKeyAlgorithmToHsmShape(keyAlgorithm).hsmKeyAlgorithm- });+ const hsmKeyAlgorithm = certKeyAlgorithmToHsmKeyAlgorithm(keyAlgorithm);+ if (!hsmKeyAlgorithm) {+ throw new BadRequestError({+ message: `Key algorithm "${keyAlgorithm}" is not supported for HSM-backed certificate authorities.`+ });+ }+ const generated = await hsmConnectorService+ .generateKeyPair({+ connectorId: hsmConnectorId,+ projectId,+ keyLabel: `ca-${caName}-${alphaNumericNanoId(5)}`,+ keyAlgorithm: hsmKeyAlgorithm+ })+ .catch((err: unknown) => {+ if (isPqcAlgorithm(keyAlgorithm) && isPkcs11Error(err, Pkcs11ErrorCode.MechanismInvalid)) {+ throw new BadRequestError({+ message: `The HSM Connector could not create an ${keyAlgorithm} key. Update the Gateway to ${HSM_ML_DSA_MIN_GATEWAY_VERSION} or later and check that your HSM's PKCS#11 driver supports ML-DSA.`+ });+ }+ throw err;+ });return {hsmConnectorId,externalKeyId: generated.keyLabel,@@ -75,6 +106,27 @@ export const hsmCaKeySourceFactory = ({});}+ const hsmSign = (data: Buffer, mechanism: string, isDigest: boolean) =>+ hsmConnectorService.sign({+ connectorId: hsmConnectorId,+ projectId,+ keyLabel,+ keyId: hsmKeyId,+ publicKeySpki,+ mechanism,+ data,+ isDigest+ });++ if (isPqcAlgorithm(keyAlgorithm)) {+ return buildPqcExternalCaSigner({+ keyAlgCfg: keyAlgorithmToAlgCfg(keyAlgorithm),+ publicKeySpki,+ ephemeralKeys,+ signTbs: async (tbs) => bufferToArrayBuffer(await hsmSign(tbs, Pkcs11Mechanism.MlDsa, false))+ });+ }+const caPublicKey = await crypto.nativeCrypto.subtle.importKey("spki",publicKeySpki,@@ -87,17 +139,7 @@ export const hsmCaKeySourceFactory = ({caPublicKey,keyAlgorithm,signingAlgorithm: signatureAlgorithm,- sign: (data, mechanism, isDigest) =>- hsmConnectorService.sign({- connectorId: hsmConnectorId,- projectId,- keyLabel,- keyId: hsmKeyId,- publicKeySpki,- mechanism,- data,- isDigest- }),+ sign: hsmSign,ephemeralKeys});}diff --git a/backend/src/services/certificate-authority/ca-signer.ts b/backend/src/services/certificate-authority/ca-signer.tsindex 7d747dd1a6..7bc18b821b 100644--- a/backend/src/services/certificate-authority/ca-signer.ts+++ b/backend/src/services/certificate-authority/ca-signer.ts@@ -4,6 +4,7 @@ import { Certificate, CertificateList } from "@peculiar/asn1-x509";import * as x509 from "@peculiar/x509";import { crypto } from "@app/lib/crypto/cryptography";+import { getPqcCrypto } from "@app/lib/crypto/pqc";import { bufferToArrayBuffer, ecdsaRawRsToDer } from "@app/lib/csr/pkcs11-algorithm-map";import { BadRequestError } from "@app/lib/errors";import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";@@ -34,7 +35,6 @@ export type TCaSigner = {export type TCaExternalSignFn = (tbs: Buffer, mechanism: string, isDigest: boolean) => Promise<Buffer>;type TCaHsmShape = {- hsmKeyAlgorithm: HsmKeyAlgorithm;mechanism: string;isEcdsa: boolean;signingAlgorithm: Algorithm;@@ -48,7 +48,6 @@ export const caKeyAlgorithmToHsmShape = (keyAlgorithm: CertKeyAlgorithm | stringswitch (keyAlgorithm) {case CertKeyAlgorithm.RSA_2048:return {- hsmKeyAlgorithm: HsmKeyAlgorithm.RSA_2048,mechanism: "CKM_SHA256_RSA_PKCS",isEcdsa: false,signingAlgorithm: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" } as Algorithm,@@ -63,7 +62,6 @@ export const caKeyAlgorithmToHsmShape = (keyAlgorithm: CertKeyAlgorithm | stringcase CertKeyAlgorithm.RSA_4096:// SHA-256 (not SHA-384) to match keyAlgorithmToAlgCfg, so RSA_4096 signs identically to local CAs.return {- hsmKeyAlgorithm: HsmKeyAlgorithm.RSA_4096,mechanism: "CKM_SHA256_RSA_PKCS",isEcdsa: false,signingAlgorithm: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" } as Algorithm,@@ -77,7 +75,6 @@ export const caKeyAlgorithmToHsmShape = (keyAlgorithm: CertKeyAlgorithm | string};case CertKeyAlgorithm.ECDSA_P256:return {- hsmKeyAlgorithm: HsmKeyAlgorithm.ECC_P256,mechanism: "CKM_ECDSA_SHA256",isEcdsa: true,signingAlgorithm: { name: "ECDSA", hash: "SHA-256" } as Algorithm,@@ -86,7 +83,6 @@ export const caKeyAlgorithmToHsmShape = (keyAlgorithm: CertKeyAlgorithm | string};case CertKeyAlgorithm.ECDSA_P384:return {- hsmKeyAlgorithm: HsmKeyAlgorithm.ECC_P384,mechanism: "CKM_ECDSA_SHA384",isEcdsa: true,signingAlgorithm: { name: "ECDSA", hash: "SHA-384" } as Algorithm,@@ -215,6 +211,30 @@ export const buildExternalCaSigner = ({signTbs});+export const buildPqcExternalCaSigner = async ({+ keyAlgCfg,+ publicKeySpki,+ ephemeralKeys,+ signTbs+}: {+ keyAlgCfg: Algorithm;+ publicKeySpki: Buffer;+ ephemeralKeys: TEphemeralKeyCache;+ signTbs: (tbs: Buffer) => Promise<ArrayBuffer>;+}): Promise<TCaSigner> => {+ const pqcCrypto = getPqcCrypto();+ const caPublicKey = await pqcCrypto.subtle.importKey("spki", publicKeySpki, keyAlgCfg, true, ["verify"]);+ return buildExternalCaSigner({+ caPublicKey,+ signingAlgorithm: keyAlgCfg,+ generateEphemeralKey: () =>+ ephemeralKeys(keyAlgCfg, () =>+ pqcCrypto.subtle.generateKey(keyAlgCfg as RsaHashedKeyGenParams, true, ["sign", "verify"])+ ),+ signTbs+ });+};+export const buildHsmCaSigner = ({caPublicKey,keyAlgorithm,diff --git a/backend/src/services/hsm-connector/hsm-connector-fns.ts b/backend/src/services/hsm-connector/hsm-connector-fns.tsindex e2b01f7389..686eb2fa2b 100644--- a/backend/src/services/hsm-connector/hsm-connector-fns.ts+++ b/backend/src/services/hsm-connector/hsm-connector-fns.ts@@ -1,6 +1,8 @@import { z } from "zod";+import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";import { KmsDataKey } from "@app/services/kms/kms-types";+import { HsmKeyAlgorithm } from "@app/services/signer/signer-enums";import type { THsmConnectorServiceFactoryDep } from "./hsm-connector-service";import type { THsmConnectorCredentials } from "./hsm-connector-types";@@ -17,6 +19,26 @@ export const HsmKeyLabelSchema = z`Key label must be at most ${HSM_KEY_LABEL_MAX_BYTES} bytes`);+export enum HsmGatewayCapability {+ MlDsa = "pkcs11MlDsa"+}++export const HSM_ML_DSA_MIN_GATEWAY_VERSION = "v0.44.10";++const HSM_KEY_ALGORITHM_BY_CERT_KEY_ALGORITHM: Partial<Record<string, HsmKeyAlgorithm>> = {+ [CertKeyAlgorithm.RSA_2048]: HsmKeyAlgorithm.RSA_2048,+ [CertKeyAlgorithm.RSA_3072]: HsmKeyAlgorithm.RSA_3072,+ [CertKeyAlgorithm.RSA_4096]: HsmKeyAlgorithm.RSA_4096,+ [CertKeyAlgorithm.ECDSA_P256]: HsmKeyAlgorithm.ECC_P256,+ [CertKeyAlgorithm.ECDSA_P384]: HsmKeyAlgorithm.ECC_P384,+ [CertKeyAlgorithm.ML_DSA_44]: HsmKeyAlgorithm.ML_DSA_44,+ [CertKeyAlgorithm.ML_DSA_65]: HsmKeyAlgorithm.ML_DSA_65,+ [CertKeyAlgorithm.ML_DSA_87]: HsmKeyAlgorithm.ML_DSA_87+};++export const certKeyAlgorithmToHsmKeyAlgorithm = (keyAlgorithm: string): HsmKeyAlgorithm | undefined =>+ HSM_KEY_ALGORITHM_BY_CERT_KEY_ALGORITHM[keyAlgorithm];+export const HSM_CREDENTIALS_LIMITS = {slotLabelMax: 128,pinMax: 512,diff --git a/backend/src/services/hsm-connector/hsm-connector-routing.test.ts b/backend/src/services/hsm-connector/hsm-connector-routing.test.tsnew file mode 100644index 0000000000..5d3831e397--- /dev/null+++ b/backend/src/services/hsm-connector/hsm-connector-routing.test.ts@@ -0,0 +1,121 @@+import { BadRequestError } from "@app/lib/errors";++import { HsmGatewayCapability } from "./hsm-connector-fns";+import { hsmConnectorRoutingFactory } from "./hsm-connector-routing";++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }+}));++vi.mock("@app/lib/gateway-v2/gateway-v2", () => ({+ withGatewayV2Proxy: vi.fn(async (fn: (port: number) => Promise<unknown>) => fn(1))+}));++vi.mock("@app/lib/gateway-v2/pkcs11-rpc", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@app/lib/gateway-v2/pkcs11-rpc")>()),+ callPkcs11Endpoint: vi.fn(async () => ({ ok: true, status: 200, result: { signature: "c2ln" } }))+}));++type TPoolGateway = { id: string; capabilities: Record<string, unknown> };++const buildRouting = (members: TPoolGateway[], healthyIds?: string[]) => {+ const healthy = members.filter((member) => !healthyIds || healthyIds.includes(member.id));+ const selectGatewayFromPool = vi.fn(+ async ({+ exclude,+ filter,+ unavailableMessage+ }: {+ exclude: Set<string>;+ filter: (gateway: TPoolGateway) => boolean;+ unavailableMessage: string;+ }) => {+ const candidate = healthy.find((member) => !exclude.has(member.id) && filter(member));+ if (!candidate) throw new BadRequestError({ message: unavailableMessage });+ return candidate;+ }+ );+ const getPlatformConnectionDetailsByGatewayId = vi.fn(async ({ gatewayId }: { gatewayId: string }) => ({+ gatewayId+ }));+ const routing = hsmConnectorRoutingFactory({+ gatewayV2Service: { getPlatformConnectionDetailsByGatewayId } as never,+ gatewayV2DAL: { findById: vi.fn(async (id: string) => members.find((member) => member.id === id)) } as never,+ gatewayPoolService: { selectGatewayFromPool, listHealthyGateways: vi.fn(async () => healthy) } as never+ });+ return { routing, getPlatformConnectionDetailsByGatewayId };+};++const signThroughPool = (+ routing: ReturnType<typeof buildRouting>["routing"],+ requiredCapability?: HsmGatewayCapability,+ connector: { gatewayId: string | null; gatewayPoolId: string | null } = { gatewayId: null, gatewayPoolId: "pool" }+) =>+ routing.dispatchPkcs11({+ connector,+ credentials: { slotLabel: "slot", pin: "pin" },+ endpoint: "/v1/sign",+ params: {},+ requiredCapability+ });++describe("HSM Connector routing", () => {+ test("ML-DSA operations skip pool members that do not advertise ML-DSA support", async () => {+ const { routing, getPlatformConnectionDetailsByGatewayId } = buildRouting([+ { id: "old-gateway", capabilities: { pkcs11: true } },+ { id: "new-gateway", capabilities: { pkcs11: true, pkcs11MlDsa: true } }+ ]);++ await signThroughPool(routing, HsmGatewayCapability.MlDsa);++ expect(getPlatformConnectionDetailsByGatewayId).toHaveBeenCalledTimes(1);+ expect(getPlatformConnectionDetailsByGatewayId.mock.calls[0][0]).toMatchObject({ gatewayId: "new-gateway" });+ });++ test("explains a pool with no member that supports ML-DSA", async () => {+ const { routing } = buildRouting([{ id: "old-gateway", capabilities: { pkcs11: true } }]);++ await expect(signThroughPool(routing, HsmGatewayCapability.MlDsa)).rejects.toThrow(+ /No HSM-capable gateway in the pool supports ML-DSA keys/+ );+ });++ test("an offline pool is reported as offline, not as needing an upgrade", async () => {+ const { routing } = buildRouting([{ id: "new-gateway", capabilities: { pkcs11: true, pkcs11MlDsa: true } }], []);++ await expect(signThroughPool(routing, HsmGatewayCapability.MlDsa)).rejects.toThrow(+ /No HSM-capable gateway available in the pool/+ );+ });++ test("a single gateway without ML-DSA support is refused before it is dialed", async () => {+ const { routing, getPlatformConnectionDetailsByGatewayId } = buildRouting([+ { id: "old-gateway", capabilities: { pkcs11: true } }+ ]);++ await expect(+ signThroughPool(routing, HsmGatewayCapability.MlDsa, { gatewayId: "old-gateway", gatewayPoolId: null })+ ).rejects.toThrow(/The HSM Connector's gateway does not support ML-DSA keys/);+ expect(getPlatformConnectionDetailsByGatewayId).not.toHaveBeenCalled();+ });++ test("a single gateway with ML-DSA support is used", async () => {+ const { routing, getPlatformConnectionDetailsByGatewayId } = buildRouting([+ { id: "new-gateway", capabilities: { pkcs11: true, pkcs11MlDsa: true } }+ ]);++ await signThroughPool(routing, HsmGatewayCapability.MlDsa, { gatewayId: "new-gateway", gatewayPoolId: null });++ expect(getPlatformConnectionDetailsByGatewayId.mock.calls[0][0]).toMatchObject({ gatewayId: "new-gateway" });+ });++ test("other operations still use any HSM-capable member", async () => {+ const { routing, getPlatformConnectionDetailsByGatewayId } = buildRouting([+ { id: "old-gateway", capabilities: { pkcs11: true } }+ ]);++ await signThroughPool(routing);++ expect(getPlatformConnectionDetailsByGatewayId.mock.calls[0][0]).toMatchObject({ gatewayId: "old-gateway" });+ });+});diff --git a/backend/src/services/hsm-connector/hsm-connector-routing.ts b/backend/src/services/hsm-connector/hsm-connector-routing.tsindex 251ab11d90..d5d07584ce 100644--- a/backend/src/services/hsm-connector/hsm-connector-routing.ts+++ b/backend/src/services/hsm-connector/hsm-connector-routing.ts@@ -1,4 +1,5 @@import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";+import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";@@ -11,6 +12,7 @@ import {import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";import { logger } from "@app/lib/logger";+import { HSM_ML_DSA_MIN_GATEWAY_VERSION, HsmGatewayCapability } from "./hsm-connector-fns";import {THsmConnectorCredentials,THsmConnectorTestMemberResult,@@ -22,6 +24,13 @@ const TEST_FANOUT_MAX = 10;const PKCS11_TARGET_HOST = "pkcs11";const NO_CAPABLE_MEMBER_MESSAGE ="No HSM-capable gateway available in the pool. Ensure at least one gateway in the pool has HSM support enabled.";+const ML_DSA_DRIVER_HINT = "check that your HSM's PKCS#11 driver supports ML-DSA";+const POOL_MISSING_CAPABILITY_MESSAGES: Record<HsmGatewayCapability, string> = {+ [HsmGatewayCapability.MlDsa]: `No HSM-capable gateway in the pool supports ML-DSA keys. Update at least one of them to ${HSM_ML_DSA_MIN_GATEWAY_VERSION} or later and ${ML_DSA_DRIVER_HINT}.`+};+const GATEWAY_MISSING_CAPABILITY_MESSAGES: Record<HsmGatewayCapability, string> = {+ [HsmGatewayCapability.MlDsa]: `The HSM Connector's gateway does not support ML-DSA keys. Update it to ${HSM_ML_DSA_MIN_GATEWAY_VERSION} or later and ${ML_DSA_DRIVER_HINT}.`+};type TGatewayRouting = {gatewayId: string | null | undefined;@@ -30,16 +39,25 @@ type TGatewayRouting = {type THsmConnectorRoutingDeps = {gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayV2DAL: Pick<TGatewayV2DALFactory, "findById">;gatewayPoolService: Pick<TGatewayPoolServiceFactory, "listHealthyGateways" | "selectGatewayFromPool">;};-const isPkcs11Capable = (capabilities: unknown): boolean => {+const isPkcs11Capable = (capabilities: unknown, requiredCapability?: HsmGatewayCapability): boolean => {const caps = (capabilities as Record<string, unknown> | null | undefined) ?? {};- return caps.pkcs11 === true;+ return caps.pkcs11 === true && (!requiredCapability || caps[requiredCapability] === true);};-export const hsmConnectorRoutingFactory = ({ gatewayV2Service, gatewayPoolService }: THsmConnectorRoutingDeps) => {- const pickGateway = async (connector: TGatewayRouting, triedGatewayIds: Set<string>): Promise<string> => {+export const hsmConnectorRoutingFactory = ({+ gatewayV2Service,+ gatewayV2DAL,+ gatewayPoolService+}: THsmConnectorRoutingDeps) => {+ const pickGateway = async (+ connector: TGatewayRouting,+ triedGatewayIds: Set<string>,+ requiredCapability?: HsmGatewayCapability+ ): Promise<string> => {if (connector.gatewayId) {if (triedGatewayIds.has(connector.gatewayId)) {throw new BadRequestError({@@ -47,6 +65,16 @@ export const hsmConnectorRoutingFactory = ({ gatewayV2Service, gatewayPoolServic"Gateway is unreachable for HSM operations. Ensure the gateway is online and has HSM support enabled."});}+ if (requiredCapability) {+ const gateway = await gatewayV2DAL.findById(connector.gatewayId);+ if (+ gateway &&+ isPkcs11Capable(gateway.capabilities) &&+ !isPkcs11Capable(gateway.capabilities, requiredCapability)+ ) {+ throw new BadRequestError({ message: GATEWAY_MISSING_CAPABILITY_MESSAGES[requiredCapability] });+ }+ }return connector.gatewayId;}if (!connector.gatewayPoolId) {@@ -55,12 +83,25 @@ export const hsmConnectorRoutingFactory = ({ gatewayV2Service, gatewayPoolServic// Key material is not portable between HSMs, so a member without the module attached is not an// acceptable substitute no matter how idle it is.- const selected = await gatewayPoolService.selectGatewayFromPool({- poolId: connector.gatewayPoolId,- exclude: triedGatewayIds,- filter: (gateway) => isPkcs11Capable(gateway.capabilities),- unavailableMessage: NO_CAPABLE_MEMBER_MESSAGE- });+ const poolId = connector.gatewayPoolId;+ const selected = await gatewayPoolService+ .selectGatewayFromPool({+ poolId,+ exclude: triedGatewayIds,+ filter: (gateway) => isPkcs11Capable(gateway.capabilities, requiredCapability),+ unavailableMessage: NO_CAPABLE_MEMBER_MESSAGE+ })+ .catch(async (err: unknown) => {+ if (!requiredCapability || !(err instanceof BadRequestError)) throw err;+ const healthyGateways = await gatewayPoolService.listHealthyGateways(poolId);+ const hasOtherPkcs11Member = healthyGateways.some(+ (gateway) => !triedGatewayIds.has(gateway.id) && isPkcs11Capable(gateway.capabilities)+ );+ if (hasOtherPkcs11Member) {+ throw new BadRequestError({ message: POOL_MISSING_CAPABILITY_MESSAGES[requiredCapability] });+ }+ throw err;+ });return selected.id;};@@ -69,6 +110,7 @@ export const hsmConnectorRoutingFactory = ({ gatewayV2Service, gatewayPoolServiccredentials: THsmConnectorCredentials;endpoint: Pkcs11RpcEndpoint;params: Record<string, unknown>;+ requiredCapability?: HsmGatewayCapability;}): Promise<T> => {const triedGatewayIds = new Set<string>();let lastError: { code: string; message: string } | undefined;@@ -80,7 +122,7 @@ export const hsmConnectorRoutingFactory = ({ gatewayV2Service, gatewayPoolServicfor (let attempt = 0; attempt <= PKCS11_POOL_RETRY_LIMIT; attempt += 1) {let gatewayId;try {- gatewayId = await pickGateway(args.connector, triedGatewayIds);+ gatewayId = await pickGateway(args.connector, triedGatewayIds, args.requiredCapability);} catch (err) {// Once every capable member has been tried, the accumulated PKCS#11 failure is the useful// error. Reporting "no HSM-capable gateway" instead points operators at the wrong problem.diff --git a/backend/src/services/hsm-connector/hsm-connector-service.ts b/backend/src/services/hsm-connector/hsm-connector-service.tsindex 8c1be0a1a0..7f3d8e17e2 100644--- a/backend/src/services/hsm-connector/hsm-connector-service.ts+++ b/backend/src/services/hsm-connector/hsm-connector-service.ts@@ -15,6 +15,7 @@ import {ProjectPermissionSub} from "@app/ee/services/permission/project-permission";import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { Pkcs11Mechanism } from "@app/lib/csr/pkcs11-algorithm-map";import { isPkcs11Error, Pkcs11ErrorCode } from "@app/lib/gateway-v2/pkcs11-rpc";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TOrgDALFactory } from "@app/services/org/org-dal";@@ -25,7 +26,8 @@ import {decryptHsmConnectorCredentials,encryptHsmConnectorCredentials,HsmConnectorCredentialsSchema,- HsmConnectorSanitizedSchema+ HsmConnectorSanitizedSchema,+ HsmGatewayCapability} from "./hsm-connector-fns";import { hsmConnectorRoutingFactory } from "./hsm-connector-routing";import type {@@ -57,6 +59,11 @@ export type THsmConnectorServiceFactory = ReturnType<typeof hsmConnectorServiceFconst OLD_GATEWAY_BAD_REQUEST_MESSAGE = "Invalid request";const GATEWAY_MAX_SIGN_DATA_BYTES = 64 * 1024;+const ML_DSA_HSM_KEY_ALGORITHMS = new Set<HsmKeyAlgorithm>([+ HsmKeyAlgorithm.ML_DSA_44,+ HsmKeyAlgorithm.ML_DSA_65,+ HsmKeyAlgorithm.ML_DSA_87+]);export const hsmConnectorServiceFactory = ({hsmConnectorDAL,@@ -69,7 +76,7 @@ export const hsmConnectorServiceFactory = ({orgDAL,licenseService}: THsmConnectorServiceFactoryDep) => {- const routing = hsmConnectorRoutingFactory({ gatewayV2Service, gatewayPoolService });+ const routing = hsmConnectorRoutingFactory({ gatewayV2Service, gatewayV2DAL, gatewayPoolService });const assertGatewayBelongsToOrg = async (actorOrgId: string,@@ -469,7 +476,8 @@ export const hsmConnectorServiceFactory = ({connector: { gatewayId: row.gatewayId, gatewayPoolId: row.gatewayPoolId },credentials,endpoint: "/v1/generate-key-pair",- params: { keyLabel: fullLabel, keyAlgorithm: args.keyAlgorithm }+ params: { keyLabel: fullLabel, keyAlgorithm: args.keyAlgorithm },+ requiredCapability: ML_DSA_HSM_KEY_ALGORITHMS.has(args.keyAlgorithm) ? HsmGatewayCapability.MlDsa : undefined});return {publicKeySpkiDer: Buffer.from(result.publicKey, "base64"),@@ -506,7 +514,8 @@ export const hsmConnectorServiceFactory = ({mechanism: args.mechanism,data: args.data.toString("base64"),isDigest: args.isDigest- }+ },+ requiredCapability: args.mechanism === Pkcs11Mechanism.MlDsa ? HsmGatewayCapability.MlDsa : undefined}).catch((err: unknown) => {if (isPkcs11Error(err, Pkcs11ErrorCode.KeyNotFound)) {diff --git a/backend/src/services/signer/signer-enums.ts b/backend/src/services/signer/signer-enums.tsindex 1efc2af5d3..e1e7df4b6d 100644--- a/backend/src/services/signer/signer-enums.ts+++ b/backend/src/services/signer/signer-enums.ts@@ -30,7 +30,10 @@ export enum HsmKeyAlgorithm {RSA_3072 = "RSA_3072",RSA_4096 = "RSA_4096",ECC_P256 = "ECC_P256",- ECC_P384 = "ECC_P384"+ ECC_P384 = "ECC_P384",+ ML_DSA_44 = "ML_DSA_44",+ ML_DSA_65 = "ML_DSA_65",+ ML_DSA_87 = "ML_DSA_87"}export const SIGNER_APPROVAL_REQUIRED_ERROR_NAME = "ApprovalRequired";diff --git a/backend/src/services/signer/signer-issuance-fns.ts b/backend/src/services/signer/signer-issuance-fns.tsindex db8a73e7e8..8d7fc41233 100644--- a/backend/src/services/signer/signer-issuance-fns.ts+++ b/backend/src/services/signer/signer-issuance-fns.ts@@ -19,6 +19,7 @@ import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authoimport { 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 { certKeyAlgorithmToHsmKeyAlgorithm } from "@app/services/hsm-connector/hsm-connector-fns";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";@@ -211,6 +212,12 @@ export const hsmKeyAlgorithmToCertKeyAlgorithm = (hsmAlg: HsmKeyAlgorithm): Certreturn CertKeyAlgorithm.ECDSA_P256;case HsmKeyAlgorithm.ECC_P384:return CertKeyAlgorithm.ECDSA_P384;+ case HsmKeyAlgorithm.ML_DSA_44:+ return CertKeyAlgorithm.ML_DSA_44;+ case HsmKeyAlgorithm.ML_DSA_65:+ return CertKeyAlgorithm.ML_DSA_65;+ case HsmKeyAlgorithm.ML_DSA_87:+ return CertKeyAlgorithm.ML_DSA_87;default: {const exhaustive: never = hsmAlg;throw new BadRequestError({ message: `Unsupported HSM key algorithm: ${exhaustive as string}` });@@ -219,22 +226,13 @@ export const hsmKeyAlgorithmToCertKeyAlgorithm = (hsmAlg: HsmKeyAlgorithm): Cert};export const mapCertKeyAlgorithmToHsmKeyAlgorithm = (certAlg: string): HsmKeyAlgorithm => {- switch (certAlg) {- case CertKeyAlgorithm.RSA_2048:- return HsmKeyAlgorithm.RSA_2048;- case CertKeyAlgorithm.RSA_3072:- return HsmKeyAlgorithm.RSA_3072;- 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.`- });+ const hsmKeyAlgorithm = isPqcAlgorithm(certAlg) ? undefined : certKeyAlgorithmToHsmKeyAlgorithm(certAlg);+ if (!hsmKeyAlgorithm) {+ throw new BadRequestError({+ message: `Cannot route HSM renewal: cert keyAlgorithm "${certAlg}" is not supported by the HSM Connector.`+ });}+ return hsmKeyAlgorithm;};export const issueHsmBackedSignerCertificate = async (diff --git a/docs/documentation/platform/pki/ca/private-ca.mdx b/docs/documentation/platform/pki/ca/private-ca.mdxindex d655d633c1..c35f4f17b9 100644--- a/docs/documentation/platform/pki/ca/private-ca.mdx+++ b/docs/documentation/platform/pki/ca/private-ca.mdx@@ -45,9 +45,9 @@ Create a simple Private CA hierarchy with a root CA and intermediate CA.- Valid Until: The date until which the CA is valid in the date time string format specified [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format). For example, the following formats would be valid: `YYYY`, `YYYY-MM`, `YYYY-MM-DD`, `YYYY-MM-DDTHH:mm:ss.sssZ`.- Path Length: The maximum number of intermediate CAs that can be chained to this CA. A path of `-1` implies no limit; a path of `0` implies no intermediate CAs can be chained.- - Key Algorithm: The type of public key algorithm and size, in bits, of the key pair that the CA creates when it issues a certificate. Supported key algorithms are `RSA 2048`, `RSA 4096`, `ECDSA P-256`, and `ECDSA P-384` with the default being `RSA 2048`.+ - Key Algorithm: The algorithm of the CA key pair. The default is `RSA 2048`, and the choices depend on **Key Source**.- Key Source: Where the CA's signing key is generated and stored. **Infisical** (the default) generates and manages the key for you. **HSM** generates the key inside your own Hardware Security Module through an [HSM Connector](/documentation/platform/pki/settings/hsm-connectors), and every signing operation the CA performs runs on the HSM. See [HSM-backed Internal CAs](#hsm-backed-internal-cas) below. **AWS KMS** creates the key in your AWS account, and every signing operation runs in [AWS KMS](#aws-kms-backed-internal-cas).- - HSM Connector: The [HSM Connector](/documentation/platform/pki/settings/hsm-connectors) Infisical uses to reach your HSM. Shown only when **Key Source** is **HSM**. With an HSM key source the algorithm choices stay limited to `RSA 2048`, `RSA 4096`, `ECDSA P-256`, and `ECDSA P-384`.+ - HSM Connector: The [HSM Connector](/documentation/platform/pki/settings/hsm-connectors) Infisical uses to reach your HSM. Shown only when **Key Source** is **HSM**. With an HSM key source, the algorithm choices are `RSA 2048`, `RSA 4096`, `ECDSA P-256`, `ECDSA P-384`, `ML-DSA-44`, `ML-DSA-65`, and `ML-DSA-87`.- AWS Connection: The [AWS connection](/integrations/app-connections/aws) used to create the key and sign with it. Shown only when **Key Source** is **AWS KMS**.- Region: The AWS region to create the key in. Shown only when **Key Source** is **AWS KMS**.- Name: A slug-friendly name for the CA.@@ -260,7 +260,12 @@ Create a simple Private CA hierarchy with a root CA and intermediate CA.By default, Infisical generates and manages the signing key for an Internal CA. You can instead keep the CA's signing key inside your own Hardware Security Module. When **Key Source** is set to **HSM**, Infisical generates the keypair on the HSM through an [HSM Connector](/documentation/platform/pki/settings/hsm-connectors) and performs every signing operation the CA does on the HSM. That covers the self-signed root certificate, intermediate CSRs, the certificates the CA issues, and its CRLs.-Both root and intermediate CAs can be HSM-backed. HSM-backed CAs support the `RSA 2048`, `RSA 4096`, `ECDSA P-256`, and `ECDSA P-384` key algorithms.+Both root and intermediate CAs can be HSM-backed. HSM-backed CAs support the `RSA 2048`, `RSA 4096`, `ECDSA P-256`, `ECDSA P-384`, `ML-DSA-44`, `ML-DSA-65`, and `ML-DSA-87` key algorithms.++To use an ML-DSA key on an HSM, you need:++- An HSM whose PKCS#11 driver supports ML-DSA, such as Fortanix DSM with PKCS#11 client 5.7 or later+- A [Gateway](/documentation/platform/gateways/overview) running v0.44.10 or later<Note>Set up an [HSM Connector](/documentation/platform/pki/settings/hsm-connectors) before creating an HSM-backed CA. Creating one requires the **Attach** permission on HSM Connectors in addition to permission to create Certificate Authorities.@@ -356,7 +361,7 @@ Deleting the CA schedules its key for deletion in AWS KMS with a 30-day waitingYes. You can either manually obtain a CSR and import the signed certificate, or use an integrated external CA provider like [Venafi TLS Protect Cloud](/documentation/platform/pki/ca/venafi) or [Microsoft ADCS](/documentation/platform/pki/ca/adcs) to automate the signing process.</Accordion><Accordion title="Can the CA signing key be kept in my own HSM?">- Yes. Set **Key Source** to **HSM** when creating the CA and pick an [HSM Connector](/documentation/platform/pki/settings/hsm-connectors). The keypair is generated on your HSM and every signing operation the CA performs runs there. Both root and intermediate CAs support this. Supported algorithms are `RSA 2048`, `RSA 4096`, `ECDSA P-256`, and `ECDSA P-384`. See [HSM-backed Internal CAs](#hsm-backed-internal-cas).+ Yes. Set **Key Source** to **HSM** when creating the CA and pick an [HSM Connector](/documentation/platform/pki/settings/hsm-connectors). The keypair is generated on your HSM and every signing operation the CA performs runs there. Both root and intermediate CAs support this. Supported algorithms are `RSA 2048`, `RSA 4096`, `ECDSA P-256`, `ECDSA P-384`, `ML-DSA-44`, `ML-DSA-65`, and `ML-DSA-87`. See [HSM-backed Internal CAs](#hsm-backed-internal-cas).</Accordion><Accordion title="Can the CA signing key be kept in AWS KMS?">Yes, including post-quantum ML-DSA keys. Set **Key Source** to **AWS KMS** and [create the CA through an AWS connection](#aws-kms-backed-internal-cas).diff --git a/docs/documentation/platform/pki/settings/hsm-connectors.mdx b/docs/documentation/platform/pki/settings/hsm-connectors.mdxindex 408553ec20..7230905483 100644--- a/docs/documentation/platform/pki/settings/hsm-connectors.mdx+++ b/docs/documentation/platform/pki/settings/hsm-connectors.mdx@@ -150,7 +150,7 @@ In **Certificate Manager > Settings > HSM Connectors**, select **Add HSM ConnectYes. 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.+ 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. For ML-DSA keys, at least one PKCS#11 Gateway in the pool must meet the requirements listed under [HSM-backed internal CAs](/documentation/platform/pki/ca/private-ca#hsm-backed-internal-cas).</Accordion><Accordion title="Which mechanisms are supported?">The PKCS#11 bridge supports the following signing mechanisms:@@ -164,8 +164,9 @@ In **Certificate Manager > Settings > HSM Connectors**, select **Add HSM Connect| ECDSA with SHA-256 | ECDSA signing with SHA-256 inside the HSM || ECDSA with SHA-384 | ECDSA signing with SHA-384 inside the HSM || ECDSA with SHA-512 | ECDSA signing with SHA-512 inside the HSM |+ | ML-DSA | ML-DSA signing inside the HSM |- Key algorithms supported for generation: RSA 2048-bit, RSA 4096-bit, ECDSA P-256, and ECDSA P-384.+ Key algorithms supported for generation: RSA 2048-bit, RSA 4096-bit, ECDSA P-256, ECDSA P-384, ML-DSA-44, ML-DSA-65, and ML-DSA-87. ML-DSA keys work with HSM-backed CAs only, not code signers.</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.diff --git a/frontend/src/hooks/api/hsmConnectors/types.ts b/frontend/src/hooks/api/hsmConnectors/types.tsindex 48a3a00352..a4b183c4a4 100644--- a/frontend/src/hooks/api/hsmConnectors/types.ts+++ b/frontend/src/hooks/api/hsmConnectors/types.ts@@ -61,6 +61,28 @@ export type THsmConnectorKey = {keyAlgorithm: string;};+export enum HsmKeyAlgorithm {+ RSA_2048 = "RSA_2048",+ RSA_3072 = "RSA_3072",+ RSA_4096 = "RSA_4096",+ ECC_P256 = "ECC_P256",+ ECC_P384 = "ECC_P384",+ ML_DSA_44 = "ML_DSA_44",+ ML_DSA_65 = "ML_DSA_65",+ ML_DSA_87 = "ML_DSA_87"+}++export const hsmKeyAlgorithmLabels: Record<HsmKeyAlgorithm, string> = {+ [HsmKeyAlgorithm.RSA_2048]: "RSA-2048",+ [HsmKeyAlgorithm.RSA_3072]: "RSA-3072",+ [HsmKeyAlgorithm.RSA_4096]: "RSA-4096",+ [HsmKeyAlgorithm.ECC_P256]: "ECDSA P-256",+ [HsmKeyAlgorithm.ECC_P384]: "ECDSA P-384",+ [HsmKeyAlgorithm.ML_DSA_44]: "ML-DSA-44",+ [HsmKeyAlgorithm.ML_DSA_65]: "ML-DSA-65",+ [HsmKeyAlgorithm.ML_DSA_87]: "ML-DSA-87"+};+export type THsmConnectorLinkedCertificate = {id: string;commonName: string;diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsxindex bdc7115531..acfeb7ad39 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx@@ -317,10 +317,7 @@ export const KeyValidityStep = ({})}</SelectContent></Select>- <FieldDescription>- Algorithm and size of the CA key pair.- {isHsm && " HSM-backed CAs support RSA and ECDSA only."}- </FieldDescription>+ <FieldDescription>Algorithm of the CA key pair.</FieldDescription><FieldError errors={[error]} /></FieldContent></Field>diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/types.ts b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/types.tsindex e8bb559f59..1f849227e0 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/types.ts+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/types.ts@@ -10,7 +10,10 @@ export const KEY_SOURCE_SUPPORTED_CA_KEY_ALGORITHMS: Partial<CertKeyAlgorithm.RSA_2048,CertKeyAlgorithm.RSA_4096,CertKeyAlgorithm.ECDSA_P256,- CertKeyAlgorithm.ECDSA_P384+ CertKeyAlgorithm.ECDSA_P384,+ CertKeyAlgorithm.ML_DSA_44,+ CertKeyAlgorithm.ML_DSA_65,+ CertKeyAlgorithm.ML_DSA_87],[CertKeySource.AwsKms]: [CertKeyAlgorithm.RSA_2048,diff --git a/frontend/src/pages/cert-manager/components/SignerKeyStep.tsx b/frontend/src/pages/cert-manager/components/SignerKeyStep.tsxindex 584e3eebb0..cc6e3a198c 100644--- a/frontend/src/pages/cert-manager/components/SignerKeyStep.tsx+++ b/frontend/src/pages/cert-manager/components/SignerKeyStep.tsx@@ -29,7 +29,12 @@ import {ProjectPermissionSub} from "@app/context/ProjectPermissionContext/types";import { useDebounce } from "@app/hooks";-import { THsmConnectorKey, useListHsmConnectorKeys } from "@app/hooks/api/hsmConnectors";+import {+ HsmKeyAlgorithm,+ hsmKeyAlgorithmLabels,+ THsmConnectorKey,+ useListHsmConnectorKeys+} from "@app/hooks/api/hsmConnectors";import {CertKeySource,HSM_SUPPORTED_KEY_ALGORITHMS,@@ -41,7 +46,9 @@ import { CreateHsmConnectorWizard } from "@app/pages/cert-manager/SettingsPage/cimport { ExternalOrderMode, isUsingExistingCertificate } from "./DigiCertExistingOrderField";const formatHsmKeyOption = (key: THsmConnectorKey) =>- key.keyAlgorithm ? `ID ${key.keyId} (${key.keyAlgorithm.replace("_", " ")})` : `ID ${key.keyId}`;+ key.keyAlgorithm+ ? `ID ${key.keyId} (${hsmKeyAlgorithmLabels[key.keyAlgorithm as HsmKeyAlgorithm] ?? key.keyAlgorithm})`+ : `ID ${key.keyId}`;export type HsmConnectorOption = { id: string; name: string; slotLabel: string };