Skip to content

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

Add HSM-backed internal certificate authorities

Carlos Monastyrski98ae18fc0952
diff --git a/backend/src/db/migrations/20260629173042_internal-ca-hsm-key.ts b/backend/src/db/migrations/20260629173042_internal-ca-hsm-key.ts
new file mode 100644
index 0000000000..3f80b2c3ed
--- /dev/null
+++ b/backend/src/db/migrations/20260629173042_internal-ca-hsm-key.ts
@@ -0,0 +1,93 @@
+import { Knex } from "knex";
+
+import { TableName } from "@app/db/schemas";
+
+const CA_SECRET_KEY_SOURCE_CHK = "certificate_authority_secret_key_source_chk";
+const CA_SECRET_HSM_CONNECTOR_FK = "certificate_authority_secret_hsmconnectorid_foreign";
+const CA_SECRET_HSM_CONNECTOR_IDX = "certificate_authority_secret_hsmconnectorid_idx";
+
+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.CertificateAuthoritySecret))) return;
+
+ const hasKeySource = await knex.schema.hasColumn(TableName.CertificateAuthoritySecret, "keySource");
+ const hasHsmConnectorId = await knex.schema.hasColumn(TableName.CertificateAuthoritySecret, "hsmConnectorId");
+ const hasHsmKeyLabel = await knex.schema.hasColumn(TableName.CertificateAuthoritySecret, "hsmKeyLabel");
+ const hasHsmPublicKeySpki = await knex.schema.hasColumn(TableName.CertificateAuthoritySecret, "hsmPublicKeySpki");
+
+ if (!hasKeySource || !hasHsmConnectorId || !hasHsmKeyLabel || !hasHsmPublicKeySpki) {
+ await knex.schema.alterTable(TableName.CertificateAuthoritySecret, (t) => {
+ if (!hasKeySource) {
+ t.string("keySource", 32).notNullable().defaultTo("infisical");
+ }
+ if (!hasHsmConnectorId) {
+ t.uuid("hsmConnectorId").nullable();
+ t.foreign("hsmConnectorId", CA_SECRET_HSM_CONNECTOR_FK)
+ .references("id")
+ .inTable(TableName.HsmConnector)
+ .onDelete("RESTRICT");
+ t.index(["hsmConnectorId"], CA_SECRET_HSM_CONNECTOR_IDX, { predicate: knex.whereNotNull("hsmConnectorId") });
+ }
+ if (!hasHsmKeyLabel) {
+ t.string("hsmKeyLabel", 128).nullable();
+ }
+ if (!hasHsmPublicKeySpki) {
+ t.binary("hsmPublicKeySpki").nullable();
+ }
+ });
+ }
+
+ // HSM-backed CAs have no locally stored private key, so the column must become nullable.
+ await knex.schema.alterTable(TableName.CertificateAuthoritySecret, (t) => {
+ t.binary("encryptedPrivateKey").nullable().alter();
+ });
+
+ if (!(await constraintExists(knex, TableName.CertificateAuthoritySecret, CA_SECRET_KEY_SOURCE_CHK))) {
+ await knex.raw(
+ `ALTER TABLE ?? ADD CONSTRAINT ?? CHECK (
+ ("keySource" = 'infisical' AND "encryptedPrivateKey" IS NOT NULL)
+ OR
+ ("keySource" = 'hsm' AND "hsmConnectorId" IS NOT NULL AND "hsmKeyLabel" IS NOT NULL)
+ ) NOT VALID`,
+ [TableName.CertificateAuthoritySecret, CA_SECRET_KEY_SOURCE_CHK]
+ );
+ await knex.raw(`ALTER TABLE ?? VALIDATE CONSTRAINT ??`, [
+ TableName.CertificateAuthoritySecret,
+ CA_SECRET_KEY_SOURCE_CHK
+ ]);
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasTable(TableName.CertificateAuthoritySecret))) return;
+
+ if (await constraintExists(knex, TableName.CertificateAuthoritySecret, CA_SECRET_KEY_SOURCE_CHK)) {
+ await knex.raw(`ALTER TABLE ?? DROP CONSTRAINT ??`, [
+ TableName.CertificateAuthoritySecret,
+ CA_SECRET_KEY_SOURCE_CHK
+ ]);
+ }
+
+ const hasKeySource = await knex.schema.hasColumn(TableName.CertificateAuthoritySecret, "keySource");
+ const hasHsmConnectorId = await knex.schema.hasColumn(TableName.CertificateAuthoritySecret, "hsmConnectorId");
+ const hasHsmKeyLabel = await knex.schema.hasColumn(TableName.CertificateAuthoritySecret, "hsmKeyLabel");
+ const hasHsmPublicKeySpki = await knex.schema.hasColumn(TableName.CertificateAuthoritySecret, "hsmPublicKeySpki");
+
+ if (hasKeySource || hasHsmConnectorId || hasHsmKeyLabel || hasHsmPublicKeySpki) {
+ await knex.schema.alterTable(TableName.CertificateAuthoritySecret, (t) => {
+ if (hasHsmPublicKeySpki) t.dropColumn("hsmPublicKeySpki");
+ if (hasHsmKeyLabel) t.dropColumn("hsmKeyLabel");
+ if (hasHsmConnectorId) t.dropColumn("hsmConnectorId");
+ if (hasKeySource) t.dropColumn("keySource");
+ });
+ }
+}
diff --git a/backend/src/db/schemas/certificate-authority-secret.ts b/backend/src/db/schemas/certificate-authority-secret.ts
index 36ab1c5060..5d0d50d5d3 100644
--- a/backend/src/db/schemas/certificate-authority-secret.ts
+++ b/backend/src/db/schemas/certificate-authority-secret.ts
@@ -14,7 +14,11 @@ export const CertificateAuthoritySecretSchema = z.object({
createdAt: z.date(),
updatedAt: z.date(),
caId: z.string().uuid(),
- encryptedPrivateKey: zodBuffer
+ encryptedPrivateKey: zodBuffer.nullable().optional(),
+ keySource: z.string().default("infisical"),
+ hsmConnectorId: z.string().uuid().nullable().optional(),
+ hsmKeyLabel: z.string().nullable().optional(),
+ hsmPublicKeySpki: zodBuffer.nullable().optional()
});
export type TCertificateAuthoritySecret = z.infer<typeof CertificateAuthoritySecretSchema>;
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index cd6cd952db..d049c79903 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2659,6 +2659,11 @@ export const CertificateAuthorities = {
"The maximum number of intermediate CAs that may follow this CA in the certificate / CA chain. A maxPathLength of -1 implies no path limit on the chain.",
keyAlgorithm:
"The type of public key algorithm and size, in bits, of the key pair for the CA; when you create an intermediate CA, you must use a key algorithm supported by the parent CA.",
+ keySource:
+ "Where the CA's signing key is generated and stored. 'infisical' keeps the key in Infisical's KMS; 'hsm' generates and stores the key in the HSM reached through the specified HSM Connector.",
+ hsmConnectorId:
+ "The ID of the HSM Connector to generate and store the CA's signing key in. Required when keySource is 'hsm'.",
+ hsmKeyLabel: "The label of the CA signing key on the HSM. Set automatically for HSM-backed CAs.",
crlDistributionPointUrls:
"Additional CRL Distribution Point URLs (HTTP/HTTPS) embedded in every certificate issued by this CA. Up to 4 URLs; the Infisical-managed CRL endpoint is included by default unless disabled.",
disableManagedCrlDistributionPointUrl:
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index cfc47a237e..1defda423b 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2858,7 +2858,8 @@ export const registerRoutes = async (
appConnectionService,
pkiSyncDAL,
pkiSyncQueue,
- internalCertificateAuthorityDAL
+ internalCertificateAuthorityDAL,
+ hsmConnectorService
});
const internalCertificateAuthorityService = internalCertificateAuthorityServiceFactory({
@@ -2879,7 +2880,8 @@ export const registerRoutes = async (
permissionService,
licenseService,
caSigningConfigDAL,
- usageMeteringService
+ usageMeteringService,
+ hsmConnectorService
});
const caAutoRenewalQueue = caAutoRenewalQueueFactory({
@@ -2920,7 +2922,9 @@ export const registerRoutes = async (
resourceMetadataDAL,
gatewayV2Service,
gatewayPoolService,
- usageMeteringService
+ usageMeteringService,
+ hsmConnectorService,
+ certificateAuthoritySecretDAL
});
const certificateEstService = certificateEstServiceFactory({
@@ -2982,7 +2986,8 @@ export const registerRoutes = async (
pkiAlertV2Queue,
pkiApplicationDAL,
licenseService,
- usageMeteringService
+ usageMeteringService,
+ hsmConnectorService
});
const digicertCaFns = DigiCertCertificateAuthorityFns({
diff --git a/backend/src/server/routes/v1/hsm-connector-router-schemas.ts b/backend/src/server/routes/v1/hsm-connector-router-schemas.ts
index 5f57ed1084..6e618ef6e9 100644
--- a/backend/src/server/routes/v1/hsm-connector-router-schemas.ts
+++ b/backend/src/server/routes/v1/hsm-connector-router-schemas.ts
@@ -1,6 +1,7 @@
import { z } from "zod";
import { slugSchema } from "@app/server/lib/schemas";
+import { CaStatus, InternalCaType } from "@app/services/certificate-authority/certificate-authority-enums";
import { HsmConnectorCredentialsSchema } from "@app/services/hsm-connector/hsm-connector-fns";
const HSM_CONNECTOR_NAME_MAX = 32;
@@ -89,5 +90,16 @@ export const HsmConnectorLinkedResourcesResponseSchema = z.object({
createdAt: z.date()
})
),
+ certificateAuthorities: z.array(
+ z.object({
+ id: z.string().uuid(),
+ name: z.string(),
+ commonName: z.string().nullable(),
+ status: z.nativeEnum(CaStatus),
+ type: z.nativeEnum(InternalCaType),
+ hsmKeyLabel: z.string().nullable(),
+ createdAt: z.date()
+ })
+ ),
totalCount: z.number()
});
diff --git a/backend/src/services/cert-manager-export/cert-manager-export-service.ts b/backend/src/services/cert-manager-export/cert-manager-export-service.ts
index e608f903cf..16b9404a36 100644
--- a/backend/src/services/cert-manager-export/cert-manager-export-service.ts
+++ b/backend/src/services/cert-manager-export/cert-manager-export-service.ts
@@ -16,6 +16,7 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
+import { CertKeySource } from "@app/services/signer/signer-enums";
import { TExportCertManagerProjectDTO, TExportCertManagerProjectResult } from "./cert-manager-export-types";
@@ -167,6 +168,29 @@ export const certManagerExportServiceFactory = ({
);
const sourceInternalCAs = sourceCAsRaw.filter((ca) => Boolean(ca.internalCa?.id));
+ const allSourceSecrets = sourceInternalCAs.length
+ ? await certificateAuthoritySecretDAL.find({ $in: { caId: sourceInternalCAs.map((ca) => ca.id) } }, { tx })
+ : [];
+ const sourceSecretsByCaId = new Map<string, typeof allSourceSecrets>();
+ for (const secret of allSourceSecrets) {
+ const existing = sourceSecretsByCaId.get(secret.caId);
+ if (existing) existing.push(secret);
+ else sourceSecretsByCaId.set(secret.caId, [secret]);
+ }
+
+ const hsmBackedCaIds = new Set(
+ allSourceSecrets.filter((s) => s.keySource === CertKeySource.Hsm).map((s) => s.caId)
+ );
+ if (hsmBackedCaIds.size) {
+ const names = sourceInternalCAs
+ .filter((ca) => hsmBackedCaIds.has(ca.id))
+ .map((ca) => ca.name)
+ .join(", ");
+ throw new BadRequestError({
+ message: `Cannot export HSM-backed certificate authorities (${names}); their signing keys are bound to a project-scoped HSM connector. Remove them from the source project before exporting.`
+ });
+ }
+
const caIndexById = new Map(sourceInternalCAs.map((ca) => [ca.id, ca]));
const visited = new Set<string>();
const sortedCAs: typeof sourceInternalCAs = [];
@@ -205,12 +229,18 @@ export const certManagerExportServiceFactory = ({
);
caIdMap.set(sourceCa.id, newCa.id);
- const sourceSecrets = await certificateAuthoritySecretDAL.find({ caId: sourceCa.id }, { tx });
+ const sourceSecrets = sourceSecretsByCaId.get(sourceCa.id) ?? [];
for (const sourceSecret of sourceSecrets) {
const newSecret = await certificateAuthoritySecretDAL.create(
{
caId: newCa.id,
- encryptedPrivateKey: await reencrypt(sourceSecret.encryptedPrivateKey)
+ keySource: sourceSecret.keySource,
+ hsmConnectorId: sourceSecret.hsmConnectorId,
+ hsmKeyLabel: sourceSecret.hsmKeyLabel,
+ hsmPublicKeySpki: sourceSecret.hsmPublicKeySpki,
+ encryptedPrivateKey: sourceSecret.encryptedPrivateKey
+ ? await reencrypt(sourceSecret.encryptedPrivateKey)
+ : undefined
},
tx
);
diff --git a/backend/src/services/certificate-authority/ca-signer.ts b/backend/src/services/certificate-authority/ca-signer.ts
new file mode 100644
index 0000000000..8ec2ca5e79
--- /dev/null
+++ b/backend/src/services/certificate-authority/ca-signer.ts
@@ -0,0 +1,190 @@
+import { CertificationRequest } from "@peculiar/asn1-csr";
+import { AsnConvert } from "@peculiar/asn1-schema";
+import { Certificate, CertificateList } from "@peculiar/asn1-x509";
+import * as x509 from "@peculiar/x509";
+
+import { crypto } from "@app/lib/crypto/cryptography";
+import { ecdsaRawRsToDer } from "@app/lib/csr/pkcs11-algorithm-map";
+import { BadRequestError } from "@app/lib/errors";
+import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";
+import { HsmKeyAlgorithm } from "@app/services/signer/signer-enums";
+
+// @peculiar/x509's generators require a local CryptoKey, so for HSM-backed CAs we build the
+// structure with a throwaway key of the matching algorithm, then swap in a signature the HSM
+// produces over the TBS bytes (same pattern as build-csr-with-external-signer).
+
+type TCertCreateParams = Parameters<typeof x509.X509CertificateGenerator.create>[0];
+type TCsrCreateParams = Parameters<typeof x509.Pkcs10CertificateRequestGenerator.create>[0];
+type TCrlCreateParams = Parameters<typeof x509.X509CrlGenerator.create>[0];
+
+export type TCaCertificateParams = Omit<TCertCreateParams, "signingKey" | "signingAlgorithm">;
+export type TCaCsrParams = Omit<TCsrCreateParams, "keys" | "signingAlgorithm">;
+export type TCaCrlParams = Omit<TCrlCreateParams, "signingKey" | "signingAlgorithm">;
+
+export type TCaSigner = {
+ caPublicKey: CryptoKey;
+ signingAlgorithm: Algorithm;
+ createCertificate: (params: TCaCertificateParams) => Promise<x509.X509Certificate>;
+ createCsr: (params: TCaCsrParams) => Promise<x509.Pkcs10CertificateRequest>;
+ createCrl: (params: TCaCrlParams) => Promise<x509.X509Crl>;
+};
+
+export type TCaExternalSignFn = (tbs: Buffer, mechanism: string, isDigest: boolean) => Promise<Buffer>;
+
+type TCaHsmShape = {
+ hsmKeyAlgorithm: HsmKeyAlgorithm;
+ mechanism: string;
+ isEcdsa: boolean;
+ signingAlgorithm: Algorithm;
+ keyGenParams: RsaHashedKeyGenParams | EcKeyGenParams;
+ importParams: RsaHashedImportParams | EcKeyImportParams;
+};
+
+const RSA_PUBLIC_EXPONENT = new Uint8Array([1, 0, 1]);
+
+export const caKeyAlgorithmToHsmShape = (keyAlgorithm: CertKeyAlgorithm | string): TCaHsmShape => {
+ switch (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,
+ keyGenParams: {
+ name: "RSASSA-PKCS1-v1_5",
+ hash: "SHA-256",
+ publicExponent: RSA_PUBLIC_EXPONENT,
+ modulusLength: 2048
+ },
+ importParams: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }
+ };
+ case 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,
+ keyGenParams: {
+ name: "RSASSA-PKCS1-v1_5",
+ hash: "SHA-256",
+ publicExponent: RSA_PUBLIC_EXPONENT,
+ modulusLength: 4096
+ },
+ importParams: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }
+ };
+ case CertKeyAlgorithm.ECDSA_P256:
+ return {
+ hsmKeyAlgorithm: HsmKeyAlgorithm.ECC_P256,
+ mechanism: "CKM_ECDSA_SHA256",
+ isEcdsa: true,
+ signingAlgorithm: { name: "ECDSA", hash: "SHA-256" } as Algorithm,
+ keyGenParams: { name: "ECDSA", namedCurve: "P-256" },
+ importParams: { name: "ECDSA", namedCurve: "P-256" }
+ };
+ case CertKeyAlgorithm.ECDSA_P384:
+ return {
+ hsmKeyAlgorithm: HsmKeyAlgorithm.ECC_P384,
+ mechanism: "CKM_ECDSA_SHA384",
+ isEcdsa: true,
+ signingAlgorithm: { name: "ECDSA", hash: "SHA-384" } as Algorithm,
+ keyGenParams: { name: "ECDSA", namedCurve: "P-384" },
+ importParams: { name: "ECDSA", namedCurve: "P-384" }
+ };
+ default:
+ throw new BadRequestError({
+ message: `Key algorithm "${keyAlgorithm}" is not supported for HSM-backed certificate authorities.`
+ });
+ }
+};
+
+export const caKeyAlgorithmToHsmKeyAlgorithm = (keyAlgorithm: CertKeyAlgorithm | string): HsmKeyAlgorithm =>
+ caKeyAlgorithmToHsmShape(keyAlgorithm).hsmKeyAlgorithm;
+
+const bufferToArrayBuffer = (buf: Buffer): ArrayBuffer => {
+ const ab = new ArrayBuffer(buf.length);
+ new Uint8Array(ab).set(buf);
+ return ab;
+};
+
+export const buildLocalCaSigner = ({
+ privateKey,
+ publicKey,
+ signingAlgorithm
+}: {
+ privateKey: CryptoKey;
+ publicKey: CryptoKey;
+ signingAlgorithm: Algorithm;
+}): TCaSigner => ({
+ caPublicKey: publicKey,
+ signingAlgorithm,
+ createCertificate: (params) =>
+ x509.X509CertificateGenerator.create({ ...params, signingKey: privateKey, signingAlgorithm }),
+ createCsr: (params) =>
+ x509.Pkcs10CertificateRequestGenerator.create({
+ ...params,
+ keys: { privateKey, publicKey },
+ signingAlgorithm
+ }),
+ createCrl: (params) => x509.X509CrlGenerator.create({ ...params, signingKey: privateKey, signingAlgorithm })
+});
+
+export const buildHsmCaSigner = ({
+ caPublicKey,
+ keyAlgorithm,
+ sign
+}: {
+ caPublicKey: CryptoKey;
+ keyAlgorithm: CertKeyAlgorithm | string;
+ sign: TCaExternalSignFn;
+}): TCaSigner => {
+ const shape = caKeyAlgorithmToHsmShape(keyAlgorithm);
+
+ const signTbs = async (tbs: Buffer): Promise<ArrayBuffer> => {
+ // isDigest=false: the HSM hashes via its *_SHA<NN>_* mechanism, so we hand it the raw TBS.
+ let signature = await sign(tbs, shape.mechanism, false);
+ if (shape.isEcdsa) signature = ecdsaRawRsToDer(signature);
+ return bufferToArrayBuffer(signature);
+ };
+
+ const generateEphemeralKey = () =>
+ crypto.nativeCrypto.subtle.generateKey(shape.keyGenParams as RsaHashedKeyGenParams, true, ["sign", "verify"]);
+
+ return {
+ caPublicKey,
+ signingAlgorithm: shape.signingAlgorithm,
+ createCertificate: async (params) => {
+ const ephemeral = await generateEphemeralKey();
+ const built = await x509.X509CertificateGenerator.create({
+ ...params,
+ signingKey: ephemeral.privateKey,
+ signingAlgorithm: shape.signingAlgorithm
+ });
+ const cert = AsnConvert.parse(built.rawData, Certificate);
+ cert.signatureValue = await signTbs(Buffer.from(AsnConvert.serialize(cert.tbsCertificate)));
+ return new x509.X509Certificate(AsnConvert.serialize(cert));
+ },
+ createCsr: async (params) => {
+ const ephemeral = await generateEphemeralKey();
+ const built = await x509.Pkcs10CertificateRequestGenerator.create({
+ ...params,
+ keys: { privateKey: ephemeral.privateKey, publicKey: caPublicKey },
+ signingAlgorithm: shape.signingAlgorithm
+ });
+ const csr = AsnConvert.parse(built.rawData, CertificationRequest);
+ csr.signature = await signTbs(Buffer.from(AsnConvert.serialize(csr.certificationRequestInfo)));
+ return new x509.Pkcs10CertificateRequest(AsnConvert.serialize(csr));
+ },
+ createCrl: async (params) => {
+ const ephemeral = await generateEphemeralKey();
+ const built = await x509.X509CrlGenerator.create({
+ ...params,
+ signingKey: ephemeral.privateKey,
+ signingAlgorithm: shape.signingAlgorithm
+ });
+ const crl = AsnConvert.parse(built.rawData, CertificateList);
+ crl.signature = await signTbs(Buffer.from(AsnConvert.serialize(crl.tbsCertList)));
+ return new x509.X509Crl(AsnConvert.serialize(crl));
+ }
+ };
+};
diff --git a/backend/src/services/certificate-authority/certificate-authority-fns.ts b/backend/src/services/certificate-authority/certificate-authority-fns.ts
index 8fc63a8825..456f7dac69 100644
--- a/backend/src/services/certificate-authority/certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-fns.ts
@@ -6,6 +6,7 @@ import { crypto } from "@app/lib/crypto/cryptography";
import { derivePublicKeyFromSecret, getPqcCrypto, isPqcAlgorithm, PqcCryptoKey } from "@app/lib/crypto/pqc";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
+import { CertKeySource } from "@app/services/signer/signer-enums";
import {
CertExtendedKeyUsage,
@@ -16,12 +17,14 @@ import {
TAltNameType
} from "../certificate/certificate-types";
import { DEFAULT_CRL_VALIDITY_DAYS } from "../certificate-common/certificate-constants";
+import { buildHsmCaSigner, buildLocalCaSigner, caKeyAlgorithmToHsmShape, TCaSigner } from "./ca-signer";
import { TCertificateAuthorityDALFactory } from "./certificate-authority-dal";
import {
TDNParts,
TGetCaCertChainDTO,
TGetCaCertChainsDTO,
TGetCaCredentialsDTO,
+ TGetCaSignerDTO,
TRebuildCaCrlDTO
} from "./internal/internal-certificate-authority-types";
@@ -364,6 +367,11 @@ export const getCaCredentials = async ({
const caSecret = await certificateAuthoritySecretDAL.findOne({ caId });
if (!caSecret) throw new NotFoundError({ message: `CA secret for CA with ID '${caId}' not found` });
+ if (!caSecret.encryptedPrivateKey) {
+ throw new BadRequestError({
+ message: `Certificate authority '${caId}' is HSM-backed; its signing key is not available locally.`
+ });
+ }
const keyId = await getProjectKmsCertificateKeyId({
projectId: ca.projectId,
@@ -419,6 +427,80 @@ export const getCaCredentials = async ({
};
};
+/**
+ * Return a signer for CA with id [caId] that abstracts over where the signing key lives.
+ * For locally-keyed CAs it decrypts the KMS-stored private key; for HSM-backed CAs it routes
+ * signing through the HSM Connector. Every issuance / renewal / CRL path uses this so the
+ * call sites never branch on key source.
+ */
+export const getCaSigner = async ({
+ caId,
+ certificateAuthorityDAL,
+ certificateAuthoritySecretDAL,
+ projectDAL,
+ kmsService,
+ hsmConnectorService,
+ signatureAlgorithm
+}: TGetCaSignerDTO): Promise<{
+ caSecret: Awaited<ReturnType<typeof getCaCredentials>>["caSecret"];
+ signer: TCaSigner;
+}> => {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ if (!ca?.internalCa?.id) throw new NotFoundError({ message: `Internal CA with ID '${caId}' not found` });
+
+ const caSecret = await certificateAuthoritySecretDAL.findOne({ caId });
+ if (!caSecret) throw new NotFoundError({ message: `CA secret for CA with ID '${caId}' not found` });
+
+ const keyAlgorithm = ca.internalCa.keyAlgorithm as CertKeyAlgorithm;
+
+ if (caSecret.keySource === CertKeySource.Hsm) {
+ // signatureAlgorithm is intentionally ignored: the HSM mechanism is fixed by the key algorithm.
+ if (!caSecret.hsmConnectorId || !caSecret.hsmKeyLabel || !caSecret.hsmPublicKeySpki) {
+ throw new BadRequestError({ message: "HSM-backed CA secret is missing its connector, key label, or public key" });
+ }
+
+ const shape = caKeyAlgorithmToHsmShape(keyAlgorithm);
+ const caPublicKey = await crypto.nativeCrypto.subtle.importKey(
+ "spki",
+ caSecret.hsmPublicKeySpki,
+ shape.importParams,
+ true,
+ ["verify"]
+ );
+
+ const connectorId = caSecret.hsmConnectorId;
+ const keyLabel = caSecret.hsmKeyLabel;
+ const signer = buildHsmCaSigner({
+ caPublicKey,
+ keyAlgorithm,
+ sign: (data, mechanism, isDigest) =>
+ hsmConnectorService.sign({
+ connectorId,
+ projectId: ca.projectId,
+ keyLabel,
+ mechanism,
+ data,
+ isDigest
+ })
+ });
+
+ return { caSecret, signer };
+ }
+
+ const { caPrivateKey, caPublicKey } = await getCaCredentials({
+ caId,
+ certificateAuthorityDAL,
+ certificateAuthoritySecretDAL,
+ projectDAL,
+ kmsService,
+ signatureAlgorithm
+ });
+ const signingAlgorithm = signatureAlgorithm || keyAlgorithmToAlgCfg(keyAlgorithm);
+ const signer = buildLocalCaSigner({ privateKey: caPrivateKey, publicKey: caPublicKey, signingAlgorithm });
+
+ return { caSecret, signer };
+};
+
/**
* Return the list of decrypted pem-encoded certificates and certificate chains
* for CA with id [caId].
@@ -520,15 +602,20 @@ export const rebuildCaCrl = async ({
certificateAuthoritySecretDAL,
projectDAL,
certificateDAL,
- kmsService
+ kmsService,
+ hsmConnectorService
}: TRebuildCaCrlDTO) => {
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
if (!ca?.internalCa?.id) throw new NotFoundError({ message: `Internal CA with ID '${caId}' not found` });
- const caSecret = await certificateAuthoritySecretDAL.findOne({ caId: ca.id });
-
- const keyAlgorithm = ca.internalCa.keyAlgorithm as CertKeyAlgorithm;
- const alg = keyAlgorithmToAlgCfg(keyAlgorithm);
+ const { signer } = await getCaSigner({
+ caId: ca.id,
+ certificateAuthorityDAL,
+ certificateAuthoritySecretDAL,
+ projectDAL,
+ kmsService,
+ hsmConnectorService
+ });
const keyId = await getProjectKmsCertificateKeyId({
projectId: ca.projectId,
@@ -536,28 +623,6 @@ export const rebuildCaCrl = async ({
kmsService
});
- const kmsDecryptor = await kmsService.decryptWithKmsKey({
- kmsId: keyId
- });
-
- const privateKey = await kmsDecryptor({
- cipherTextBlob: caSecret.encryptedPrivateKey
- });
-
- let sk: CryptoKey;
- if (isPqcAlgorithm(keyAlgorithm)) {
- sk = await getPqcCrypto().subtle.importKey("pkcs8", privateKey, alg, true, ["sign"]);
- } else {
- const skObj = crypto.nativeCrypto.createPrivateKey({ key: privateKey, format: "der", type: "pkcs8" });
- sk = await crypto.nativeCrypto.subtle.importKey(
- "pkcs8",
- skObj.export({ format: "der", type: "pkcs8" }),
- alg,
- true,
- ["sign"]
- );
- }
-
const revokedCerts = await certificateDAL.find({
caId: ca.id,
status: CertStatus.REVOKED
@@ -567,7 +632,7 @@ export const rebuildCaCrl = async ({
const nextUpdate = new Date(thisUpdate);
nextUpdate.setDate(nextUpdate.getDate() + DEFAULT_CRL_VALIDITY_DAYS);
- const crl = await x509.X509CrlGenerator.create({
+ const crl = await signer.createCrl({
issuer: ca.internalCa.dn,
thisUpdate,
nextUpdate,
@@ -578,9 +643,7 @@ export const rebuildCaCrl = async ({
revocationDate,
reason: revokedCert.revocationReason as number
};
- }),
- signingAlgorithm: alg,
- signingKey: sk
+ })
});
const kmsEncryptor = await kmsService.encryptWithKmsKey({
diff --git a/backend/src/services/certificate-authority/certificate-authority-queue.ts b/backend/src/services/certificate-authority/certificate-authority-queue.ts
index 5b57eb3ab7..849bb9b66a 100644
--- a/backend/src/services/certificate-authority/certificate-authority-queue.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-queue.ts
@@ -1,17 +1,14 @@
/* eslint-disable no-await-in-loop, no-continue */
-import * as x509 from "@peculiar/x509";
-
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
-import { crypto } from "@app/lib/crypto/cryptography";
-import { getPqcCrypto, isPqcAlgorithm } from "@app/lib/crypto/pqc";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
-import { CertKeyAlgorithm, CertStatus } from "@app/services/certificate/certificate-types";
+import { CertStatus } from "@app/services/certificate/certificate-types";
import { DEFAULT_CRL_VALIDITY_DAYS } from "@app/services/certificate-common/certificate-constants";
+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";
@@ -29,7 +26,7 @@ import { AcmeCertificateAuthorityFns } from "./acme/acme-certificate-authority-f
import { AzureAdCsCertificateAuthorityFns } from "./azure-ad-cs/azure-ad-cs-certificate-authority-fns";
import { TCertificateAuthorityDALFactory } from "./certificate-authority-dal";
import { CaType } from "./certificate-authority-enums";
-import { keyAlgorithmToAlgCfg } from "./certificate-authority-fns";
+import { getCaSigner } from "./certificate-authority-fns";
import { TCertificateAuthoritySecretDALFactory } from "./certificate-authority-secret-dal";
import { TExternalCertificateAuthorityDALFactory } from "./external-certificate-authority-dal";
import { TInternalCertificateAuthorityDALFactory } from "./internal/internal-certificate-authority-dal";
@@ -57,6 +54,7 @@ type TCertificateAuthorityQueueFactoryDep = {
pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;
pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;
internalCertificateAuthorityDAL: Pick<TInternalCertificateAuthorityDALFactory, "find">;
+ hsmConnectorService: Pick<THsmConnectorServiceFactory, "sign">;
};
export type TCertificateAuthorityQueueFactory = ReturnType<typeof certificateAuthorityQueueFactory>;
@@ -79,7 +77,8 @@ export const certificateAuthorityQueueFactory = ({
pkiSubscriberDAL,
pkiSyncDAL,
pkiSyncQueue,
- internalCertificateAuthorityDAL
+ internalCertificateAuthorityDAL,
+ hsmConnectorService
}: TCertificateAuthorityQueueFactoryDep) => {
const acmeFns = AcmeCertificateAuthorityFns({
appConnectionDAL,
@@ -151,9 +150,6 @@ export const certificateAuthorityQueueFactory = ({
crlExpiresAt.setDate(crlExpiresAt.getDate() + DEFAULT_CRL_VALIDITY_DAYS);
if (crlExpiresAt > nextRunAt) continue;
- const caSecret = await certificateAuthoritySecretDAL.findOne({ caId: internalCa.caId });
- const alg = keyAlgorithmToAlgCfg(internalCa.keyAlgorithm as CertKeyAlgorithm);
-
const ca = await certificateAuthorityDAL.findById(internalCa.caId);
const keyId = await getProjectKmsCertificateKeyId({
@@ -162,22 +158,14 @@ export const certificateAuthorityQueueFactory = ({
kmsService
});
- const kmsDecryptor = await kmsService.decryptWithKmsKey({ kmsId: keyId });
- const privateKey = await kmsDecryptor({ cipherTextBlob: caSecret.encryptedPrivateKey });
-
- let sk: CryptoKey;
- if (isPqcAlgorithm(internalCa.keyAlgorithm)) {
- sk = await getPqcCrypto().subtle.importKey("pkcs8", privateKey, alg, true, ["sign"]);
- } else {
- const skObj = crypto.nativeCrypto.createPrivateKey({ key: privateKey, format: "der", type: "pkcs8" });
- sk = await crypto.nativeCrypto.subtle.importKey(
- "pkcs8",
- skObj.export({ format: "der", type: "pkcs8" }),
- alg,
- true,
- ["sign"]
- );
- }
+ const { signer } = await getCaSigner({
+ caId: internalCa.caId,
+ certificateAuthorityDAL,
+ certificateAuthoritySecretDAL,
+ projectDAL,
+ kmsService,
+ hsmConnectorService
+ });
const revokedCerts = await certificateDAL.find({
caId: internalCa.caId,
@@ -188,7 +176,7 @@ export const certificateAuthorityQueueFactory = ({
const nextUpdate = new Date(thisUpdate);
nextUpdate.setDate(nextUpdate.getDate() + DEFAULT_CRL_VALIDITY_DAYS);
- const crl = await x509.X509CrlGenerator.create({
+ const crl = await signer.createCrl({
issuer: internalCa.dn,
thisUpdate,
nextUpdate,
@@ -196,9 +184,7 @@ export const certificateAuthorityQueueFactory = ({
serialNumber: revokedCert.serialNumber,
revocationDate: new Date(revokedCert.revokedAt as Date),
reason: revokedCert.revocationReason as number
- })),
- signingAlgorithm: alg,
- signingKey: sk
+ }))
});
const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: keyId });
diff --git a/backend/src/services/certificate-authority/certificate-authority-service.ts b/backend/src/services/certificate-authority/certificate-authority-service.ts
index fb02898e32..de3259de89 100644
--- a/backend/src/services/certificate-authority/certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-service.ts
@@ -12,6 +12,7 @@ import {
import { getProcessedPermissionRules } from "@app/lib/casl/permission-filter-utils";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { OrgServiceActor, TProjectPermission } from "@app/lib/types";
+import { CertKeySource } from "@app/services/signer/signer-enums";
import { TAppConnectionDALFactory } from "../app-connection/app-connection-dal";
import { TAppConnectionServiceFactory } from "../app-connection/app-connection-service";
@@ -26,6 +27,7 @@ import {
TAttachCertificateToRequestDTO,
TUpdateCertificateRequestStatusDTO
} from "../certificate-request/certificate-request-types";
+import type { THsmConnectorServiceFactory } from "../hsm-connector/hsm-connector-service";
import { TKmsServiceFactory } from "../kms/kms-service";
import { MaxInternalCas } from "../license-client";
import { TUsageMeteringServiceFactory } from "../license-client/usage";
@@ -68,6 +70,7 @@ import {
} from "./azure-ad-cs/azure-ad-cs-certificate-authority-types";
import { TCertificateAuthorityDALFactory } from "./certificate-authority-dal";
import { CaType } from "./certificate-authority-enums";
+import { TCertificateAuthoritySecretDALFactory } from "./certificate-authority-secret-dal";
import {
TCertificateAuthority,
TCreateCertificateAuthorityDTO,
@@ -142,6 +145,8 @@ type TCertificateAuthorityServiceFactoryDep = {
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
+ hsmConnectorService: Pick<THsmConnectorServiceFactory, "assertAttachPermission">;
+ certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
};
export type TCertificateAuthorityServiceFactory = ReturnType<typeof certificateAuthorityServiceFactory>;
@@ -166,7 +171,9 @@ export const certificateAuthorityServiceFactory = ({
resourceMetadataDAL,
gatewayV2Service,
gatewayPoolService,
- usageMeteringService
+ usageMeteringService,
+ hsmConnectorService,
+ certificateAuthoritySecretDAL
}: TCertificateAuthorityServiceFactoryDep) => {
const acmeFns = AcmeCertificateAuthorityFns({
appConnectionDAL,
@@ -282,8 +289,21 @@ export const certificateAuthorityServiceFactory = ({
);
if (type === CaType.INTERNAL) {
+ const internalConfig = configuration as TCreateInternalCertificateAuthorityDTO["configuration"];
+
+ if (internalConfig.keySource === CertKeySource.Hsm) {
+ if (!internalConfig.hsmConnectorId) {
+ throw new BadRequestError({ message: "An HSM Connector is required when the key source is HSM." });
+ }
+ await hsmConnectorService.assertAttachPermission(
+ { type: actor.type, id: actor.id, authMethod: actor.authMethod, orgId: actor.orgId },
+ internalConfig.hsmConnectorId,
+ projectId
+ );
+ }
+
const ca = await internalCertificateAuthorityService.createCa({
- ...(configuration as TCreateInternalCertificateAuthorityDTO["configuration"]),
+ ...internalConfig,
isInternal: true,
projectId,
name
@@ -407,6 +427,8 @@ export const certificateAuthorityServiceFactory = ({
});
}
+ const caSecret = await certificateAuthoritySecretDAL.findOne({ caId: id });
+
return {
id: certificateAuthority.id,
type,
@@ -414,7 +436,12 @@ export const certificateAuthorityServiceFactory = ({
subject: ProjectPermissionSub.CertificateAuthorities,
name: certificateAuthority.name,
projectId: certificateAuthority.projectId,
- configuration: certificateAuthority.internalCa,
+ configuration: {
+ ...certificateAuthority.internalCa,
+ keySource: (caSecret?.keySource as CertKeySource | undefined) ?? CertKeySource.Infisical,
+ hsmConnectorId: caSecret?.hsmConnectorId ?? undefined,
+ hsmKeyLabel: caSecret?.hsmKeyLabel ?? undefined
+ },
status: certificateAuthority.status
} as TCertificateAuthority;
}
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-schemas.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-schemas.ts
index 818e4f9f9d..5c796dce28 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-schemas.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-schemas.ts
@@ -2,6 +2,7 @@ import { z } from "zod";
import { CertificateAuthorities } from "@app/lib/api-docs/constants";
import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";
+import { CertKeySource } from "@app/services/signer/signer-enums";
import { CaStatus, CaType, InternalCaType } from "../certificate-authority-enums";
import {
@@ -24,6 +25,9 @@ type TInternalCertificateAuthorityConfiguration = {
notAfter?: string;
maxPathLength?: number | null;
keyAlgorithm: CertKeyAlgorithm;
+ keySource?: CertKeySource;
+ hsmConnectorId?: string;
+ hsmKeyLabel?: string;
dn?: string | null;
parentCaId?: string | null;
serialNumber?: string | null;
@@ -46,6 +50,16 @@ export const InternalCertificateAuthorityConfigurationSchema = z
notAfter: validateCaDateField.optional().describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.notAfter),
maxPathLength: z.number().min(-1).nullish().describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.maxPathLength),
keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.keyAlgorithm),
+ keySource: z
+ .nativeEnum(CertKeySource)
+ .optional()
+ .describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.keySource),
+ hsmConnectorId: z
+ .string()
+ .uuid()
+ .optional()
+ .describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.hsmConnectorId),
+ hsmKeyLabel: z.string().optional().describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.hsmKeyLabel),
dn: z.string().trim().nullish(),
parentCaId: z.string().uuid().nullish(),
serialNumber: z.string().trim().nullish(),
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
index 6d3f21ea46..5f63f62c57 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
@@ -19,13 +19,11 @@ import { extractX509CertFromChain } from "@app/lib/certificates/extract-certific
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import {
- derivePublicKeyFromSecret,
exportPqcKeyToDer,
exportPqcKeyToPem,
getPqcCrypto,
isPqcAlgorithm,
- isPqcCryptoKey,
- PqcCryptoKey
+ isPqcCryptoKey
} from "@app/lib/crypto/pqc";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { ms } from "@app/lib/ms";
@@ -33,6 +31,7 @@ import { alphaNumericNanoId } from "@app/lib/nanoid";
import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
+import type { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { MaxActiveCerts } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
@@ -40,6 +39,7 @@ import { TPkiCollectionDALFactory } from "@app/services/pki-collection/pki-colle
import { TPkiCollectionItemDALFactory } from "@app/services/pki-collection/pki-collection-item-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
+import { CertKeySource } from "@app/services/signer/signer-enums";
import { TCertificateAuthorityCrlDALFactory } from "../../../ee/services/certificate-authority-crl/certificate-authority-crl-dal";
import { extractCertificateFields } from "../../certificate/certificate-fns";
@@ -56,6 +56,13 @@ import { DEFAULT_CRL_VALIDITY_DAYS } from "../../certificate-common/certificate-
import { validatePqcLicense } from "../../certificate-common/certificate-utils";
import { TCertificateTemplateDALFactory } from "../../certificate-template/certificate-template-dal";
import { validateCertificateDetailsAgainstTemplate } from "../../certificate-template/certificate-template-fns";
+import {
+ buildHsmCaSigner,
+ buildLocalCaSigner,
+ caKeyAlgorithmToHsmKeyAlgorithm,
+ caKeyAlgorithmToHsmShape,
+ TCaSigner
+} from "../ca-signer";
import { TCaSigningConfigDALFactory } from "../ca-signing-config/ca-signing-config-dal";
import { CaSigningConfigType } from "../ca-signing-config/ca-signing-config-enums";
import { TCertificateAuthorityCertDALFactory } from "../certificate-authority-cert-dal";
@@ -69,7 +76,7 @@ import {
extractDnParts,
getCaCertChain, // TODO: consider rename
getCaCertChains,
- getCaCredentials,
+ getCaSigner,
keyAlgorithmToAlgCfg,
signatureAlgorithmToAlgCfg,
validateImportedCertificate
@@ -132,6 +139,10 @@ type TInternalCertificateAuthorityServiceFactoryDep = {
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
caSigningConfigDAL: Pick<TCaSigningConfigDALFactory, "findByCaId" | "create" | "deleteById" | "transaction">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
+ hsmConnectorService: Pick<
+ THsmConnectorServiceFactory,
+ "generateKeyPair" | "sign" | "getPublicKey" | "assertAttachPermission"
+ >;
};
export type TInternalCertificateAuthorityServiceFactory = ReturnType<typeof internalCertificateAuthorityServiceFactory>;
@@ -153,7 +164,8 @@ export const internalCertificateAuthorityServiceFactory = ({
permissionService,
licenseService,
caSigningConfigDAL,
- usageMeteringService
+ usageMeteringService,
+ hsmConnectorService
}: TInternalCertificateAuthorityServiceFactoryDep) => {
const $validatePqcLicense = (keyAlgorithm: string, projectId: string) =>
validatePqcLicense({ keyAlgorithm, projectId, projectDAL, licenseService });
@@ -336,8 +348,67 @@ export const internalCertificateAuthorityServiceFactory = ({
});
const alg = keyAlgorithmToAlgCfg(keyAlgorithm);
- const cryptoEngine = isPqcAlgorithm(keyAlgorithm) ? getPqcCrypto() : crypto.nativeCrypto;
- const keys = await cryptoEngine.subtle.generateKey(alg as RsaHashedKeyGenParams, true, ["sign", "verify"]);
+
+ const keySource = dto.keySource ?? CertKeySource.Infisical;
+ const useHsm = keySource === CertKeySource.Hsm;
+
+ let caSigner: TCaSigner;
+ let localKeys: CryptoKeyPair | undefined;
+ let hsmKey: { keyLabel: string; publicKeySpkiDer: Buffer } | undefined;
+
+ if (useHsm) {
+ if (!dto.hsmConnectorId) {
+ throw new BadRequestError({ message: "An HSM Connector is required when the key source is HSM." });
+ }
+ if (isPqcAlgorithm(keyAlgorithm)) {
+ throw new BadRequestError({
+ message: "Post-quantum algorithms are not supported for HSM-backed certificate authorities."
+ });
+ }
+ const shape = caKeyAlgorithmToHsmShape(keyAlgorithm);
+
+ if (!dto.isInternal) {
+ await hsmConnectorService.assertAttachPermission(
+ { type: dto.actor, id: dto.actorId, authMethod: dto.actorAuthMethod, orgId: dto.actorOrgId },
+ dto.hsmConnectorId,
+ projectId
+ );
+ }
+
+ // Kept outside the transaction below (network round-trip); an aborted tx orphans a harmless
+ // unreferenced HSM key rather than holding a DB connection open across the call.
+ const generated = await hsmConnectorService.generateKeyPair({
+ connectorId: dto.hsmConnectorId,
+ projectId,
+ keyLabel: `ca-${crypto.nativeCrypto.randomUUID()}`,
+ keyAlgorithm: caKeyAlgorithmToHsmKeyAlgorithm(keyAlgorithm)
+ });
+ hsmKey = generated;
+
+ const caPublicKey = await crypto.nativeCrypto.subtle.importKey(
+ "spki",
+ generated.publicKeySpkiDer,
+ shape.importParams,
+ true,
+ ["verify"]
+ );
+ const connectorId = dto.hsmConnectorId;
+ const { keyLabel } = generated;
+ caSigner = buildHsmCaSigner({
+ caPublicKey,
+ keyAlgorithm,
+ sign: (data, mechanism, isDigest) =>
+ hsmConnectorService.sign({ connectorId, projectId, keyLabel, mechanism, data, isDigest })
+ });
+ } else {
+ const cryptoEngine = isPqcAlgorithm(keyAlgorithm) ? getPqcCrypto() : crypto.nativeCrypto;
+ localKeys = await cryptoEngine.subtle.generateKey(alg as RsaHashedKeyGenParams, true, ["sign", "verify"]);
+ caSigner = buildLocalCaSigner({
+ privateKey: localKeys.privateKey,
+ publicKey: localKeys.publicKey,
+ signingAlgorithm: alg
+ });
+ }
const newCa = await certificateAuthorityDAL.transaction(async (tx) => {
let notBeforeDate: Date | undefined;
@@ -399,36 +470,52 @@ export const internalCertificateAuthorityServiceFactory = ({
kmsId: certificateManagerKmsId
});
- // https://nodejs.org/api/crypto.html#static-method-keyobjectfromkey
- let privateKeyDer: Buffer;
- if (isPqcCryptoKey(keys.privateKey)) {
- privateKeyDer = await exportPqcKeyToDer(keys.privateKey);
+ let caSecret;
+ if (useHsm && hsmKey) {
+ caSecret = await certificateAuthoritySecretDAL.create(
+ {
+ caId: ca.id,
+ keySource: CertKeySource.Hsm,
+ hsmConnectorId: dto.hsmConnectorId,
+ hsmKeyLabel: hsmKey.keyLabel,
+ hsmPublicKeySpki: hsmKey.publicKeySpkiDer
+ },
+ tx
+ );
} else {
- const skObj = crypto.nativeCrypto.KeyObject.from(keys.privateKey);
- privateKeyDer = skObj.export({ type: "pkcs8", format: "der" });
- }
+ const localPrivateKey = (localKeys as CryptoKeyPair).privateKey;
+ // https://nodejs.org/api/crypto.html#static-method-keyobjectfromkey
+ let privateKeyDer: Buffer;
+ if (isPqcCryptoKey(localPrivateKey)) {
+ privateKeyDer = await exportPqcKeyToDer(localPrivateKey);
+ } else {
+ const skObj = crypto.nativeCrypto.KeyObject.from(localPrivateKey);
+ privateKeyDer = skObj.export({ type: "pkcs8", format: "der" });
+ }
- const { cipherTextBlob: encryptedPrivateKey } = await kmsEncryptor({
- plainText: privateKeyDer
- });
+ const { cipherTextBlob: encryptedPrivateKey } = await kmsEncryptor({
+ plainText: privateKeyDer
+ });
- const caSecret = await certificateAuthoritySecretDAL.create(
- {
- caId: ca.id,
- encryptedPrivateKey
- },
- tx
- );
+ caSecret = await certificateAuthoritySecretDAL.create(
+ {
+ caId: ca.id,
+ keySource: CertKeySource.Infisical,
+ encryptedPrivateKey
+ },
+ tx
+ );
+ }
if (type === InternalCaType.ROOT && notAfter) {
// note: create self-signed cert only applicable for root CA
- const cert = await x509.X509CertificateGenerator.createSelfSigned({
- name: dn,
+ const cert = await caSigner.createCertificate({
+ subject: dn,
+ issuer: dn,
serialNumber,
notBefore: notBeforeDate,
notAfter: notAfterDate,
- signingAlgorithm: alg,
- keys,
+ publicKey: caSigner.caPublicKey,
extensions: [
new x509.BasicConstraintsExtension(
true,
@@ -439,7 +526,7 @@ export const internalCertificateAuthorityServiceFactory = ({
isPqcAlgorithm(keyAlgorithm) ? PQC_ROOT_CA_KEY_USAGES : ROOT_CA_KEY_USAGES,
true
),
- await x509.SubjectKeyIdentifierExtension.create(keys.publicKey)
+ await x509.SubjectKeyIdentifierExtension.create(caSigner.caPublicKey)
]
});
@@ -476,13 +563,11 @@ export const internalCertificateAuthorityServiceFactory = ({
const nextUpdate = new Date(thisUpdate);
nextUpdate.setDate(nextUpdate.getDate() + DEFAULT_CRL_VALIDITY_DAYS);
- const crl = await x509.X509CrlGenerator.create({
+ const crl = await caSigner.createCrl({
issuer: internalCa.dn,
thisUpdate,
nextUpdate,
- entries: [],
- signingAlgorithm: alg,
- signingKey: keys.privateKey
+ entries: []
});
const { cipherTextBlob: encryptedCrl } = await kmsEncryptor({
@@ -637,35 +722,29 @@ export const internalCertificateAuthorityServiceFactory = ({
await $validatePqcLicense(ca.internalCa.keyAlgorithm, ca.projectId);
- const { caPrivateKey, caPublicKey } = await getCaCredentials({
+ const { signer } = await getCaSigner({
caId,
certificateAuthorityDAL,
certificateAuthoritySecretDAL,
projectDAL,
- kmsService
+ kmsService,
+ hsmConnectorService
});
- const alg = keyAlgorithmToAlgCfg(ca.internalCa.keyAlgorithm as CertKeyAlgorithm);
-
const effectivePathLength =
maxPathLength !== undefined && maxPathLength >= 0 ? maxPathLength : (ca.internalCa.maxPathLength ?? -1);
const resolvedPathLength =
effectivePathLength === -1 || effectivePathLength === null ? undefined : effectivePathLength;
- const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({
+ const csrObj = await signer.createCsr({
name: ca.internalCa.dn,
- keys: {
- privateKey: caPrivateKey,
- publicKey: caPublicKey
- },
- signingAlgorithm: alg,
extensions: [
new x509.BasicConstraintsExtension(true, resolvedPathLength, true),
new x509.KeyUsagesExtension(
isPqcAlgorithm(ca.internalCa.keyAlgorithm) ? PQC_CA_KEY_USAGES : CLASSICAL_CA_KEY_USAGES,
true
),
- await x509.SubjectKeyIdentifierExtension.create(caPublicKey)
+ await x509.SubjectKeyIdentifierExtension.create(signer.caPublicKey)
],
attributes: [new x509.ChallengePasswordAttribute("password")]
});
@@ -733,16 +812,15 @@ export const internalCertificateAuthorityServiceFactory = ({
kmsId: certificateManagerKmsId
});
- const { caPrivateKey, caPublicKey, caSecret } = await getCaCredentials({
+ const { caSecret, signer } = await getCaSigner({
caId: ca.id,
certificateAuthorityDAL,
certificateAuthoritySecretDAL,
projectDAL,
- kmsService
+ kmsService,
+ hsmConnectorService
});
- const alg = keyAlgorithmToAlgCfg(ca.internalCa.keyAlgorithm as CertKeyAlgorithm);
-
const kmsDecryptor = await kmsService.decryptWithKmsKey({
kmsId: certificateManagerKmsId
});
@@ -766,16 +844,13 @@ export const internalCertificateAuthorityServiceFactory = ({
}
const notBeforeDate = new Date();
- const cert = await x509.X509CertificateGenerator.createSelfSigned({
- name: ca.internalCa.dn,
+ const cert = await signer.createCertificate({
+ subject: ca.internalCa.dn,
+ issuer: ca.internalCa.dn,
serialNumber,
notBefore: notBeforeDate,
notAfter: new Date(notAfter),
- signingAlgorithm: alg,
- keys: {
- privateKey: caPrivateKey,
- publicKey: caPublicKey
- },
+ publicKey: signer.caPublicKey,
extensions: [
new x509.BasicConstraintsExtension(
true,
@@ -788,7 +863,7 @@ export const internalCertificateAuthorityServiceFactory = ({
isPqcAlgorithm(ca.internalCa.keyAlgorithm) ? PQC_ROOT_CA_KEY_USAGES : ROOT_CA_KEY_USAGES,
true
),
- await x509.SubjectKeyIdentifierExtension.create(caPublicKey)
+ await x509.SubjectKeyIdentifierExtension.create(signer.caPublicKey)
]
});
@@ -839,12 +914,13 @@ export const internalCertificateAuthorityServiceFactory = ({
}
const parentCa = await certificateAuthorityDAL.findByIdWithAssociatedCa(ca.internalCa.parentCaId);
- const { caPrivateKey: parentCaPrivateKey } = await getCaCredentials({
+ const { signer: parentSigner } = await getCaSigner({
caId: parentCa.id,
certificateAuthorityDAL,
certificateAuthoritySecretDAL,
projectDAL,
- kmsService
+ kmsService,
+ hsmConnectorService
});
if (!parentCa.internalCa) {
@@ -877,13 +953,8 @@ export const internalCertificateAuthorityServiceFactory = ({
});
}
- const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({
+ const csrObj = await signer.createCsr({
name: ca.internalCa.dn,
- keys: {
- privateKey: caPrivateKey,
- publicKey: caPublicKey
- },
- signingAlgorithm: alg,
extensions: [
new x509.KeyUsagesExtension(
isPqcAlgorithm(ca.internalCa.keyAlgorithm) ? PQC_CA_KEY_USAGES : CLASSICAL_CA_KEY_USAGES
@@ -893,16 +964,13 @@ export const internalCertificateAuthorityServiceFactory = ({
});
const notBeforeDate = new Date();
- const parentAlg = keyAlgorithmToAlgCfg(parentCa.internalCa.keyAlgorithm as CertKeyAlgorithm);
- const intermediateCert = await x509.X509CertificateGenerator.create({
+ const intermediateCert = await parentSigner.createCertificate({
serialNumber,
subject: csrObj.subject,
issuer: parentCaCertObj.subject,
notBefore: notBeforeDate,
notAfter: new Date(notAfter),
- signingKey: parentCaPrivateKey,
publicKey: csrObj.publicKey,
- signingAlgorithm: parentAlg,
extensions: [
new x509.KeyUsagesExtension(
isPqcAlgorithm(ca.internalCa.keyAlgorithm) ? PQC_CA_KEY_USAGES : CLASSICAL_CA_KEY_USAGES,
@@ -1205,8 +1273,6 @@ export const internalCertificateAuthorityServiceFactory = ({
throw new BadRequestError({ message: "CA is expired" });
}
- const alg = keyAlgorithmToAlgCfg(ca.internalCa.keyAlgorithm as CertKeyAlgorithm);
-
const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
projectId: ca.projectId,
projectDAL,
@@ -1254,12 +1320,13 @@ export const internalCertificateAuthorityServiceFactory = ({
throw new BadRequestError({ message: "notAfter date is after CA certificate's notAfter date" });
}
- const { caPrivateKey, caSecret } = await getCaCredentials({
+ const { caSecret, signer } = await getCaSigner({
caId: ca.id,
certificateAuthorityDAL,
certificateAuthoritySecretDAL,
projectDAL,
- kmsService
+ kmsService,
+ hsmConnectorService
});
const serialNumber = createSerialNumber();
@@ -1273,15 +1340,13 @@ export const internalCertificateAuthorityServiceFactory = ({
ca.internalCa.disableManagedCrlDistributionPointUrl
);
- const intermediateCert = await x509.X509CertificateGenerator.create({
+ const intermediateCert = await signer.createCertificate({
serialNumber,
subject: csrObj.subject,
issuer: caCertObj.subject,
notBefore: notBeforeDate,
notAfter: notAfterDate,
- signingKey: caPrivateKey,
publicKey: csrObj.publicKey,
- signingAlgorithm: alg,
extensions: [
new x509.KeyUsagesExtension(
isPqcAlgorithm(csrObj.publicKey.algorithm.name) ? PQC_CA_KEY_USAGES : CLASSICAL_CA_KEY_USAGES,
@@ -1413,13 +1478,15 @@ export const internalCertificateAuthorityServiceFactory = ({
// TODO: validate that latest key-pair of CA is used to sign the certificate
// once renewal with new key pair is supported
- const { caSecret, caPublicKey } = await getCaCredentials({
+ const { caSecret, signer } = await getCaSigner({
caId: ca.id,
certificateAuthorityDAL,
certificateAuthoritySecretDAL,
projectDAL,
- kmsService
+ kmsService,
+ hsmConnectorService
});
+ const { caPublicKey } = signer;
const caPublicKeySpki = isPqcCryptoKey(caPublicKey)
? await exportPqcKeyToDer(caPublicKey)
@@ -1530,79 +1597,23 @@ export const internalCertificateAuthorityServiceFactory = ({
await $validatePqcLicense(intermediateCa.internalCa.keyAlgorithm, intermediateCa.projectId);
await $validatePqcLicense(parentCa.internalCa.keyAlgorithm, parentCa.projectId);
- const caSecret = await certificateAuthoritySecretDAL.findOne(
- {
- caId: intermediateCa.id
- },
- tx
- );
-
- if (!caSecret) throw new NotFoundError({ message: "Failed to find CA secret" });
-
- const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
- projectId: intermediateCa.projectId,
+ const { signer } = await getCaSigner({
+ caId: intermediateCa.id,
+ certificateAuthorityDAL,
+ certificateAuthoritySecretDAL,
projectDAL,
- kmsService
- });
-
- const kmsDecryptor = await kmsService.decryptWithKmsKey({
- kmsId: certificateManagerKmsId
- });
-
- const caPrivateKey = await kmsDecryptor({
- cipherTextBlob: caSecret.encryptedPrivateKey
+ kmsService,
+ hsmConnectorService
});
const caKeyAlg = intermediateCa.internalCa.keyAlgorithm as CertKeyAlgorithm;
- const alg = keyAlgorithmToAlgCfg(caKeyAlg);
-
- let privateKey: CryptoKey;
- let publicKey: CryptoKey;
-
- if (isPqcAlgorithm(caKeyAlg)) {
- const pqcCrypto = getPqcCrypto();
- privateKey = await pqcCrypto.subtle.importKey("pkcs8", caPrivateKey, alg as RsaHashedImportParams, true, [
- "sign"
- ]);
- const { raw: pubRaw, spkiDer } = await derivePublicKeyFromSecret(
- caKeyAlg,
- (privateKey as InstanceType<typeof PqcCryptoKey>).rawKey
- );
- publicKey = new PqcCryptoKey(pubRaw, caKeyAlg, "public", ["verify"], spkiDer);
- } else {
- const skObj = crypto.nativeCrypto.createPrivateKey({ key: caPrivateKey, format: "der", type: "pkcs8" });
- const pkObj = crypto.nativeCrypto.createPublicKey(skObj);
- const publicKeyBuffer = pkObj.export({ format: "der", type: "spki" });
- privateKey = await crypto.nativeCrypto.subtle.importKey(
- "pkcs8",
- caPrivateKey,
- alg as RsaHashedImportParams,
- true,
- ["sign"]
- );
- publicKey = await crypto.nativeCrypto.subtle.importKey(
- "spki",
- publicKeyBuffer,
- alg as RsaHashedImportParams,
- true,
- ["verify"]
- );
- }
-
- const keys = {
- privateKey,
- publicKey
- };
-
- const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({
+ const csrObj = await signer.createCsr({
name: intermediateCa.internalCa.dn,
- keys,
- signingAlgorithm: alg,
extensions: [
new x509.BasicConstraintsExtension(true, maxPathLength === -1 ? undefined : maxPathLength, true),
new x509.KeyUsagesExtension(isPqcAlgorithm(caKeyAlg) ? PQC_CA_KEY_USAGES : CLASSICAL_CA_KEY_USAGES, true),
- await x509.SubjectKeyIdentifierExtension.create(keys.publicKey)
+ await x509.SubjectKeyIdentifierExtension.create(signer.caPublicKey)
]
});
@@ -1853,12 +1864,13 @@ export const internalCertificateAuthorityServiceFactory = ({
attributes: [new x509.ChallengePasswordAttribute("password")]
});
- const { caPrivateKey, caSecret } = await getCaCredentials({
+ const { caSecret, signer } = await getCaSigner({
caId: ca.id,
certificateAuthorityDAL,
certificateAuthoritySecretDAL,
projectDAL,
kmsService,
+ hsmConnectorService,
signatureAlgorithm: signingAlg
});
@@ -1987,15 +1999,13 @@ export const internalCertificateAuthorityServiceFactory = ({
}
const serialNumber = createSerialNumber();
- const leafCert = await x509.X509CertificateGenerator.create({
+ const leafCert = await signer.createCertificate({
serialNumber,
subject: csrObj.subject,
issuer: caCertObj.subject,
notBefore: notBeforeDate,
notAfter: notAfterDate,
- signingKey: caPrivateKey,
publicKey: csrObj.publicKey,
- signingAlgorithm: signingAlg,
extensions
});
@@ -2266,12 +2276,13 @@ export const internalCertificateAuthorityServiceFactory = ({
const dn = extractDnParts(csrObj.subjectName);
const cn = (commonName || dn.commonName) ?? "";
- const { caPrivateKey, caSecret } = await getCaCredentials({
+ const { caSecret, signer } = await getCaSigner({
caId: ca.id,
certificateAuthorityDAL,
certificateAuthoritySecretDAL,
projectDAL,
kmsService,
+ hsmConnectorService,
signatureAlgorithm: alg
});
@@ -2467,15 +2478,13 @@ export const internalCertificateAuthorityServiceFactory = ({
}
const serialNumber = createSerialNumber();
- const leafCert = await x509.X509CertificateGenerator.create({
+ const leafCert = await signer.createCertificate({
serialNumber,
subject: subjectOverride || csrObj.subject,
issuer: caCertObj.subject,
notBefore: notBeforeDate,
notAfter: notAfterDate,
- signingKey: caPrivateKey,
publicKey: csrObj.publicKey,
- signingAlgorithm: alg,
extensions
});
@@ -2649,60 +2658,26 @@ export const internalCertificateAuthorityServiceFactory = ({
kmsId: certificateManagerKmsId
});
- const caSecret = await certificateAuthoritySecretDAL.findOne({ caId });
- if (!caSecret) throw new NotFoundError({ message: "CA secret not found" });
+ if (!ca.internalCa) throw new BadRequestError({ message: "CA internal configuration not found" });
- const kmsDecryptor = await kmsService.decryptWithKmsKey({
- kmsId: certificateManagerKmsId
+ const { caSecret, signer } = await getCaSigner({
+ caId,
+ certificateAuthorityDAL,
+ certificateAuthoritySecretDAL,
+ projectDAL,
+ kmsService,
+ hsmConnectorService
});
- const privateKeyBlob = await kmsDecryptor({ cipherTextBlob: caSecret.encryptedPrivateKey });
- if (!ca.internalCa) throw new BadRequestError({ message: "CA internal configuration not found" });
const rootKeyAlg = ca.internalCa.keyAlgorithm as CertKeyAlgorithm;
- const alg = keyAlgorithmToAlgCfg(rootKeyAlg);
-
- let actualPrivateKey: CryptoKey;
- let actualPublicKey: CryptoKey;
-
- if (isPqcAlgorithm(rootKeyAlg)) {
- const pqcCrypto = getPqcCrypto();
- actualPrivateKey = await pqcCrypto.subtle.importKey("pkcs8", privateKeyBlob, alg as RsaHashedImportParams, true, [
- "sign"
- ]);
-
- const { raw: pubKeyRaw, spkiDer } = await derivePublicKeyFromSecret(
- rootKeyAlg,
- (actualPrivateKey as InstanceType<typeof PqcCryptoKey>).rawKey
- );
- actualPublicKey = new PqcCryptoKey(pubKeyRaw, rootKeyAlg, "public", ["verify"], spkiDer);
- } else {
- const skObj = crypto.nativeCrypto.createPrivateKey({ key: privateKeyBlob, format: "der", type: "pkcs8" });
- const pkObj = crypto.nativeCrypto.createPublicKey(skObj);
- const publicKeyBuffer = pkObj.export({ format: "der", type: "spki" });
-
- actualPrivateKey = await crypto.nativeCrypto.subtle.importKey(
- "pkcs8",
- skObj.export({ format: "der", type: "pkcs8" }),
- alg as RsaHashedImportParams,
- true,
- ["sign"]
- );
- actualPublicKey = await crypto.nativeCrypto.subtle.importKey(
- "spki",
- publicKeyBuffer,
- alg as RsaHashedImportParams,
- true,
- ["verify"]
- );
- }
- const cert = await x509.X509CertificateGenerator.createSelfSigned({
- name: ca.internalCa.dn,
+ const cert = await signer.createCertificate({
+ subject: ca.internalCa.dn,
+ issuer: ca.internalCa.dn,
serialNumber,
notBefore: notBeforeDate,
notAfter: notAfterDate,
- signingAlgorithm: alg,
- keys: { privateKey: actualPrivateKey, publicKey: actualPublicKey },
+ publicKey: signer.caPublicKey,
extensions: [
new x509.BasicConstraintsExtension(
true,
@@ -2712,7 +2687,7 @@ export const internalCertificateAuthorityServiceFactory = ({
true
),
new x509.KeyUsagesExtension(isPqcAlgorithm(rootKeyAlg) ? PQC_ROOT_CA_KEY_USAGES : ROOT_CA_KEY_USAGES, true),
- await x509.SubjectKeyIdentifierExtension.create(actualPublicKey)
+ await x509.SubjectKeyIdentifierExtension.create(signer.caPublicKey)
]
});
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
index e9f37ef293..0f56dede8c 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
@@ -11,8 +11,10 @@ import {
CertKeyUsage,
CertSignatureAlgorithm
} from "@app/services/certificate/certificate-types";
+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 { CertKeySource } from "@app/services/signer/signer-enums";
import { TCertificateAuthorityCertDALFactory } from "../certificate-authority-cert-dal";
import { TCertificateAuthorityDALFactory } from "../certificate-authority-dal";
@@ -49,6 +51,8 @@ export type TCreateCaDTO =
notAfter?: string;
maxPathLength?: number | null;
keyAlgorithm: CertKeyAlgorithm;
+ keySource?: CertKeySource;
+ hsmConnectorId?: string;
crlDistributionPointUrls?: string[];
disableManagedCrlDistributionPointUrl?: boolean;
}
@@ -69,6 +73,8 @@ export type TCreateCaDTO =
notAfter?: string;
maxPathLength?: number | null;
keyAlgorithm: CertKeyAlgorithm;
+ keySource?: CertKeySource;
+ hsmConnectorId?: string;
crlDistributionPointUrls?: string[];
disableManagedCrlDistributionPointUrl?: boolean;
} & Omit<TProjectPermission, "projectId">);
@@ -317,6 +323,16 @@ export type TGetCaCredentialsDTO = {
signatureAlgorithm?: RsaHashedImportParams | EcKeyImportParams;
};
+export type TGetCaSignerDTO = {
+ caId: string;
+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;
+ certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
+ projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
+ kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;
+ hsmConnectorService: Pick<THsmConnectorServiceFactory, "sign">;
+ signatureAlgorithm?: RsaHashedImportParams | EcKeyImportParams;
+};
+
export type TGetCaCertChainsDTO = {
caId: string;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById">;
@@ -341,6 +357,7 @@ export type TRebuildCaCrlDTO = {
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
certificateDAL: Pick<TCertificateDALFactory, "find">;
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "decryptWithKmsKey" | "encryptWithKmsKey">;
+ hsmConnectorService: Pick<THsmConnectorServiceFactory, "sign">;
};
export type TRotateCaCrlTriggerDTO = {
diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.ts
index 0b531e9439..7a179ad48e 100644
--- a/backend/src/services/certificate/certificate-service.ts
+++ b/backend/src/services/certificate/certificate-service.ts
@@ -26,6 +26,7 @@ import { caSupportsCapability } from "@app/services/certificate-authority/certif
import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate-authority/certificate-authority-secret-dal";
import { TCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/certificate-authority-service";
import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";
+import type { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { MaxActiveCerts } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
@@ -107,6 +108,7 @@ type TCertificateServiceFactoryDep = {
pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
+ hsmConnectorService: Pick<THsmConnectorServiceFactory, "sign">;
};
export type TCertificateServiceFactory = ReturnType<typeof certificateServiceFactory>;
@@ -132,7 +134,8 @@ export const certificateServiceFactory = ({
pkiAlertV2Queue,
pkiApplicationDAL,
licenseService,
- usageMeteringService
+ usageMeteringService,
+ hsmConnectorService
}: TCertificateServiceFactoryDep) => {
const $canActOnCertViaApplication = async (
cert: { applicationId?: string | null; projectId: string },
@@ -576,7 +579,8 @@ export const certificateServiceFactory = ({
certificateAuthoritySecretDAL,
projectDAL,
certificateDAL,
- kmsService
+ kmsService,
+ hsmConnectorService
});
}
diff --git a/backend/src/services/hsm-connector/hsm-connector-dal.ts b/backend/src/services/hsm-connector/hsm-connector-dal.ts
index 545134911f..d1b69afd75 100644
--- a/backend/src/services/hsm-connector/hsm-connector-dal.ts
+++ b/backend/src/services/hsm-connector/hsm-connector-dal.ts
@@ -4,6 +4,7 @@ import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex";
+import { CaStatus, InternalCaType } from "@app/services/certificate-authority/certificate-authority-enums";
export type THsmConnectorDALFactory = ReturnType<typeof hsmConnectorDALFactory>;
@@ -22,6 +23,18 @@ export const hsmConnectorDALFactory = (db: TDbClient) => {
}
};
+ const countReferencingCertificateAuthorities = async (connectorId: string, tx?: Knex): Promise<number> => {
+ try {
+ const result = await (tx || db)(TableName.CertificateAuthoritySecret)
+ .where("hsmConnectorId", connectorId)
+ .count<{ count: string }[]>("id as count")
+ .first();
+ return Number(result?.count ?? 0);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "HsmConnectorDAL.countReferencingCertificateAuthorities" });
+ }
+ };
+
const findByProjectId = async (projectId: string) => {
try {
return await db
@@ -48,6 +61,33 @@ export const hsmConnectorDALFactory = (db: TDbClient) => {
baseQuery.clone().count<{ count: string }[]>("id as count").first()
]);
+ const caRows =
+ offset === 0
+ ? await db
+ .replicaNode()(TableName.CertificateAuthoritySecret)
+ .where(`${TableName.CertificateAuthoritySecret}.hsmConnectorId`, connectorId)
+ .join(
+ TableName.CertificateAuthority,
+ `${TableName.CertificateAuthority}.id`,
+ `${TableName.CertificateAuthoritySecret}.caId`
+ )
+ .join(
+ TableName.InternalCertificateAuthority,
+ `${TableName.InternalCertificateAuthority}.caId`,
+ `${TableName.CertificateAuthoritySecret}.caId`
+ )
+ .select(
+ db.ref("id").withSchema(TableName.CertificateAuthority).as("id"),
+ db.ref("name").withSchema(TableName.CertificateAuthority).as("name"),
+ db.ref("status").withSchema(TableName.CertificateAuthority).as("status"),
+ db.ref("type").withSchema(TableName.InternalCertificateAuthority).as("type"),
+ db.ref("commonName").withSchema(TableName.InternalCertificateAuthority).as("commonName"),
+ db.ref("hsmKeyLabel").withSchema(TableName.CertificateAuthoritySecret).as("hsmKeyLabel"),
+ db.ref("createdAt").withSchema(TableName.CertificateAuthority).as("createdAt")
+ )
+ .orderBy(`${TableName.CertificateAuthority}.createdAt`, "desc")
+ : [];
+
return {
certificates: rows.map((r) => ({
id: r.id,
@@ -57,6 +97,15 @@ export const hsmConnectorDALFactory = (db: TDbClient) => {
hsmKeyLabel: (r.hsmKeyLabel as string | null) ?? null,
createdAt: r.createdAt
})),
+ certificateAuthorities: caRows.map((r) => ({
+ id: r.id,
+ name: r.name,
+ commonName: (r.commonName as string | null) ?? null,
+ status: r.status as CaStatus,
+ type: r.type as InternalCaType,
+ hsmKeyLabel: (r.hsmKeyLabel as string | null) ?? null,
+ createdAt: r.createdAt
+ })),
totalCount: Number(totalCountResult?.count ?? 0)
};
} catch (error) {
@@ -67,6 +116,7 @@ export const hsmConnectorDALFactory = (db: TDbClient) => {
return {
...hsmConnectorOrm,
countReferencingCertificates,
+ countReferencingCertificateAuthorities,
findByProjectId,
listLinkedResources
};
diff --git a/backend/src/services/hsm-connector/hsm-connector-service.ts b/backend/src/services/hsm-connector/hsm-connector-service.ts
index 720c967a11..a60230a03b 100644
--- a/backend/src/services/hsm-connector/hsm-connector-service.ts
+++ b/backend/src/services/hsm-connector/hsm-connector-service.ts
@@ -320,13 +320,33 @@ export const hsmConnectorServiceFactory = ({
await assertProjectPermission(actor, row.projectId, ProjectPermissionHsmConnectorActions.Delete);
await hsmConnectorDAL.transaction(async (tx) => {
- const refCount = await hsmConnectorDAL.countReferencingCertificates(row.id, tx);
- if (refCount > 0) {
+ const [certCount, caCount] = await Promise.all([
+ hsmConnectorDAL.countReferencingCertificates(row.id, tx),
+ hsmConnectorDAL.countReferencingCertificateAuthorities(row.id, tx)
+ ]);
+ if (certCount > 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.`
+ message: `HSM Connector is in use by ${certCount} certificate(s). Open the connector to see the linked certificates panel and re-issue or retire them first.`
});
}
- await hsmConnectorDAL.deleteById(row.id, tx);
+ if (caCount > 0) {
+ throw new BadRequestError({
+ message: `HSM Connector is in use by ${caCount} certificate authority(ies). Delete or migrate those CAs before removing this connector.`
+ });
+ }
+ try {
+ await hsmConnectorDAL.deleteById(row.id, tx);
+ } catch (err) {
+ // 23503 = FK violation: something started referencing this connector after the count check.
+ const cause = (err as { error?: { code?: string } })?.error;
+ if (cause?.code === "23503") {
+ throw new BadRequestError({
+ message:
+ "HSM Connector is in use by a certificate or certificate authority. Re-issue or retire them, or delete/migrate the CAs, before removing this connector."
+ });
+ }
+ throw err;
+ }
});
return { id: row.id, name: row.name, projectId: row.projectId };
};
diff --git a/docs/documentation/platform/pki/ca/private-ca.mdx b/docs/documentation/platform/pki/ca/private-ca.mdx
index f37d94e157..ca7790a893 100644
--- a/docs/documentation/platform/pki/ca/private-ca.mdx
+++ b/docs/documentation/platform/pki/ca/private-ca.mdx
@@ -46,6 +46,8 @@ 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 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.
+ - 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`.
- Name: A slug-friendly name for the CA.
- Organization (O): The organization name.
- Country (C): The country code.
@@ -252,6 +254,31 @@ Create a simple Private CA hierarchy with a root CA and intermediate CA.
</Tab>
</Tabs>
+## HSM-backed Internal CAs
+
+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.
+
+<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.
+</Note>
+
+To create an HSM-backed CA over the API, set `keySource` to `hsm` and supply the `hsmConnectorId` in the request.
+
+```bash Request
+curl --location --request POST 'https://app.infisical.com/api/v1/cert-manager/ca/internal' \
+ --header 'Authorization: Bearer <access-token>' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "type": "root",
+ "commonName": "My HSM Root CA",
+ "keyAlgorithm": "ECDSA_P384",
+ "keySource": "hsm",
+ "hsmConnectorId": "<hsm-connector-id>"
+ }'
+```
+
## FAQ
<AccordionGroup>
@@ -261,6 +288,9 @@ Create a simple Private CA hierarchy with a root CA and intermediate CA.
<Accordion title="Does Infisical support chaining an Intermediate CA to an external CA?">
Yes. 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 [Azure AD CS](/documentation/platform/pki/ca/azure-adcs#signing-internal-intermediate-cas-with-ad-cs) 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).
+ </Accordion>
</AccordionGroup>
## What's Next?
@@ -282,3 +312,9 @@ Create a simple Private CA hierarchy with a root CA and intermediate CA.
Set up Applications to issue certificates.
</Card>
</CardGroup>
+
+<CardGroup cols={2}>
+ <Card title="HSM Connectors" icon="shield-halved" href="/documentation/platform/pki/settings/hsm-connectors">
+ Keep the CA signing key inside your own Hardware Security Module.
+ </Card>
+</CardGroup>
diff --git a/frontend/src/hooks/api/ca/types.ts b/frontend/src/hooks/api/ca/types.ts
index 707c8b26a5..09b4cf5036 100644
--- a/frontend/src/hooks/api/ca/types.ts
+++ b/frontend/src/hooks/api/ca/types.ts
@@ -1,4 +1,5 @@
import { CertExtendedKeyUsage, CertKeyAlgorithm, CertKeyUsage } from "../certificates/enums";
+import { CertKeySource } from "../signers/types";
import {
AcmeDnsProvider,
CaRenewalType,
@@ -128,6 +129,9 @@ export type TInternalCertificateAuthority = {
locality: string;
maxPathLength: number;
keyAlgorithm: CertKeyAlgorithm;
+ keySource?: CertKeySource;
+ hsmConnectorId?: string;
+ hsmKeyLabel?: string;
notAfter?: string;
notBefore?: string;
dn?: string;
diff --git a/frontend/src/hooks/api/hsmConnectors/queries.tsx b/frontend/src/hooks/api/hsmConnectors/queries.tsx
index a2658f0aa7..f6554cf183 100644
--- a/frontend/src/hooks/api/hsmConnectors/queries.tsx
+++ b/frontend/src/hooks/api/hsmConnectors/queries.tsx
@@ -2,7 +2,11 @@ import { useQuery, UseQueryOptions } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
-import { THsmConnector, THsmConnectorLinkedCertificate } from "./types";
+import {
+ THsmConnector,
+ THsmConnectorLinkedCertificate,
+ THsmConnectorLinkedCertificateAuthority
+} from "./types";
export const hsmConnectorKeys = {
all: ["hsm-connectors"] as const,
@@ -49,7 +53,11 @@ export const useListHsmConnectorLinkedResources = (
connectorId: string | undefined,
pagination?: { offset?: number; limit?: number },
options?: Omit<
- UseQueryOptions<{ certificates: THsmConnectorLinkedCertificate[]; totalCount: number }>,
+ UseQueryOptions<{
+ certificates: THsmConnectorLinkedCertificate[];
+ certificateAuthorities: THsmConnectorLinkedCertificateAuthority[];
+ totalCount: number;
+ }>,
"queryKey" | "queryFn"
>
) => {
@@ -61,12 +69,14 @@ export const useListHsmConnectorLinkedResources = (
queryFn: async () => {
const { data } = await apiRequest.get<{
certificates: THsmConnectorLinkedCertificate[];
+ certificateAuthorities: THsmConnectorLinkedCertificateAuthority[];
totalCount: number;
}>(`/api/v1/cert-manager/hsm-connectors/${connectorId}/linked-resources`, {
params: { offset, limit }
});
return {
certificates: data.certificates ?? [],
+ certificateAuthorities: data.certificateAuthorities ?? [],
totalCount: data.totalCount ?? 0
};
},
diff --git a/frontend/src/hooks/api/hsmConnectors/types.ts b/frontend/src/hooks/api/hsmConnectors/types.ts
index 327b6b5110..26aec9d398 100644
--- a/frontend/src/hooks/api/hsmConnectors/types.ts
+++ b/frontend/src/hooks/api/hsmConnectors/types.ts
@@ -64,3 +64,13 @@ export type THsmConnectorLinkedCertificate = {
hsmKeyLabel: string | null;
createdAt: string;
};
+
+export type THsmConnectorLinkedCertificateAuthority = {
+ id: string;
+ name: string;
+ commonName: string | null;
+ status: string;
+ type: string;
+ hsmKeyLabel: string | null;
+ createdAt: string;
+};
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
index 8ba8c41f17..c0b48f58af 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
@@ -60,6 +60,8 @@ import { caStatusToNameMap, caTypeToNameMap } from "@app/hooks/api/ca/constants"
import { caKeys } from "@app/hooks/api/ca/queries";
import { TInternalCertificateAuthority } from "@app/hooks/api/ca/types";
import { certKeyAlgorithmToNameMap } from "@app/hooks/api/certificates/constants";
+import { useGetHsmConnectorById } from "@app/hooks/api/hsmConnectors";
+import { CertKeySource } from "@app/hooks/api/signers";
import { usePopUp } from "@app/hooks/usePopUp";
type Props = {
@@ -112,6 +114,11 @@ export const CaDetailsSection = ({ caId }: Props) => {
const parentCa = parentCaData as TInternalCertificateAuthority | undefined;
+ const isHsmBacked = ca?.configuration?.keySource === CertKeySource.Hsm;
+ const { data: hsmConnector } = useGetHsmConnectorById(ca?.configuration?.hsmConnectorId, {
+ enabled: Boolean(isHsmBacked && ca?.configuration?.hsmConnectorId)
+ });
+
const { data: autoRenewal } = useGetCaAutoRenewal(caId, {
enabled:
Boolean(caId) &&
@@ -287,6 +294,34 @@ export const CaDetailsSection = ({ caId }: Props) => {
<DetailValue>{certKeyAlgorithmToNameMap[ca.configuration.keyAlgorithm]}</DetailValue>
</Detail>
+ <Detail>
+ <DetailLabel>Key Source</DetailLabel>
+ <DetailValue>
+ <Badge variant={isHsmBacked ? "info" : "neutral"}>
+ {isHsmBacked ? "HSM" : "Infisical"}
+ </Badge>
+ </DetailValue>
+ </Detail>
+
+ {isHsmBacked && (
+ <>
+ <Detail>
+ <DetailLabel>HSM Connector</DetailLabel>
+ <DetailValue className="break-all">
+ {hsmConnector?.name ?? ca.configuration.hsmConnectorId ?? "-"}
+ </DetailValue>
+ </Detail>
+ {ca.configuration.hsmKeyLabel && (
+ <Detail>
+ <DetailLabel>HSM Key Label</DetailLabel>
+ <DetailValue className="font-mono text-xs break-all">
+ {ca.configuration.hsmKeyLabel}
+ </DetailValue>
+ </Detail>
+ )}
+ </>
+ )}
+
{showAutoRenewal && (
<>
<Detail>
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx
index 177d9a0d38..1357a03dc8 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx
@@ -1,3 +1,4 @@
+import { useState } from "react";
import { PlusIcon } from "lucide-react";
import { createNotification } from "@app/components/notifications";
@@ -22,6 +23,7 @@ import { CaStatus, CaType, useDeleteCa, useUpdateCa } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
import { PkiDocsUrls } from "../../pki-docs-urls";
+import { CreateCaWizard } from "./CreateCaWizard/CreateCaWizard";
import { CaCertModal } from "./CaCertModal";
import { CaInstallCertModal } from "./CaInstallCertModal";
import { CaModal } from "./CaModal";
@@ -31,6 +33,7 @@ export const CaSection = () => {
const { currentProject } = useProject();
const { mutateAsync: deleteCa } = useDeleteCa();
const { mutateAsync: updateCa } = useUpdateCa();
+ const [isCreateWizardOpen, setIsCreateWizardOpen] = useState(false);
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
"ca",
@@ -85,7 +88,7 @@ export const CaSection = () => {
{(isAllowed) => (
<Button
variant="project"
- onClick={() => handlePopUpOpen("ca")}
+ onClick={() => setIsCreateWizardOpen(true)}
isDisabled={!isAllowed}
>
<PlusIcon />
@@ -98,6 +101,7 @@ export const CaSection = () => {
<CardContent>
<CaTable handlePopUpOpen={handlePopUpOpen} />
</CardContent>
+ <CreateCaWizard isOpen={isCreateWizardOpen} onOpenChange={setIsCreateWizardOpen} />
<CaModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
<CaInstallCertModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
<CaCertModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/BasicsStep.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/BasicsStep.tsx
new file mode 100644
index 0000000000..c909c1b25f
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/BasicsStep.tsx
@@ -0,0 +1,74 @@
+import { Controller, useForm } from "react-hook-form";
+
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3";
+import { InternalCaType } from "@app/hooks/api/ca/enums";
+
+import { CaWizardForm } from "./schemas";
+
+type Props = {
+ form: ReturnType<typeof useForm<CaWizardForm>>;
+};
+
+export const BasicsStep = ({ form }: Props) => {
+ return (
+ <FieldGroup>
+ <Controller
+ name="name"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Name <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input {...field} placeholder="my-internal-ca" isError={Boolean(error)} />
+ <FieldDescription>A unique slug used to reference this CA.</FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ name="type"
+ control={form.control}
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>
+ CA Type <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value={InternalCaType.ROOT}>Root</SelectItem>
+ <SelectItem value={InternalCaType.INTERMEDIATE}>Intermediate</SelectItem>
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ {field.value === InternalCaType.ROOT
+ ? "Self-signed and active immediately."
+ : "Created pending a certificate; generate its CSR and have a parent CA sign it."}
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ </FieldGroup>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/CreateCaWizard.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/CreateCaWizard.tsx
new file mode 100644
index 0000000000..a29d731092
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/CreateCaWizard.tsx
@@ -0,0 +1,260 @@
+import { useMemo, useState } from "react";
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { format } from "date-fns";
+import { ShieldIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ DocumentationLinkBadge,
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ Stepper,
+ StepperList,
+ StepperStep
+} from "@app/components/v3";
+import { useSubscription } from "@app/context";
+import { useCreateCa } from "@app/hooks/api/ca";
+import { CaStatus, CaType, InternalCaType } from "@app/hooks/api/ca/enums";
+import { CertKeyAlgorithm } from "@app/hooks/api/certificates/enums";
+import { useListHsmConnectors } from "@app/hooks/api/hsmConnectors";
+import { CertKeySource } from "@app/hooks/api/signers";
+
+import { PkiDocsUrls } from "../../../pki-docs-urls";
+import { BasicsStep } from "./BasicsStep";
+import { DistributionStep } from "./DistributionStep";
+import { KeyValidityStep } from "./KeyValidityStep";
+import { CaWizardForm, caWizardSchema } from "./schemas";
+import { SubjectStep } from "./SubjectStep";
+import { STEPS } from "./types";
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (open: boolean) => void;
+};
+
+const getDateTenYearsFromToday = () => {
+ const date = new Date();
+ date.setFullYear(date.getFullYear() + 10);
+ return format(date, "yyyy-MM-dd");
+};
+
+const DEFAULT_VALUES: CaWizardForm = {
+ name: "",
+ type: InternalCaType.ROOT,
+ organization: "",
+ ou: "",
+ country: "",
+ province: "",
+ locality: "",
+ commonName: "",
+ keySource: CertKeySource.Infisical,
+ hsmConnectorId: null,
+ keyAlgorithm: CertKeyAlgorithm.RSA_2048,
+ notAfter: getDateTenYearsFromToday(),
+ maxPathLength: "-1",
+ disableManagedCrlDistributionPointUrl: false,
+ crlDistributionPointUrls: []
+};
+
+const STEP_FIELDS: (keyof CaWizardForm)[][] = [
+ ["name", "type"],
+ ["commonName", "organization", "ou", "country", "province", "locality"],
+ ["keySource", "hsmConnectorId", "keyAlgorithm", "notAfter", "maxPathLength"],
+ ["crlDistributionPointUrls"]
+];
+
+export const CreateCaWizard = ({ isOpen, onOpenChange }: Props) => {
+ const [step, setStep] = useState(0);
+ const { subscription } = useSubscription();
+ const createCa = useCreateCa();
+
+ const { data: hsmConnectors = [], isPending: isHsmConnectorsLoading } = useListHsmConnectors({
+ enabled: Boolean(subscription?.hsm)
+ });
+
+ const hsmConnectorOptions = useMemo(
+ () => hsmConnectors.map((c) => ({ id: c.id, name: c.name, slotLabel: c.slotLabel })),
+ [hsmConnectors]
+ );
+
+ const form = useForm<CaWizardForm>({
+ resolver: zodResolver(caWizardSchema),
+ defaultValues: DEFAULT_VALUES
+ });
+
+ const reset = () => {
+ setStep(0);
+ form.reset(DEFAULT_VALUES);
+ };
+
+ const handleClose = (open: boolean) => {
+ if (!open) reset();
+ onOpenChange(open);
+ };
+
+ const onCreate = async () => {
+ const values = form.getValues();
+ const isRoot = values.type === InternalCaType.ROOT;
+ try {
+ await createCa.mutateAsync({
+ name: values.name,
+ type: CaType.INTERNAL,
+ status: CaStatus.ACTIVE,
+ configuration: {
+ type: values.type,
+ commonName: values.commonName,
+ organization: values.organization,
+ ou: values.ou,
+ country: values.country,
+ province: values.province,
+ locality: values.locality,
+ keyAlgorithm: values.keyAlgorithm,
+ keySource: values.keySource,
+ hsmConnectorId:
+ values.keySource === CertKeySource.Hsm
+ ? (values.hsmConnectorId ?? undefined)
+ : undefined,
+ maxPathLength: Number(values.maxPathLength),
+ ...(isRoot ? { notAfter: values.notAfter } : {}),
+ crlDistributionPointUrls: values.crlDistributionPointUrls.map(({ value }) => value),
+ disableManagedCrlDistributionPointUrl: values.disableManagedCrlDistributionPointUrl
+ }
+ });
+
+ createNotification({ text: "Successfully created CA", type: "success" });
+ handleClose(false);
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: err instanceof Error ? err.message : "Failed to create CA"
+ });
+ }
+ };
+
+ const isLast = step === STEPS.length - 1;
+
+ const goNext = async () => {
+ const ok = await form.trigger(STEP_FIELDS[step]);
+ if (!ok) return;
+ if (isLast) {
+ await onCreate();
+ return;
+ }
+ setStep((s) => s + 1);
+ };
+
+ const goBack = () => {
+ if (step > 0) setStep((s) => s - 1);
+ };
+
+ const currentStep = STEPS[step];
+ const ctaLabel = isLast ? "Create CA" : "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">
+ <ShieldIcon className="h-5 w-5" />
+ </div>
+ <div>
+ <div className="flex items-center gap-x-2 text-mineshaft-300">
+ Create Internal CA
+ <DocumentationLinkBadge href={PkiDocsUrls.ca.internal} />
+ </div>
+ <p className="text-sm leading-4 text-mineshaft-400">
+ A private Certificate Authority hosted by Infisical, with its signing key managed
+ by Infisical or kept in your HSM.
+ </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={form} />}
+ {step === 1 && <SubjectStep form={form} />}
+ {step === 2 && (
+ <KeyValidityStep
+ form={form}
+ hsmConnectorOptions={hsmConnectorOptions}
+ isHsmConnectorsLoading={isHsmConnectorsLoading}
+ />
+ )}
+ {step === 3 && <DistributionStep form={form} />}
+ </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">
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-[11px] font-medium tracking-wider text-muted uppercase">
+ Step {step + 1} · {currentStep.rightLabel}
+ </p>
+ <DocumentationLinkBadge href={currentStep.docsUrl} />
+ </div>
+ <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>
+ </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" />
+ <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={createCa.isPending}>
+ {ctaLabel}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </SheetContent>
+ </Sheet>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/DistributionStep.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/DistributionStep.tsx
new file mode 100644
index 0000000000..022f8d9b67
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/DistributionStep.tsx
@@ -0,0 +1,95 @@
+import { Controller, useFieldArray, useForm } from "react-hook-form";
+import { PlusIcon, Trash2Icon } from "lucide-react";
+
+import {
+ Button,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ IconButton,
+ Input,
+ Switch
+} from "@app/components/v3";
+import { MAX_INTERNAL_CA_DISTRIBUTION_POINT_URLS } from "@app/hooks/api/ca";
+
+import { CaWizardForm } from "./schemas";
+
+type Props = {
+ form: ReturnType<typeof useForm<CaWizardForm>>;
+};
+
+export const DistributionStep = ({ form }: Props) => {
+ const crlUrls = useFieldArray({ control: form.control, name: "crlDistributionPointUrls" });
+
+ return (
+ <FieldGroup>
+ <Controller
+ name="disableManagedCrlDistributionPointUrl"
+ control={form.control}
+ render={({ field: { value, onChange } }) => (
+ <Field orientation="horizontal">
+ <FieldContent>
+ <FieldLabel>Disable managed CRL URL</FieldLabel>
+ <FieldDescription>
+ When enabled, the Infisical-managed CRL endpoint is not embedded in issued
+ certificates. Only the custom URLs below are included.
+ </FieldDescription>
+ </FieldContent>
+ <Switch variant="project" checked={value} onCheckedChange={onChange} />
+ </Field>
+ )}
+ />
+
+ <Field>
+ <FieldLabel>CRL Distribution Points</FieldLabel>
+ <FieldContent>
+ <div className="flex flex-col gap-2">
+ {crlUrls.fields.map((entry, index) => (
+ <Controller
+ key={entry.id}
+ control={form.control}
+ name={`crlDistributionPointUrls.${index}.value`}
+ render={({ field, fieldState: { error } }) => (
+ <div className="flex items-start gap-2">
+ <div className="flex-1">
+ <Input
+ {...field}
+ placeholder="https://crl.example.com/internal-ca.crl"
+ isError={Boolean(error)}
+ />
+ <FieldError errors={[error]} />
+ </div>
+ <IconButton
+ aria-label="Remove URL"
+ variant="outline"
+ onClick={() => crlUrls.remove(index)}
+ >
+ <Trash2Icon className="h-4 w-4" />
+ </IconButton>
+ </div>
+ )}
+ />
+ ))}
+ <Button
+ variant="outline"
+ size="sm"
+ className="self-start"
+ isDisabled={crlUrls.fields.length >= MAX_INTERNAL_CA_DISTRIBUTION_POINT_URLS}
+ onClick={() => crlUrls.append({ value: "" })}
+ >
+ <PlusIcon className="h-4 w-4" />
+ Add URL
+ </Button>
+ </div>
+ <FieldDescription>
+ Backup CRL URLs embedded in issued certificates. Up to{" "}
+ {MAX_INTERNAL_CA_DISTRIBUTION_POINT_URLS}.
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+ </FieldGroup>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx
new file mode 100644
index 0000000000..f3c383d1ce
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx
@@ -0,0 +1,232 @@
+import { Controller, useForm } from "react-hook-form";
+
+import {
+ Badge,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ FilterableSelect,
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3";
+import { useProjectPermission, useSubscription } from "@app/context";
+import {
+ ProjectPermissionHsmConnectorActions,
+ ProjectPermissionSub
+} from "@app/context/ProjectPermissionContext/types";
+import { InternalCaType } from "@app/hooks/api/ca/enums";
+import { certKeyAlgorithms, isPqcAlgorithm } from "@app/hooks/api/certificates/constants";
+import { CertKeyAlgorithm } from "@app/hooks/api/certificates/enums";
+import { CertKeySource } from "@app/hooks/api/signers";
+
+import { CaWizardForm } from "./schemas";
+import { HSM_SUPPORTED_CA_KEY_ALGORITHMS, HsmConnectorOption } from "./types";
+
+type Props = {
+ form: ReturnType<typeof useForm<CaWizardForm>>;
+ hsmConnectorOptions: HsmConnectorOption[];
+ isHsmConnectorsLoading: boolean;
+};
+
+export const KeyValidityStep = ({ form, hsmConnectorOptions, isHsmConnectorsLoading }: Props) => {
+ const { subscription } = useSubscription();
+ const isHsmLicensed = Boolean(subscription?.hsm);
+ const { permission } = useProjectPermission();
+ const canAttachHsm = permission.can(
+ ProjectPermissionHsmConnectorActions.Attach,
+ ProjectPermissionSub.HsmConnectors
+ );
+
+ const keySource = form.watch("keySource");
+ const caType = form.watch("type");
+ const isHsm = keySource === CertKeySource.Hsm;
+ const isRoot = caType === InternalCaType.ROOT;
+
+ return (
+ <FieldGroup>
+ <Controller
+ name="keySource"
+ control={form.control}
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>
+ Key source <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Select
+ value={field.value}
+ onValueChange={(value) => {
+ field.onChange(value);
+ if (
+ value === CertKeySource.Hsm &&
+ !HSM_SUPPORTED_CA_KEY_ALGORITHMS.includes(form.getValues("keyAlgorithm"))
+ ) {
+ form.setValue("keyAlgorithm", CertKeyAlgorithm.RSA_2048, {
+ shouldValidate: true
+ });
+ }
+ }}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value={CertKeySource.Infisical}>Infisical</SelectItem>
+ <SelectItem value={CertKeySource.Hsm} disabled={!isHsmLicensed || !canAttachHsm}>
+ <div className="flex items-center gap-2">
+ HSM
+ {!isHsmLicensed && <Badge variant="info">Enterprise</Badge>}
+ {isHsmLicensed && !canAttachHsm && (
+ <Badge variant="warning">Permission required</Badge>
+ )}
+ </div>
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ {isHsm
+ ? "The CA keypair is generated on a Hardware Security Module and every signature is performed there."
+ : "Infisical generates and manages the CA keypair for you."}
+ </FieldDescription>
+ </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} (${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 CA signing key.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ )}
+
+ <Controller
+ name="keyAlgorithm"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => {
+ const options = certKeyAlgorithms.filter(
+ ({ value }) => !isHsm || HSM_SUPPORTED_CA_KEY_ALGORITHMS.includes(value)
+ );
+ return (
+ <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">
+ {options.map(({ label, value }) => {
+ const pqcLocked = isPqcAlgorithm(value) && !subscription?.pkiPqc;
+ return (
+ <SelectItem key={value} value={value} disabled={pqcLocked}>
+ <div className="flex items-center gap-2">
+ {label}
+ {pqcLocked && <Badge variant="info">Enterprise</Badge>}
+ </div>
+ </SelectItem>
+ );
+ })}
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ Algorithm and size of the CA key pair. HSM-backed CAs support RSA and ECDSA only.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ );
+ }}
+ />
+
+ {isRoot && (
+ <>
+ <Controller
+ name="notAfter"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Valid Until <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input {...field} placeholder="YYYY-MM-DD" isError={Boolean(error)} />
+ <FieldDescription>
+ When the self-signed Root CA certificate expires.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ name="maxPathLength"
+ control={form.control}
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Path Length</FieldLabel>
+ <FieldContent>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {[-1, 0, 1, 2, 3, 4].map((value) => (
+ <SelectItem key={value} value={String(value)}>
+ {String(value)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ How many intermediate CAs may follow this CA in the chain. -1 means no limit.
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ </>
+ )}
+ </FieldGroup>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/SubjectStep.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/SubjectStep.tsx
new file mode 100644
index 0000000000..bddc52f334
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/SubjectStep.tsx
@@ -0,0 +1,46 @@
+import { Controller, useForm } from "react-hook-form";
+
+import { Field, FieldContent, FieldError, FieldGroup, FieldLabel, Input } from "@app/components/v3";
+
+import { CaWizardForm } from "./schemas";
+
+type Props = {
+ form: ReturnType<typeof useForm<CaWizardForm>>;
+};
+
+const SUBJECT_FIELDS: { name: keyof CaWizardForm; label: string; placeholder: string }[] = [
+ { name: "commonName", label: "Common Name (CN)", placeholder: "Example CA" },
+ { name: "organization", label: "Organization (O)", placeholder: "Acme Corp" },
+ { name: "ou", label: "Organization Unit (OU)", placeholder: "Engineering" },
+ { name: "country", label: "Country (C)", placeholder: "US" },
+ { name: "province", label: "State or Province (ST)", placeholder: "California" },
+ { name: "locality", label: "Locality (L)", placeholder: "San Francisco" }
+];
+
+export const SubjectStep = ({ form }: Props) => {
+ return (
+ <FieldGroup>
+ {SUBJECT_FIELDS.map((subjectField) => (
+ <Controller
+ key={subjectField.name}
+ name={subjectField.name}
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>{subjectField.label}</FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ value={(field.value as string) ?? ""}
+ placeholder={subjectField.placeholder}
+ isError={Boolean(error)}
+ />
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ ))}
+ </FieldGroup>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/schemas.ts b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/schemas.ts
new file mode 100644
index 0000000000..52a963067d
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/schemas.ts
@@ -0,0 +1,98 @@
+import { z } from "zod";
+
+import {
+ MAX_DISTRIBUTION_POINT_URL_LENGTH,
+ MAX_INTERNAL_CA_DISTRIBUTION_POINT_URLS
+} from "@app/hooks/api/ca";
+import { InternalCaType } from "@app/hooks/api/ca/enums";
+import { CertKeyAlgorithm } from "@app/hooks/api/certificates/enums";
+import { CertKeySource } from "@app/hooks/api/signers";
+import { slugSchema } from "@app/lib/schemas";
+
+import { HSM_SUPPORTED_CA_KEY_ALGORITHMS } from "./types";
+
+const isValidDate = (dateString: string) => !Number.isNaN(new Date(dateString).getTime());
+
+const distributionPointUrlEntrySchema = z.object({
+ value: z
+ .string()
+ .trim()
+ .max(MAX_DISTRIBUTION_POINT_URL_LENGTH, "URL is too long")
+ .url("Must be a valid URL")
+ .refine((url) => /^https?:\/\//i.test(url), { message: "URL must use http:// or https://" })
+});
+
+const distributionPointUrlsSchema = z
+ .array(distributionPointUrlEntrySchema)
+ .max(
+ MAX_INTERNAL_CA_DISTRIBUTION_POINT_URLS,
+ `Up to ${MAX_INTERNAL_CA_DISTRIBUTION_POINT_URLS} URLs are allowed`
+ )
+ .superRefine((entries, ctx) => {
+ const seen = new Set<string>();
+ entries.forEach((entry, index) => {
+ const normalized = entry.value.trim().replace(/\/+$/, "").toLowerCase();
+ if (seen.has(normalized)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: [index, "value"],
+ message: "Duplicate URL"
+ });
+ }
+ seen.add(normalized);
+ });
+ });
+
+export const caWizardSchema = z
+ .object({
+ name: slugSchema({ min: 1, max: 64, field: "Name" }),
+ type: z.nativeEnum(InternalCaType).default(InternalCaType.ROOT),
+ organization: z.string().trim().default(""),
+ ou: z.string().trim().default(""),
+ country: z.string().trim().default(""),
+ province: z.string().trim().default(""),
+ locality: z.string().trim().default(""),
+ commonName: z.string().trim().default(""),
+ keySource: z.nativeEnum(CertKeySource).default(CertKeySource.Infisical),
+ hsmConnectorId: z.string().uuid().optional().nullable(),
+ keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).default(CertKeyAlgorithm.RSA_2048),
+ notAfter: z.string().trim().default(""),
+ maxPathLength: z.string().default("-1"),
+ disableManagedCrlDistributionPointUrl: z.boolean().default(false),
+ crlDistributionPointUrls: distributionPointUrlsSchema.default([])
+ })
+ .refine(
+ (data) =>
+ [
+ data.commonName,
+ data.organization,
+ data.ou,
+ data.country,
+ data.province,
+ data.locality
+ ].some((field) => field !== ""),
+ {
+ message: "At least one subject field (Common Name, Organization, ...) must be set.",
+ path: ["commonName"]
+ }
+ )
+ .refine((data) => data.type !== InternalCaType.ROOT || isValidDate(data.notAfter), {
+ message: "A valid expiry date is required for a Root CA.",
+ path: ["notAfter"]
+ })
+ .refine((data) => data.keySource !== CertKeySource.Hsm || Boolean(data.hsmConnectorId), {
+ message: "Pick an HSM Connector.",
+ path: ["hsmConnectorId"]
+ })
+ .refine(
+ (data) =>
+ data.keySource !== CertKeySource.Hsm ||
+ HSM_SUPPORTED_CA_KEY_ALGORITHMS.includes(data.keyAlgorithm),
+ {
+ message:
+ "This algorithm is not supported by HSM-backed keys. Pick RSA 2048, RSA 4096, ECDSA P256, or ECDSA P384.",
+ path: ["keyAlgorithm"]
+ }
+ );
+
+export type CaWizardForm = z.infer<typeof caWizardSchema>;
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/types.ts b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/types.ts
new file mode 100644
index 0000000000..c0a0e72daa
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/types.ts
@@ -0,0 +1,65 @@
+import { CertKeyAlgorithm } from "@app/hooks/api/certificates/enums";
+
+import { PkiDocsUrls } from "../../../pki-docs-urls";
+
+export const HSM_SUPPORTED_CA_KEY_ALGORITHMS: readonly CertKeyAlgorithm[] = [
+ CertKeyAlgorithm.RSA_2048,
+ CertKeyAlgorithm.RSA_4096,
+ CertKeyAlgorithm.ECDSA_P256,
+ CertKeyAlgorithm.ECDSA_P384
+];
+
+export type HsmConnectorOption = { id: string; name: string; slotLabel: string };
+
+export type WizardStep = {
+ name: string;
+ shortDescription: string;
+ title: string;
+ subtitle: string;
+ rightLabel: string;
+ rightDescription: string;
+ docsUrl: string;
+};
+
+export const STEPS: WizardStep[] = [
+ {
+ name: "Basics",
+ shortDescription: "Name and type",
+ title: "Basics",
+ subtitle: "Name the certificate authority and choose whether it is a root or intermediate.",
+ rightLabel: "BASICS",
+ rightDescription:
+ "The name identifies the CA inside Infisical. A Root CA is self-signed and active immediately. An Intermediate CA is created pending a certificate, then signed by a parent CA after you generate its CSR.",
+ docsUrl: PkiDocsUrls.ca.internal
+ },
+ {
+ name: "Subject",
+ shortDescription: "Distinguished name",
+ title: "Subject",
+ subtitle: "The distinguished name (DN) embedded in the CA certificate.",
+ rightLabel: "SUBJECT",
+ rightDescription:
+ "The Common Name, Organization, and related fields make up the Distinguished Name that identifies this CA on every certificate it issues. At least one field is required.",
+ docsUrl: PkiDocsUrls.ca.internal
+ },
+ {
+ name: "Key & Validity",
+ shortDescription: "Source, algorithm, validity",
+ title: "Key & Validity",
+ subtitle: "Choose where the signing key is generated and how long the CA is valid.",
+ rightLabel: "KEY & VALIDITY",
+ rightDescription:
+ "Pick the key source: Infisical generates and manages the keypair, or HSM keeps the keypair inside your own Hardware Security Module and performs every signature there. Root CAs are self-signed immediately, so their validity and path length are set here.",
+ docsUrl: PkiDocsUrls.ca.internal
+ },
+ {
+ name: "Distribution",
+ shortDescription: "Revocation endpoints",
+ title: "Distribution",
+ subtitle: "Configure the CRL distribution points embedded in issued certificates.",
+ rightLabel: "DISTRIBUTION",
+ rightDescription:
+ "Certificates issued by this CA carry CRL Distribution Point URLs so clients can check revocation. The Infisical-managed CRL endpoint is included by default; add backup URLs or disable the managed one as needed.",
+ docsUrl: PkiDocsUrls.ca.internal
+ }
+];
diff --git a/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/HsmConnectorLinkedCertsSection.tsx b/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/HsmConnectorLinkedCertsSection.tsx
index 6cfecb7f90..2008a5bb67 100644
--- a/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/HsmConnectorLinkedCertsSection.tsx
+++ b/frontend/src/pages/cert-manager/HsmConnectorDetailsByIDPage/components/HsmConnectorLinkedCertsSection.tsx
@@ -26,6 +26,7 @@ import {
TooltipTrigger
} from "@app/components/v3";
import { useOrganization, useProject } from "@app/context";
+import { CaStatus } from "@app/hooks/api/ca/enums";
import { CertStatus } from "@app/hooks/api/certificates/enums";
import { useListHsmConnectorLinkedResources } from "@app/hooks/api/hsmConnectors";
@@ -39,6 +40,7 @@ export const HsmConnectorLinkedCertsSection = ({ connectorId }: Props) => {
limit: perPage
});
const linked = data?.certificates ?? [];
+ const linkedCas = data?.certificateAuthorities ?? [];
const totalCount = data?.totalCount ?? 0;
const navigate = useNavigate();
const { currentProject } = useProject();
@@ -61,26 +63,71 @@ export const HsmConnectorLinkedCertsSection = ({ connectorId }: Props) => {
return (
<Card className="w-full">
<CardHeader className="border-b">
- <CardTitle>Linked certificates</CardTitle>
+ <CardTitle>Linked resources</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.
+ Certificates and certificate authorities that use this HSM Connector as their key source.
+ Delete is blocked while any of these exist. Re-issue or retire the certificates, and
+ delete or migrate the certificate authorities first.
</CardDescription>
</CardHeader>
<CardContent>
{isPending && <Skeleton className="h-24" />}
- {!isPending && linked.length === 0 && (
+ {!isPending && linked.length === 0 && linkedCas.length === 0 && (
<Empty className="border border-solid">
<EmptyHeader>
- <EmptyTitle>No certificates linked</EmptyTitle>
+ <EmptyTitle>No linked resources</EmptyTitle>
<EmptyDescription>
- No certificate currently uses this connector. It is safe to delete.
+ No certificate or certificate authority currently uses this connector. It is safe to
+ delete.
</EmptyDescription>
</EmptyHeader>
</Empty>
)}
+ {!isPending && linkedCas.length > 0 && (
+ <div className="mb-6">
+ <p className="mb-2 text-sm font-medium text-mineshaft-200">Certificate authorities</p>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Name</TableHead>
+ <TableHead>Type</TableHead>
+ <TableHead>Status</TableHead>
+ <TableHead>HSM key label</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {linkedCas.map((ca) => (
+ <TableRow key={ca.id}>
+ <TableCell className="font-medium">{ca.name}</TableCell>
+ <TableCell className="capitalize">{ca.type}</TableCell>
+ <TableCell>
+ <Badge variant={ca.status === CaStatus.ACTIVE ? "success" : "outline"}>
+ {ca.status}
+ </Badge>
+ </TableCell>
+ <TableCell className="max-w-[14rem] font-mono text-xs">
+ {ca.hsmKeyLabel ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="block truncate">{ca.hsmKeyLabel}</span>
+ </TooltipTrigger>
+ <TooltipContent>{ca.hsmKeyLabel}</TooltipContent>
+ </Tooltip>
+ ) : (
+ "-"
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ )}
{!isPending && linked.length > 0 && (
<>
+ {linkedCas.length > 0 && (
+ <p className="mb-2 text-sm font-medium text-mineshaft-200">Certificates</p>
+ )}
<Table>
<TableHeader>
<TableRow>