Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(code-signing): use an existing DigiCert certificate and its HSM key in a signer
Carlos Monastyrski85dd1450e93c
diff --git a/backend/src/db/migrations/20261016142318_hsm-key-id.ts b/backend/src/db/migrations/20261016142318_hsm-key-id.tsnew file mode 100644index 0000000000..4d2b2d86c5--- /dev/null+++ b/backend/src/db/migrations/20261016142318_hsm-key-id.ts@@ -0,0 +1,43 @@+import { Knex } from "knex";++import { TableName } from "@app/db/schemas";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasColumn(TableName.Certificate, "hsmKeyId"))) {+ await knex.schema.alterTable(TableName.Certificate, (t) => {+ t.string("hsmKeyId", 256).nullable();+ });+ }++ if (!(await knex.schema.hasColumn(TableName.CertificateAuthoritySecret, "hsmKeyId"))) {+ await knex.schema.alterTable(TableName.CertificateAuthoritySecret, (t) => {+ t.string("hsmKeyId", 256).nullable();+ });+ }++ if (!(await knex.schema.hasColumn(TableName.PkiSignerCertificateIssuanceJobs, "hsmKeyId"))) {+ await knex.schema.alterTable(TableName.PkiSignerCertificateIssuanceJobs, (t) => {+ t.string("hsmKeyId", 256).nullable();+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ if (await knex.schema.hasColumn(TableName.Certificate, "hsmKeyId")) {+ await knex.schema.alterTable(TableName.Certificate, (t) => {+ t.dropColumn("hsmKeyId");+ });+ }++ if (await knex.schema.hasColumn(TableName.CertificateAuthoritySecret, "hsmKeyId")) {+ await knex.schema.alterTable(TableName.CertificateAuthoritySecret, (t) => {+ t.dropColumn("hsmKeyId");+ });+ }++ if (await knex.schema.hasColumn(TableName.PkiSignerCertificateIssuanceJobs, "hsmKeyId")) {+ await knex.schema.alterTable(TableName.PkiSignerCertificateIssuanceJobs, (t) => {+ t.dropColumn("hsmKeyId");+ });+ }+}diff --git a/backend/src/db/schemas/certificate-authority-secret.ts b/backend/src/db/schemas/certificate-authority-secret.tsindex 5d0d50d5d3..5d589b44c7 100644--- a/backend/src/db/schemas/certificate-authority-secret.ts+++ b/backend/src/db/schemas/certificate-authority-secret.ts@@ -18,6 +18,7 @@ export const CertificateAuthoritySecretSchema = z.object({keySource: z.string().default("infisical"),hsmConnectorId: z.string().uuid().nullable().optional(),hsmKeyLabel: z.string().nullable().optional(),+ hsmKeyId: z.string().nullable().optional(),hsmPublicKeySpki: zodBuffer.nullable().optional()});diff --git a/backend/src/db/schemas/certificates.ts b/backend/src/db/schemas/certificates.tsindex 68fe46719d..76420fe57f 100644--- a/backend/src/db/schemas/certificates.ts+++ b/backend/src/db/schemas/certificates.ts@@ -52,6 +52,7 @@ export const CertificatesSchema = z.object({keySource: z.string().default("infisical"),hsmConnectorId: z.string().uuid().nullable().optional(),hsmKeyLabel: z.string().nullable().optional(),+ hsmKeyId: z.string().nullable().optional(),hsmPublicKeySpki: zodBuffer.nullable().optional(),subjectDomainComponents: z.string().nullable().optional(),orderId: z.string().uuid().default("00000000-0000-0000-0000-000000000000"),diff --git a/backend/src/db/schemas/pki-signer-certificate-issuance-jobs.ts b/backend/src/db/schemas/pki-signer-certificate-issuance-jobs.tsindex 68563dcac5..8df42ad5e4 100644--- a/backend/src/db/schemas/pki-signer-certificate-issuance-jobs.ts+++ b/backend/src/db/schemas/pki-signer-certificate-issuance-jobs.ts@@ -32,6 +32,7 @@ export const PkiSignerCertificateIssuanceJobsSchema = z.object({keySource: z.string().default("infisical"),hsmConnectorId: z.string().uuid().nullable().optional(),hsmKeyLabel: z.string().nullable().optional(),+ hsmKeyId: z.string().nullable().optional(),hsmPublicKeySpki: zodBuffer.nullable().optional()});diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 30faead9fb..90157df0ef 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -5026,6 +5026,8 @@ interface CreatePkiSignerEvent {approvalPolicyId?: string | null;keySource?: CertKeySource;hsmConnectorId?: string | null;+ hsmKeyLabel?: string;+ hsmKeyId?: string;externalConfiguration?: TSignerExternalConfigurationInput;};}@@ -5120,10 +5122,13 @@ interface ReissuePkiSignerCertificateEvent {signerId: string;name: string;caId: string;+ certificateId?: string | null;commonName?: string;keyAlgorithm?: string;keySource?: string;hsmConnectorId?: string;+ hsmKeyLabel?: string;+ hsmKeyId?: string;hsmKeyAlgorithm?: string;externalConfiguration?: TSignerExternalConfigurationInput;};diff --git a/backend/src/lib/csr/build-csr-with-external-signer.test.ts b/backend/src/lib/csr/build-csr-with-external-signer.test.tsnew file mode 100644index 0000000000..ce3b4040d2--- /dev/null+++ b/backend/src/lib/csr/build-csr-with-external-signer.test.ts@@ -0,0 +1,68 @@+import { createPublicKey, verify, webcrypto } from "node:crypto";++import { CertificationRequest } from "@peculiar/asn1-csr";+import { AsnConvert } from "@peculiar/asn1-schema";+import * as x509 from "@peculiar/x509";+import { beforeAll, describe, expect, it } from "vitest";++import { HsmKeyAlgorithm } from "@app/services/signer/signer-enums";++import { buildCsrWithExternalSigner } from "./build-csr-with-external-signer";++type TCase = {+ hsmKeyAlgorithm: HsmKeyAlgorithm;+ gen: RsaHashedKeyGenParams | EcKeyGenParams;+ sign: AlgorithmIdentifier | EcdsaParams;+ hash: string;+};++const CASES: TCase[] = [+ {+ hsmKeyAlgorithm: HsmKeyAlgorithm.RSA_3072,+ gen: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256", publicExponent: new Uint8Array([1, 0, 1]), modulusLength: 3072 },+ sign: { name: "RSASSA-PKCS1-v1_5" },+ hash: "sha256"+ },+ {+ hsmKeyAlgorithm: HsmKeyAlgorithm.ECC_P256,+ gen: { name: "ECDSA", namedCurve: "P-256" },+ sign: { name: "ECDSA", hash: "SHA-256" },+ hash: "sha256"+ },+ {+ hsmKeyAlgorithm: HsmKeyAlgorithm.ECC_P384,+ gen: { name: "ECDSA", namedCurve: "P-384" },+ sign: { name: "ECDSA", hash: "SHA-384" },+ hash: "sha384"+ }+];++beforeAll(() => {+ x509.cryptoProvider.set(webcrypto as unknown as Crypto);+});++describe.each(CASES)("buildCsrWithExternalSigner: $hsmKeyAlgorithm", (testCase) => {+ it("should produce CSRs whose DER signature verifies with OpenSSL for every signature value", async () => {+ const keys = (await webcrypto.subtle.generateKey(testCase.gen, true, ["sign", "verify"])) as CryptoKeyPair;+ const publicKeySpkiDer = Buffer.from(await webcrypto.subtle.exportKey("spki", keys.publicKey));+ const iterations = testCase.hsmKeyAlgorithm === HsmKeyAlgorithm.RSA_3072 ? 3 : 40;++ for (let i = 0; i < iterations; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ const { csrDer } = await buildCsrWithExternalSigner({+ publicKeySpkiDer,+ keyAlgorithm: testCase.hsmKeyAlgorithm,+ subjectCommonName: "Example Code Signing",+ signCallback: async (tbs) => Buffer.from(await webcrypto.subtle.sign(testCase.sign, keys.privateKey, tbs))+ });+ const csr = AsnConvert.parse(csrDer, CertificationRequest);+ const isValid = verify(+ testCase.hash,+ Buffer.from(AsnConvert.serialize(csr.certificationRequestInfo)),+ createPublicKey({ key: publicKeySpkiDer, format: "der", type: "spki" }),+ Buffer.from(csr.signature)+ );+ expect(isValid).toBe(true);+ }+ });+});diff --git a/backend/src/lib/csr/build-csr-with-external-signer.ts b/backend/src/lib/csr/build-csr-with-external-signer.tsindex 5c808e768a..e18c6c91fc 100644--- a/backend/src/lib/csr/build-csr-with-external-signer.ts+++ b/backend/src/lib/csr/build-csr-with-external-signer.ts@@ -1,5 +1,5 @@import { Attributes, CertificationRequest, CertificationRequestInfo } from "@peculiar/asn1-csr";-import { ECDSASigValue, id_ecdsaWithSHA256, id_ecdsaWithSHA384 } from "@peculiar/asn1-ecc";+import { id_ecdsaWithSHA256, id_ecdsaWithSHA384 } from "@peculiar/asn1-ecc";import { id_sha256WithRSAEncryption, id_sha384WithRSAEncryption } from "@peculiar/asn1-rsa";import { AsnConvert, OctetString } from "@peculiar/asn1-schema";import {@@ -23,6 +23,7 @@ import {} from "@peculiar/asn1-x509";import * as x509 from "@peculiar/x509";+import { ecdsaRawRsToDer } from "@app/lib/csr/pkcs11-algorithm-map";import { BadRequestError } from "@app/lib/errors";import { HsmKeyAlgorithm } from "@app/services/signer/signer-enums";@@ -52,6 +53,7 @@ const pickAlgorithmShape = (const nullParams = new Uint8Array([0x05, 0x00]).buffer as ArrayBuffer;switch (keyAlgorithm) {case HsmKeyAlgorithm.RSA_2048:+ case HsmKeyAlgorithm.RSA_3072:return {mechanism: "CKM_SHA256_RSA_PKCS",pk11SignsDigest: false,@@ -139,21 +141,6 @@ const buildCodeSigningExtensions = (subjectAltNames?: string[]): Extensions => {return new Extensions(extensions);};-// PKCS#11 emits raw `r || s`; X.509 expects DER ECDSASigValue.-const rawRsToDer = (raw: Buffer): Buffer => {- if (raw.length % 2 !== 0) {- throw new BadRequestError({ message: `Unexpected ECDSA signature length: ${raw.length}` });- }- const half = raw.length / 2;- const r = raw.subarray(0, half);- const s = raw.subarray(half);- const sig = new ECDSASigValue({- r: bufferToArrayBuffer(r),- s: bufferToArrayBuffer(s)- });- return Buffer.from(AsnConvert.serialize(sig));-};-export const buildCsrWithExternalSigner = async (input: BuildCsrInput): Promise<BuiltCsr> => {const shape = pickAlgorithmShape(input.keyAlgorithm);@@ -180,7 +167,7 @@ export const buildCsrWithExternalSigner = async (input: BuildCsrInput): Promise<// isDigest=false: HSM hashes via *_SHA<NN>_* so the wire payload stays raw TBS.let signatureBytes = await input.signCallback(tbsDer, shape.mechanism, shape.pk11SignsDigest);if (shape.isEcdsa) {- signatureBytes = rawRsToDer(signatureBytes);+ signatureBytes = ecdsaRawRsToDer(signatureBytes);}const sigAlg = new AlgorithmIdentifier({diff --git a/backend/src/lib/gateway-v2/pkcs11-rpc.ts b/backend/src/lib/gateway-v2/pkcs11-rpc.tsindex c60ad5f22e..0135b9f8fc 100644--- a/backend/src/lib/gateway-v2/pkcs11-rpc.ts+++ b/backend/src/lib/gateway-v2/pkcs11-rpc.ts@@ -1,6 +1,30 @@import { postGatewayRpc } from "./gateway-rpc";-export type Pkcs11RpcEndpoint = "/v1/test" | "/v1/generate-key-pair" | "/v1/sign" | "/v1/get-public-key";+export type Pkcs11RpcEndpoint =+ | "/v1/test"+ | "/v1/generate-key-pair"+ | "/v1/sign"+ | "/v1/get-public-key"+ | "/v1/find-keys";++export enum Pkcs11ErrorCode {+ KeyNotFound = "key_not_found",+ KeyAmbiguous = "key_ambiguous",+ KeyTypeMismatch = "key_type_mismatch",+ SignatureMismatch = "signature_mismatch",+ MechanismInvalid = "mechanism_invalid",+ BadRequest = "bad_request",+ Internal = "internal",+ DriverUnavailable = "driver_unavailable",+ GatewayTimeout = "gateway_timeout",+ NotSupported = "pkcs11_not_supported",+ UnsupportedGatewayVersion = "unsupported_gateway_version",+ GatewayUnreachable = "gateway_unreachable",+ GatewayNotFound = "gateway_not_found"+}++export const isPkcs11Error = (err: unknown, code: Pkcs11ErrorCode) =>+ err instanceof Error && err.message.includes(`(${code})`);export type Pkcs11RpcRequestBody = {slotLabel: string;@@ -33,11 +57,19 @@ export const callPkcs11Endpoint = async <T>(args: {label: "PKCS#11"});+ if (status === 404) {+ return {+ ok: false,+ status,+ errorCode: Pkcs11ErrorCode.UnsupportedGatewayVersion,+ errorMessage: "This gateway version does not support this operation. Update the gateway to the latest version."+ };+ }if (!text) {return {ok: false,status,- errorCode: "internal",+ errorCode: Pkcs11ErrorCode.Internal,errorMessage: `Empty response body from Gateway (status ${status})`};}@@ -48,14 +80,19 @@ export const callPkcs11Endpoint = async <T>(args: {return {ok: false,status,- errorCode: "internal",+ errorCode: Pkcs11ErrorCode.Internal,errorMessage: `Malformed response body from Gateway: ${text.slice(0, 256)}`};}if (status >= 200 && status < 300) {const { result } = parsed as { result?: T };if (result === undefined) {- return { ok: false, status, errorCode: "internal", errorMessage: "Gateway response missing `result` field" };+ return {+ ok: false,+ status,+ errorCode: Pkcs11ErrorCode.Internal,+ errorMessage: "Gateway response missing `result` field"+ };}return { ok: true, status, result };}@@ -71,9 +108,10 @@ export const callPkcs11Endpoint = async <T>(args: {export const isRetryablePkcs11RpcError = (failure: Pkcs11RpcFailure): boolean => {if (failure.status === 502 || failure.status === 503 || failure.status === 504) return true;switch (failure.errorCode) {- case "driver_unavailable":- case "gateway_timeout":- case "pkcs11_not_supported":+ case Pkcs11ErrorCode.DriverUnavailable:+ case Pkcs11ErrorCode.GatewayTimeout:+ case Pkcs11ErrorCode.NotSupported:+ case Pkcs11ErrorCode.UnsupportedGatewayVersion:return true;default:return false;diff --git a/backend/src/server/routes/v1/hsm-connector-router-schemas.ts b/backend/src/server/routes/v1/hsm-connector-router-schemas.tsindex 6e618ef6e9..6c435301ce 100644--- a/backend/src/server/routes/v1/hsm-connector-router-schemas.ts+++ b/backend/src/server/routes/v1/hsm-connector-router-schemas.ts@@ -103,3 +103,20 @@ export const HsmConnectorLinkedResourcesResponseSchema = z.object({),totalCount: z.number()});++export const HsmConnectorKeysQuerySchema = z.object({+ label: z.string().trim().min(1).max(128).describe("The exact label (CKA_LABEL) of the private keys to look up.")+});++export const HsmConnectorKeysResponseSchema = z.object({+ keys: z+ .array(+ z.object({+ keyId: z.string().describe("The hex-encoded PKCS#11 key ID (CKA_ID). Empty when the key has none."),+ keyAlgorithm: z+ .string()+ .describe("The key's algorithm, such as RSA_3072 or ECC_P256. Empty when it can't be determined.")+ })+ )+ .describe("The private keys in the HSM Connector's slot that have the label, sorted by key ID.")+});diff --git a/backend/src/server/routes/v1/hsm-connector-router.ts b/backend/src/server/routes/v1/hsm-connector-router.tsindex 249149c218..3fa7b1747b 100644--- a/backend/src/server/routes/v1/hsm-connector-router.ts+++ b/backend/src/server/routes/v1/hsm-connector-router.ts@@ -11,6 +11,8 @@ import { HsmConnectorSanitizedSchema } from "@app/services/hsm-connector/hsm-conimport {CreateHsmConnectorBodySchema,HsmConnectorIdParamSchema,+ HsmConnectorKeysQuerySchema,+ HsmConnectorKeysResponseSchema,HsmConnectorLinkedResourcesQuerySchema,HsmConnectorLinkedResourcesResponseSchema,HsmConnectorTestResultSchema,@@ -235,6 +237,28 @@ export const createHsmConnectorRouter =);}});++ server.route({+ method: "GET",+ url: "/:connectorId/keys",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listHsmConnectorKeys",+ tags: [ApiDocsTags.HsmConnectors],+ params: HsmConnectorIdParamSchema,+ querystring: HsmConnectorKeysQuerySchema,+ response: { 200: HsmConnectorKeysResponseSchema }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const { keys } = await server.services.hsmConnector.listHsmConnectorKeys(+ { connectorId: req.params.connectorId, keyLabel: req.query.label },+ req.permission+ );+ return { keys };+ }+ });};export const registerCertManagerHsmConnectorRouter = createHsmConnectorRouter({diff --git a/backend/src/server/routes/v1/signer-routers/certificate-router.ts b/backend/src/server/routes/v1/signer-routers/certificate-router.tsindex d33437d798..796343d445 100644--- a/backend/src/server/routes/v1/signer-routers/certificate-router.ts+++ b/backend/src/server/routes/v1/signer-routers/certificate-router.ts@@ -9,7 +9,8 @@ import { AuthMode } from "@app/services/auth/auth-type";import { CertKeySource } from "@app/services/signer/signer-enums";import {- HSM_SUPPORTED_KEY_ALGORITHMS,+ refineSignerCertificateInput,+ SignerCertificateInputSchema,SignerExternalConfigurationSchema,SignerIdParamsSchema,SignerKeyAlgorithm@@ -32,31 +33,10 @@ export const registerSignerCertificateRouter = async (server: FastifyZodProvidercommonName: z.string().trim().min(1).max(256).optional(),certificateTtlDays: z.number().int().min(1).max(3650).optional(),keyAlgorithm: SignerKeyAlgorithm.schema.optional(),- certificate: z- .object({- keySource: z.nativeEnum(CertKeySource),- hsmConnectorId: z.string().uuid().optional()- })- .optional(),+ certificate: SignerCertificateInputSchema.extend({ keySource: z.nativeEnum(CertKeySource) }).optional(),externalConfiguration: SignerExternalConfigurationSchema.optional()})- .superRefine((data, ctx) => {- if (data.certificate?.keySource !== CertKeySource.Hsm) return;- if (!data.certificate.hsmConnectorId) {- ctx.addIssue({- code: "custom",- message: `hsmConnectorId is required when keySource = '${CertKeySource.Hsm}'`,- path: ["certificate", "hsmConnectorId"]- });- }- if (!data.keyAlgorithm || !HSM_SUPPORTED_KEY_ALGORITHMS.includes(data.keyAlgorithm)) {- ctx.addIssue({- code: "custom",- message: `keyAlgorithm must be one of ${HSM_SUPPORTED_KEY_ALGORITHMS.join(", ")} when keySource = '${CertKeySource.Hsm}'`,- path: ["keyAlgorithm"]- });- }- }),+ .superRefine(refineSignerCertificateInput),response: { 200: PkiSignersSchema }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),@@ -70,6 +50,7 @@ export const registerSignerCertificateRouter = async (server: FastifyZodProvideractorOrgId: req.permission.orgId});+ const isImport = Boolean(req.body.externalConfiguration?.importFromExternalOrderId);await server.services.auditLog.createAuditLog({...req.auditLogInfo,projectId: signer.projectId,@@ -79,10 +60,13 @@ export const registerSignerCertificateRouter = async (server: FastifyZodProvidersignerId: signer.id,name: signer.name,caId: req.body.caId,- commonName: req.body.commonName,- keyAlgorithm: req.body.keyAlgorithm,+ commonName: isImport ? (signer.commonName ?? undefined) : req.body.commonName,+ keyAlgorithm: isImport ? (signer.keyAlgorithm ?? undefined) : req.body.keyAlgorithm,+ ...(isImport ? { certificateId: signer.certificateId } : {}),keySource: req.body.certificate?.keySource,hsmConnectorId: req.body.certificate?.hsmConnectorId,+ hsmKeyLabel: req.body.certificate?.hsmKeyLabel,+ hsmKeyId: req.body.certificate?.hsmKeyId,externalConfiguration: req.body.externalConfiguration}}diff --git a/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts b/backend/src/server/routes/v1/signer-routers/lifecycle-router.tsindex cd98c202f6..223ffc746f 100644--- a/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts+++ b/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts@@ -13,7 +13,8 @@ import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";import {ApprovalPolicyBodySchema,- HSM_SUPPORTED_KEY_ALGORITHMS,+ refineSignerCertificateInput,+ SignerCertificateInputSchema,SignerExternalConfigurationSchema,SignerIdParamsSchema,SignerKeyAlgorithm@@ -61,12 +62,9 @@ export const registerSignerLifecycleRouter = async (server: FastifyZodProvider)certificateRenewBeforeDays: z.number().int().min(1).max(30).nullable().optional(),keyAlgorithm: SignerKeyAlgorithm.schema.optional(),certificateId: z.string().uuid().optional(),- certificate: z- .object({- keySource: z.nativeEnum(CertKeySource).optional().default(CertKeySource.Infisical),- hsmConnectorId: z.string().uuid().optional()- })- .optional(),+ certificate: SignerCertificateInputSchema.extend({+ keySource: z.nativeEnum(CertKeySource).optional().default(CertKeySource.Infisical)+ }).optional(),externalConfiguration: SignerExternalConfigurationSchema.optional(),approvalPolicyId: z.string().uuid().optional(),members: z@@ -80,23 +78,7 @@ export const registerSignerLifecycleRouter = async (server: FastifyZodProvider).optional(),approvalPolicy: ApprovalPolicyBodySchema.optional()})- .superRefine((data, ctx) => {- if (data.certificate?.keySource !== CertKeySource.Hsm) return;- if (!data.certificate.hsmConnectorId) {- ctx.addIssue({- code: "custom",- message: `hsmConnectorId is required when keySource = '${CertKeySource.Hsm}'`,- path: ["certificate", "hsmConnectorId"]- });- }- if (!data.keyAlgorithm || !HSM_SUPPORTED_KEY_ALGORITHMS.includes(data.keyAlgorithm)) {- ctx.addIssue({- code: "custom",- message: `keyAlgorithm must be one of ${HSM_SUPPORTED_KEY_ALGORITHMS.join(", ")} when keySource = '${CertKeySource.Hsm}'`,- path: ["keyAlgorithm"]- });- }- }),+ .superRefine(refineSignerCertificateInput),response: {200: PkiSignersSchema}@@ -124,6 +106,8 @@ export const registerSignerLifecycleRouter = async (server: FastifyZodProvider)approvalPolicyId: signer.approvalPolicyId,keySource: req.body.certificate?.keySource,hsmConnectorId: req.body.certificate?.hsmConnectorId,+ hsmKeyLabel: req.body.certificate?.hsmKeyLabel,+ hsmKeyId: req.body.certificate?.hsmKeyId,externalConfiguration: req.body.externalConfiguration}}diff --git a/backend/src/server/routes/v1/signer-routers/schemas.test.ts b/backend/src/server/routes/v1/signer-routers/schemas.test.tsnew file mode 100644index 0000000000..2c1d750cd3--- /dev/null+++ b/backend/src/server/routes/v1/signer-routers/schemas.test.ts@@ -0,0 +1,116 @@+import { describe, expect, test } from "vitest";+import { z } from "zod";++import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";+import { CaType } from "@app/services/certificate-authority/certificate-authority-enums";+import { CertKeySource } from "@app/services/signer/signer-enums";+import { assertExternalConfigurationMatchesCaType } from "@app/services/signer/signer-service";++import {+ refineSignerCertificateInput,+ SignerCertificateInputSchema,+ SignerExternalConfigurationSchema,+ SignerKeyAlgorithm+} from "./schemas";++describe("SignerExternalConfigurationSchema", () => {+ test("keeps fields that belong to another CA type so the service can reject them", () => {+ expect(+ SignerExternalConfigurationSchema.parse({+ caType: CaType.DIGICERT,+ reissueFromExternalOrderId: "1",+ template: "x"+ })+ ).toEqual({ caType: CaType.DIGICERT, reissueFromExternalOrderId: "1", template: "x" });+ });+});++describe("assertExternalConfigurationMatchesCaType", () => {+ test("accepts a matching or omitted caType", () => {+ expect(() => assertExternalConfigurationMatchesCaType({ caType: CaType.DIGICERT }, CaType.DIGICERT)).not.toThrow();+ expect(() => assertExternalConfigurationMatchesCaType({ template: "x" }, CaType.ADCS)).not.toThrow();+ expect(() => assertExternalConfigurationMatchesCaType(undefined, null)).not.toThrow();+ });++ test("rejects a caType that does not match the certificate authority", () => {+ expect(() => assertExternalConfigurationMatchesCaType({ caType: CaType.ADCS }, CaType.DIGICERT)).toThrow(+ "does not match the type of the selected certificate authority"+ );+ expect(() => assertExternalConfigurationMatchesCaType({ caType: CaType.DIGICERT }, CaType.INTERNAL)).toThrow(+ "does not match"+ );+ });+});++describe("refineSignerCertificateInput", () => {+ const BodySchema = z+ .object({+ commonName: z.string().optional(),+ certificateTtlDays: z.number().optional(),+ keyAlgorithm: SignerKeyAlgorithm.schema.optional(),+ certificate: SignerCertificateInputSchema.optional(),+ externalConfiguration: SignerExternalConfigurationSchema.optional()+ })+ .superRefine(refineSignerCertificateInput);+ const importBody = {+ certificate: {+ keySource: CertKeySource.Hsm,+ hsmConnectorId: "00000000-0000-4000-8000-000000000000",+ hsmKeyLabel: "example-key"+ },+ externalConfiguration: { importFromExternalOrderId: "123" }+ };+ const issuePaths = (body: unknown) => {+ const result = BodySchema.safeParse(body);+ return result.success ? [] : result.error.issues.map((issue) => issue.path.join("."));+ };++ test("accepts an import with an HSM connector and key label", () => {+ expect(issuePaths(importBody)).toEqual([]);+ });++ test("rejects values that come from the imported certificate", () => {+ expect(+ issuePaths({ ...importBody, commonName: "x", certificateTtlDays: 30, keyAlgorithm: CertKeyAlgorithm.RSA_4096 })+ ).toEqual(["commonName", "certificateTtlDays", "keyAlgorithm"]);+ });++ test("requires a key label for an import and rejects one without an import", () => {+ expect(issuePaths({ ...importBody, certificate: { ...importBody.certificate, hsmKeyLabel: undefined } })).toEqual([+ "certificate.hsmKeyLabel"+ ]);+ expect(issuePaths({ certificate: importBody.certificate, keyAlgorithm: CertKeyAlgorithm.RSA_4096 })).toEqual([+ "certificate.hsmKeyLabel"+ ]);+ });++ test("rejects a key label longer than the 128-character column", () => {+ expect(+ issuePaths({ ...importBody, certificate: { ...importBody.certificate, hsmKeyLabel: "k".repeat(129) } })+ ).toEqual(["certificate.hsmKeyLabel"]);+ });++ test("accepts a hex key ID with an import and normalizes it to lowercase", () => {+ const result = BodySchema.safeParse({+ ...importBody,+ certificate: { ...importBody.certificate, hsmKeyId: "0A1B" }+ });+ expect(result.success && result.data.certificate?.hsmKeyId).toBe("0a1b");+ });++ test("rejects a key ID that is not hex bytes or is sent without an import", () => {+ expect(issuePaths({ ...importBody, certificate: { ...importBody.certificate, hsmKeyId: "abc" } })).toEqual([+ "certificate.hsmKeyId"+ ]);+ expect(+ issuePaths({+ certificate: {+ keySource: CertKeySource.Hsm,+ hsmConnectorId: importBody.certificate.hsmConnectorId,+ hsmKeyId: "0a"+ },+ keyAlgorithm: CertKeyAlgorithm.RSA_4096+ })+ ).toEqual(["certificate.hsmKeyId"]);+ });+});diff --git a/backend/src/server/routes/v1/signer-routers/schemas.ts b/backend/src/server/routes/v1/signer-routers/schemas.tsindex 93f74b8e81..2ed81e8ae1 100644--- a/backend/src/server/routes/v1/signer-routers/schemas.ts+++ b/backend/src/server/routes/v1/signer-routers/schemas.ts@@ -3,6 +3,7 @@ import { z } from "zod";import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";import { CaType } from "@app/services/certificate-authority/certificate-authority-enums";+import { CertKeySource } from "@app/services/signer/signer-enums";const RE_NO_NEWLINES = new RE2("^[^\\r\\n]+$");@@ -10,29 +11,58 @@ export const SignerIdParamsSchema = z.object({ signerId: z.string().uuid() });export const SignerRequestParamsSchema = SignerIdParamsSchema.extend({ requestId: z.string().uuid() });-export const SignerExternalConfigurationSchema = z.discriminatedUnion("caType", [- z.object({- caType: z.literal(CaType.DIGICERT),- reissueFromExternalOrderId: z- .string()- .trim()- .min(1)- .optional()- .describe(- "Reissue into this existing DigiCert order instead of placing a new order (reuses the subscription slot)."- )- }),- z.object({- caType: z.literal(CaType.ADCS),- template: z- .string()- .trim()- .min(1)- .refine((v) => RE_NO_NEWLINES.test(v), "Template name must not contain newline characters")- .optional()- .describe("The AD CS certificate template this signer requests when issuing (e.g. a code-signing template).")- })-]);+const ExternalOrderIdSchema = z.string().trim().min(1).max(32);++export const SignerExternalConfigurationSchema = z.object({+ caType: z+ .enum([CaType.DIGICERT, CaType.ADCS])+ .optional()+ .describe(+ "Optional. The CA type is resolved from caId. If provided, it must match the type of that certificate authority."+ ),+ reissueFromExternalOrderId: ExternalOrderIdSchema.optional().describe(+ "DigiCert only. Reissue into this existing DigiCert order instead of placing a new order (reuses the subscription slot). DigiCert revokes the order's previous certificate."+ ),+ importFromExternalOrderId: ExternalOrderIdSchema.optional().describe(+ "DigiCert only. Use the certificate already issued in this DigiCert order, without reissuing it. Requires certificate.hsmKeyLabel to point at the certificate's private key on the HSM. The common name, validity and key algorithm come from that certificate, so commonName, certificateTtlDays and keyAlgorithm can't be sent with it."+ ),+ template: z+ .string()+ .trim()+ .min(1)+ .max(256)+ .refine((v) => RE_NO_NEWLINES.test(v), "Template name must not contain newline characters")+ .optional()+ .describe(+ "Active Directory Certificate Service only. The certificate template this signer requests when issuing (e.g. a code-signing template)."+ )+});++export const SignerCertificateInputSchema = z.object({+ keySource: z.nativeEnum(CertKeySource).optional(),+ hsmConnectorId: z.string().uuid().optional(),+ hsmKeyLabel: z+ .string()+ .trim()+ .min(1)+ .max(128)+ .refine((v) => RE_NO_NEWLINES.test(v), "Key label must not contain newline characters")+ .optional()+ .describe(+ "The label of an existing private key on the HSM. Only used with externalConfiguration.importFromExternalOrderId. If more than one private key in the HSM Connector's slot has this label, also set hsmKeyId."+ ),+ hsmKeyId: z+ .string()+ .trim()+ .min(2)+ .max(256)+ .regex(/^(?:[0-9a-fA-F]{2})+$/, "Key ID must be the hex encoding of the key's CKA_ID")+ .transform((v) => v.toLowerCase())+ .optional()+ .describe(+ "The hex-encoded PKCS#11 key ID (CKA_ID) of the private key, used to tell apart keys that share a label. Only used with hsmKeyLabel."+ )+});export const SignerKeyAlgorithm = {values: [@@ -55,6 +85,74 @@ export const HSM_SUPPORTED_KEY_ALGORITHMS: readonly CertKeyAlgorithm[] = [CertKeyAlgorithm.ECDSA_P384];+export const refineSignerCertificateInput = (+ data: {+ commonName?: string;+ certificateTtlDays?: number;+ keyAlgorithm?: CertKeyAlgorithm;+ certificate?: z.infer<typeof SignerCertificateInputSchema>;+ externalConfiguration?: z.infer<typeof SignerExternalConfigurationSchema>;+ },+ ctx: z.RefinementCtx+) => {+ const isImport = Boolean(data.externalConfiguration?.importFromExternalOrderId);+ if (isImport && data.externalConfiguration?.reissueFromExternalOrderId) {+ ctx.addIssue({+ code: "custom",+ message: "Provide either importFromExternalOrderId or reissueFromExternalOrderId, not both",+ path: ["externalConfiguration", "importFromExternalOrderId"]+ });+ }+ if (isImport) {+ if (data.certificate?.keySource !== CertKeySource.Hsm || !data.certificate.hsmConnectorId) {+ ctx.addIssue({+ code: "custom",+ message: `Using an existing DigiCert certificate requires keySource = '${CertKeySource.Hsm}' and an hsmConnectorId`,+ path: ["certificate", "keySource"]+ });+ }+ if (!data.certificate?.hsmKeyLabel) {+ ctx.addIssue({+ code: "custom",+ message: "hsmKeyLabel is required when using an existing DigiCert certificate",+ path: ["certificate", "hsmKeyLabel"]+ });+ }+ (["commonName", "certificateTtlDays", "keyAlgorithm"] as const).forEach((field) => {+ if (data[field] === undefined) return;+ ctx.addIssue({+ code: "custom",+ message: `${field} comes from the certificate in the DigiCert order and can't be set together with externalConfiguration.importFromExternalOrderId`,+ path: [field]+ });+ });+ return;+ }+ (["hsmKeyLabel", "hsmKeyId"] as const).forEach((field) => {+ if (!data.certificate?.[field]) return;+ ctx.addIssue({+ code: "custom",+ message: `${field} can only be set together with externalConfiguration.importFromExternalOrderId`,+ path: ["certificate", field]+ });+ });+ if (data.certificate?.keySource !== CertKeySource.Hsm) return;+ if (!data.certificate.hsmConnectorId) {+ ctx.addIssue({+ code: "custom",+ message: `hsmConnectorId is required when keySource = '${CertKeySource.Hsm}'`,+ path: ["certificate", "hsmConnectorId"]+ });+ }+ if (!data.keyAlgorithm || !HSM_SUPPORTED_KEY_ALGORITHMS.includes(data.keyAlgorithm)) {+ ctx.addIssue({+ code: "custom",+ message: `keyAlgorithm must be one of ${HSM_SUPPORTED_KEY_ALGORITHMS.join(", ")} when keySource = '${CertKeySource.Hsm}'`,+ path: ["keyAlgorithm"]+ });+ }+};+export const ApprovalPolicyBodySchema = z.object({steps: z.array(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.tsindex f29b3c77af..542ad65649 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@@ -237,6 +237,7 @@ export const certManagerExportServiceFactory = ({keySource: sourceSecret.keySource,hsmConnectorId: sourceSecret.hsmConnectorId,hsmKeyLabel: sourceSecret.hsmKeyLabel,+ hsmKeyId: sourceSecret.hsmKeyId,hsmPublicKeySpki: sourceSecret.hsmPublicKeySpki,encryptedPrivateKey: sourceSecret.encryptedPrivateKey? await reencrypt(sourceSecret.encryptedPrivateKey)diff --git a/backend/src/services/certificate-authority/certificate-authority-fns.ts b/backend/src/services/certificate-authority/certificate-authority-fns.tsindex 942904653b..18a4c686eb 100644--- a/backend/src/services/certificate-authority/certificate-authority-fns.ts+++ b/backend/src/services/certificate-authority/certificate-authority-fns.ts@@ -458,6 +458,8 @@ export const getCaSigner = async ({const connectorId = caSecret.hsmConnectorId;const keyLabel = caSecret.hsmKeyLabel;+ const keyId = caSecret.hsmKeyId;+ const publicKeySpki = caSecret.hsmPublicKeySpki;const signer = buildHsmCaSigner({caPublicKey,keyAlgorithm,@@ -467,6 +469,8 @@ export const getCaSigner = async ({connectorId,projectId: ca.projectId,keyLabel,+ keyId,+ publicKeySpki,mechanism,data,isDigestdiff --git a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-fns.ts b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-fns.tsindex a7b36feac9..d9f3f3a46f 100644--- a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-fns.ts+++ b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-fns.ts@@ -745,6 +745,7 @@ export const DigiCertCertificateAuthorityFns = ({findCodeSigningOrderByReference: codeSigningFns.findCodeSigningOrderByReference,assertCodeSigningOrderReusable: codeSigningFns.assertCodeSigningOrderReusable,getCodeSigningOrderStatus: codeSigningFns.getCodeSigningOrderStatus,+ fetchIssuedCodeSigningCertificate: codeSigningFns.fetchIssuedCodeSigningCertificate,downloadCodeSigningCertificate: codeSigningFns.downloadCodeSigningCertificate};};diff --git a/backend/src/services/certificate-authority/digicert/digicert-code-signing-fns.ts b/backend/src/services/certificate-authority/digicert/digicert-code-signing-fns.tsindex 68c0f4966f..be5e02c703 100644--- a/backend/src/services/certificate-authority/digicert/digicert-code-signing-fns.ts+++ b/backend/src/services/certificate-authority/digicert/digicert-code-signing-fns.ts@@ -1,5 +1,6 @@import * as x509 from "@peculiar/x509";+import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";@@ -35,7 +36,7 @@ import {// DigiCert caps code signing order validity at 459 days (CA/Browser Forum ballot CSC-31 set a// 460-day ceiling effective 2026-03-01; DigiCert's API enforces 459).-const MAX_CS_VALIDITY_DAYS = 459;+export const MAX_CS_VALIDITY_DAYS = 459;// server_platform.id=-1 ("Other") is DigiCert's value for the customer-supplied-CSR lane.const CS_SERVER_PLATFORM_OTHER = -1;@@ -148,6 +149,20 @@ export const digiCertCodeSigningFns = ({return { ca, digicertCa, client: createDigiCertApiClient(apiKey, baseUrl) };};+ const $getOwnedCodeSigningOrder = async (caId: string, orderId: number) => {+ const context = await loadDigiCertCsContext(caId, { requireCodeSigning: true });+ const order = await context.client.getOrder(orderId);+ if (+ order.organization?.id !== context.digicertCa.configuration.organizationId ||+ order.product?.name_id !== context.digicertCa.configuration.productNameId+ ) {+ throw new BadRequestError({+ message: `DigiCert order ${orderId} belongs to a different organization or product than this certificate authority.`+ });+ }+ return { ...context, order };+ };+const orderCodeSigningCertificate = async ({caId,csr,@@ -240,17 +255,7 @@ export const digiCertCodeSigningFns = ({signatureHash: "sha256" | "sha384" | "sha512";comments?: string;}): Promise<{ orderId: number; certificateId: number | null }> => {- const { digicertCa, client } = await loadDigiCertCsContext(caId, { requireCodeSigning: true });-- const targetOrder = await client.getOrder(previousOrderId);- if (- targetOrder.organization?.id !== digicertCa.configuration.organizationId ||- targetOrder.product?.name_id !== digicertCa.configuration.productNameId- ) {- throw new BadRequestError({- message: `DigiCert order ${previousOrderId} does not belong to this CA's organization/product and cannot be reissued here.`- });- }+ const { client } = await $getOwnedCodeSigningOrder(caId, previousOrderId);const reissuePayload: TReissueCodeSigningOrderRequest = {certificate: {@@ -278,16 +283,7 @@ export const digiCertCodeSigningFns = ({};const assertCodeSigningOrderReusable = async (caId: string, orderId: number): Promise<void> => {- const { digicertCa, client } = await loadDigiCertCsContext(caId, { requireCodeSigning: true });- const order = await client.getOrder(orderId);- const sameOrg = order.organization?.id === digicertCa.configuration.organizationId;- const sameProduct = order.product?.name_id === digicertCa.configuration.productNameId;- if (!sameOrg || !sameProduct) {- throw new BadRequestError({- message:- "That DigiCert order belongs to a different organization or product than this certificate authority and cannot be reused."- });- }+ await $getOwnedCodeSigningOrder(caId, orderId);};const getCodeSigningOrderStatus = async (caId: string, orderId: number): Promise<TCodeSigningOrderInfo> => {@@ -301,6 +297,33 @@ export const digiCertCodeSigningFns = ({};};+ const fetchIssuedCodeSigningCertificate = async (+ caId: string,+ orderId: number+ ): Promise<{ pemBundle: string; certificate: x509.X509Certificate }> => {+ const { client, order } = await $getOwnedCodeSigningOrder(caId, orderId);+ if (normalizeCodeSigningStatus(order.status) !== CodeSigningOrderStatus.Issued || !order.certificate?.id) {+ throw new BadRequestError({+ message: `DigiCert order ${orderId} has no issued certificate to use (order status: '${order.status}').`+ });+ }++ const pemBundle = await client.downloadCertificatePem(order.certificate.id);+ const certificate = new x509.X509Certificate(extractLeafAndChain(pemBundle).leaf);+ if (certificate.notAfter < new Date()) {+ throw new BadRequestError({+ message: `The certificate in DigiCert order ${orderId} expired on ${certificate.notAfter.toISOString()}.`+ });+ }+ const eku = certificate.getExtension(x509.ExtendedKeyUsageExtension);+ if (!eku?.usages.some((usage) => usage === x509.ExtendedKeyUsage.codeSigning)) {+ throw new BadRequestError({+ message: `The certificate in DigiCert order ${orderId} does not have the code signing extended key usage.`+ });+ }+ return { pemBundle, certificate };+ };+const downloadCodeSigningCertificate = async ({caId,orderId,@@ -308,18 +331,23 @@ export const digiCertCodeSigningFns = ({keyAlgorithm,signatureAlgorithm,applicationId,- profileId+ profileId,+ pemBundle: providedPemBundle}: {caId: string;orderId: number;- digicertCertificateId: number;+ digicertCertificateId?: number;+ pemBundle?: string;keyAlgorithm?: string;signatureAlgorithm?: string;applicationId?: string | null;profileId?: string | null;}): Promise<{ certificateId: string; certificatePem: string }> => {const { ca, client } = await loadDigiCertCsContext(caId);- const pemBundle = await client.downloadCertificatePem(digicertCertificateId);+ if (!providedPemBundle && !digicertCertificateId) {+ throw new BadRequestError({ message: `DigiCert order ${orderId} has no certificate to download.` });+ }+ const pemBundle = providedPemBundle ?? (await client.downloadCertificatePem(digicertCertificateId as number));const { leaf, chain } = extractLeafAndChain(pemBundle);const certObj = new x509.X509Certificate(leaf);@@ -343,40 +371,53 @@ export const digiCertCodeSigningFns = ({plainText: Buffer.from(chain)});- const createdCertificateId = await certificateDAL.transaction(async (tx) => {- const cert = await certificateDAL.create(- {- ...parsedFields,- caId: ca.id,- applicationId: applicationId ?? undefined,- profileId: profileId ?? undefined,- status: CertStatus.ACTIVE,- projectId: ca.projectId,- friendlyName: parsedFields.commonName || "",- commonName: parsedFields.commonName || "",- keyUsages: parsedFields.keyUsages ?? [],- extendedKeyUsages: parsedFields.extendedKeyUsages ?? [],- keyAlgorithm: parsedFields.keyAlgorithm ?? keyAlgorithm,- signatureAlgorithm: parsedFields.signatureAlgorithm ?? signatureAlgorithm,- externalMetadata: {- type: CaType.DIGICERT,- orderId- } satisfies TDigiCertExternalMetadata- },- tx- );+ const createdCertificateId = await certificateDAL+ .transaction(async (tx) => {+ const cert = await certificateDAL.create(+ {+ ...parsedFields,+ caId: ca.id,+ applicationId: applicationId ?? undefined,+ profileId: profileId ?? undefined,+ status: CertStatus.ACTIVE,+ projectId: ca.projectId,+ friendlyName: parsedFields.commonName || "",+ commonName: parsedFields.commonName || "",+ keyUsages: parsedFields.keyUsages ?? [],+ extendedKeyUsages: parsedFields.extendedKeyUsages ?? [],+ keyAlgorithm: parsedFields.keyAlgorithm ?? keyAlgorithm,+ signatureAlgorithm: parsedFields.signatureAlgorithm ?? signatureAlgorithm,+ externalMetadata: {+ type: CaType.DIGICERT,+ orderId+ } satisfies TDigiCertExternalMetadata+ },+ tx+ );- await certificateBodyDAL.create(- {- certId: cert.id,- encryptedCertificate,- encryptedCertificateChain- },- tx- );+ await certificateBodyDAL.create(+ {+ certId: cert.id,+ encryptedCertificate,+ encryptedCertificateChain+ },+ tx+ );- return cert.id;- });+ return cert.id;+ })+ .catch(async (error: unknown) => {+ if ((error as { error?: { code?: string } })?.error?.code === DatabaseErrorCode.UniqueViolation) {+ const concurrentCert = await certificateDAL.transaction((tx) =>+ certificateDAL.findOne({ caId: ca.id, serialNumber: certObj.serialNumber }, tx)+ );+ if (concurrentCert) return concurrentCert.id;+ throw new BadRequestError({+ message: `The certificate in DigiCert order ${orderId} is already in Certificate Manager under a different certificate authority. Remove that copy from the certificate inventory, then try again.`+ });+ }+ throw error;+ });return { certificateId: createdCertificateId, certificatePem: leaf };};@@ -388,6 +429,7 @@ export const digiCertCodeSigningFns = ({findCodeSigningOrderByReference,assertCodeSigningOrderReusable,getCodeSigningOrderStatus,+ fetchIssuedCodeSigningCertificate,downloadCodeSigningCertificate};};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.tsindex 330202938c..029d5d5326 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@@ -427,7 +427,7 @@ export const internalCertificateAuthorityServiceFactory = ({let caSigner: TCaSigner;let localKeys: CryptoKeyPair | undefined;- let hsmKey: { keyLabel: string; publicKeySpkiDer: Buffer } | undefined;+ let hsmKey: { keyLabel: string; keyId: string | null; publicKeySpkiDer: Buffer } | undefined;if (useHsm) {if (!dto.hsmConnectorId) {@@ -476,12 +476,21 @@ export const internalCertificateAuthorityServiceFactory = ({["verify"]);const connectorId = dto.hsmConnectorId;- const { keyLabel } = generated;+ const { keyLabel, keyId } = generated;caSigner = buildHsmCaSigner({caPublicKey,keyAlgorithm,sign: (data, mechanism, isDigest) =>- hsmConnectorService.sign({ connectorId, projectId, keyLabel, mechanism, data, isDigest })+ hsmConnectorService.sign({+ connectorId,+ projectId,+ keyLabel,+ keyId,+ publicKeySpki: generated.publicKeySpkiDer,+ mechanism,+ data,+ isDigest+ })});} else {const cryptoEngine = isPqcAlgorithm(keyAlgorithm) ? getPqcCrypto() : crypto.nativeCrypto;@@ -625,6 +634,7 @@ export const internalCertificateAuthorityServiceFactory = ({keySource: CertKeySource.Hsm,hsmConnectorId: dto.hsmConnectorId,hsmKeyLabel: hsmKey.keyLabel,+ hsmKeyId: hsmKey.keyId,hsmPublicKeySpki: hsmKey.publicKeySpkiDer},txdiff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.tsindex b040c74ff0..ae14d20a1d 100644--- a/backend/src/services/certificate/certificate-dal.ts+++ b/backend/src/services/certificate/certificate-dal.ts@@ -949,6 +949,14 @@ export const certificateDALFactory = (db: TDbClient) => {type TCertificateLookupFilter = { id: string; serialNumber?: never } | { id?: never; serialNumber: string };+ const findByIdForUpdate = async (id: string, tx: Knex) => {+ try {+ return await tx(TableName.Certificate).where({ id }).forUpdate().first();+ } catch (error) {+ throw new DatabaseError({ error, name: "Find certificate by id for update" });+ }+ };+const findLatestRenewalOf = async (anchor: { id: string; orderId: string }, tx?: Knex): Promise<string | null> => {try {const newer = await (tx || db.replicaNode())(TableName.Certificate)@@ -1469,6 +1477,7 @@ export const certificateDALFactory = (db: TDbClient) => {findWithPrivateKeyInfo,findWithFullDetails,findLatestRenewalOf,+ findByIdForUpdate,getDashboardStats,getActivityTrend,getPqcTrenddiff --git a/backend/src/services/hsm-connector/hsm-connector-routing.ts b/backend/src/services/hsm-connector/hsm-connector-routing.tsindex 83fad50c3e..251ab11d90 100644--- a/backend/src/services/hsm-connector/hsm-connector-routing.ts+++ b/backend/src/services/hsm-connector/hsm-connector-routing.ts@@ -2,7 +2,12 @@ import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gatewaimport { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";-import { callPkcs11Endpoint, isRetryablePkcs11RpcError, Pkcs11RpcEndpoint } from "@app/lib/gateway-v2/pkcs11-rpc";+import {+ callPkcs11Endpoint,+ isRetryablePkcs11RpcError,+ Pkcs11ErrorCode,+ Pkcs11RpcEndpoint+} from "@app/lib/gateway-v2/pkcs11-rpc";import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";import { logger } from "@app/lib/logger";@@ -126,7 +131,7 @@ export const hsmConnectorRoutingFactory = ({ gatewayV2Service, gatewayPoolServic);} catch (err) {lastError = {- code: "gateway_unreachable",+ code: Pkcs11ErrorCode.GatewayUnreachable,message: err instanceof Error ? err.message : String(err)};if (!args.connector.gatewayPoolId) break;@@ -153,7 +158,12 @@ export const hsmConnectorRoutingFactory = ({ gatewayV2Service, gatewayPoolServictargetPort: 0});if (!conn) {- return { gatewayId, ok: false, errorCode: "gateway_not_found", errorMessage: `Gateway ${gatewayId} not found.` };+ return {+ gatewayId,+ ok: false,+ errorCode: Pkcs11ErrorCode.GatewayNotFound,+ errorMessage: `Gateway ${gatewayId} not found.`+ };}try {const response = await withGatewayV2Proxy(@@ -177,7 +187,7 @@ export const hsmConnectorRoutingFactory = ({ gatewayV2Service, gatewayPoolServicreturn {gatewayId,ok: false,- errorCode: "gateway_unreachable",+ errorCode: Pkcs11ErrorCode.GatewayUnreachable,errorMessage: err instanceof Error ? err.message : String(err)};}diff --git a/backend/src/services/hsm-connector/hsm-connector-service.ts b/backend/src/services/hsm-connector/hsm-connector-service.tsindex 9dbffae2e5..01b4fc7880 100644--- a/backend/src/services/hsm-connector/hsm-connector-service.ts+++ b/backend/src/services/hsm-connector/hsm-connector-service.ts@@ -15,6 +15,7 @@ import {ProjectPermissionSub} from "@app/ee/services/permission/project-permission";import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { isPkcs11Error, Pkcs11ErrorCode } from "@app/lib/gateway-v2/pkcs11-rpc";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TOrgDALFactory } from "@app/services/org/org-dal";import { HsmKeyAlgorithm } from "@app/services/signer/signer-enums";@@ -32,6 +33,7 @@ import type {TDeleteHsmConnectorDTO,TGetHsmConnectorByIdDTO,THsmConnectorCredentials,+ THsmConnectorKey,THsmConnectorSanitized,THsmConnectorServiceActor,TListHsmConnectorsDTO,@@ -53,6 +55,8 @@ export type THsmConnectorServiceFactoryDep = {export type THsmConnectorServiceFactory = ReturnType<typeof hsmConnectorServiceFactory>;+const OLD_GATEWAY_BAD_REQUEST_MESSAGE = "Invalid request";+export const hsmConnectorServiceFactory = ({hsmConnectorDAL,permissionService,@@ -411,17 +415,44 @@ export const hsmConnectorServiceFactory = ({return { projectId: row.projectId, name: row.name, result };};+ const $decryptCredentials = (row: { projectId: string; encryptedCredentials: Buffer }) =>+ decryptHsmConnectorCredentials({+ projectId: row.projectId,+ encryptedCredentials: row.encryptedCredentials,+ kmsService+ });+const $loadConnector = async (connectorId: string, expectedProjectId: string) => {const row = await hsmConnectorDAL.findById(connectorId);if (!row || row.projectId !== expectedProjectId) {throw new NotFoundError({ message: `HSM Connector ${connectorId} not found.` });}- const credentials = await decryptHsmConnectorCredentials({- projectId: row.projectId,- encryptedCredentials: row.encryptedCredentials,- kmsService- });- return { row, credentials };+ return { row, credentials: await $decryptCredentials(row) };+ };++ const $rethrowKeyError = (err: unknown, keyLabel: string, keyId?: string | null): never => {+ if (+ keyId &&+ err instanceof BadRequestError &&+ err.message.endsWith(`(${Pkcs11ErrorCode.BadRequest}): ${OLD_GATEWAY_BAD_REQUEST_MESSAGE}`)+ ) {+ throw new BadRequestError({+ message: `The HSM Connector's gateway rejected the request for the key labeled '${keyLabel}'. If more than one key in the slot has this label, update the gateway to the latest version so it can select keys by key ID.`+ });+ }+ if (isPkcs11Error(err, Pkcs11ErrorCode.SignatureMismatch)) {+ throw new BadRequestError({+ message: `The HSM key labeled '${keyLabel}' produced a signature that doesn't verify with the certificate's public key. Check that the label points to the certificate's private key.`+ });+ }+ if (isPkcs11Error(err, Pkcs11ErrorCode.KeyAmbiguous)) {+ throw new BadRequestError({+ message: keyId+ ? `More than one key in the HSM Connector's slot has the label '${keyLabel}' and key ID '${keyId}'. Give the keys unique labels or key IDs.`+ : `More than one key in the HSM Connector's slot has the label '${keyLabel}'. Set the key ID to choose one, or give the keys unique labels.`+ });+ }+ throw err;};const generateKeyPair = async (args: {@@ -429,53 +460,110 @@ export const hsmConnectorServiceFactory = ({projectId: string;keyLabel: string;keyAlgorithm: HsmKeyAlgorithm;- }): Promise<{ publicKeySpkiDer: Buffer; keyLabel: string }> => {+ }): Promise<{ publicKeySpkiDer: Buffer; keyLabel: string; keyId: string | null }> => {const { row, credentials } = await $loadConnector(args.connectorId, args.projectId);const prefix = credentials.keyNamePrefix ?? "";const fullLabel = `${prefix}${args.keyLabel}`;- const result = await routing.dispatchPkcs11<{ publicKey: string }>({+ const result = await routing.dispatchPkcs11<{ publicKey: string; keyId?: string }>({connector: { gatewayId: row.gatewayId, gatewayPoolId: row.gatewayPoolId },credentials,endpoint: "/v1/generate-key-pair",params: { keyLabel: fullLabel, keyAlgorithm: args.keyAlgorithm }});- return { publicKeySpkiDer: Buffer.from(result.publicKey, "base64"), keyLabel: fullLabel };+ return {+ publicKeySpkiDer: Buffer.from(result.publicKey, "base64"),+ keyLabel: fullLabel,+ keyId: result.keyId || null+ };};- const sign = async (args: {+ const signWithKeyId = async (args: {connectorId: string;projectId: string;keyLabel: string;+ keyId?: string | null;+ publicKeySpki: Buffer | null;mechanism: string;data: Buffer;isDigest: boolean;- }): Promise<Buffer> => {+ }): Promise<{ signature: Buffer; keyId: string | null }> => {const { row, credentials } = await $loadConnector(args.connectorId, args.projectId);- const result = await routing.dispatchPkcs11<{ signature: string }>({- connector: { gatewayId: row.gatewayId, gatewayPoolId: row.gatewayPoolId },- credentials,- endpoint: "/v1/sign",- params: {- keyLabel: args.keyLabel,- mechanism: args.mechanism,- data: args.data.toString("base64"),- isDigest: args.isDigest- }- });- return Buffer.from(result.signature, "base64");+ const result = await routing+ .dispatchPkcs11<{ signature: string; keyId?: string }>({+ connector: { gatewayId: row.gatewayId, gatewayPoolId: row.gatewayPoolId },+ credentials,+ endpoint: "/v1/sign",+ params: {+ keyLabel: args.keyLabel,+ keyId: args.keyId ?? "",+ publicKey: args.publicKeySpki?.toString("base64") ?? "",+ mechanism: args.mechanism,+ data: args.data.toString("base64"),+ isDigest: args.isDigest+ }+ })+ .catch((err: unknown) => {+ if (isPkcs11Error(err, Pkcs11ErrorCode.KeyNotFound)) {+ throw new BadRequestError({+ message: args.keyId+ ? `No private key with the label '${args.keyLabel}' and key ID '${args.keyId}' was found in the HSM Connector's slot.`+ : `No private key labeled '${args.keyLabel}' was found in the HSM Connector's slot.`+ });+ }+ return $rethrowKeyError(err, args.keyLabel, args.keyId);+ });+ return { signature: Buffer.from(result.signature, "base64"), keyId: result.keyId || null };};- const getPublicKey = async (args: { connectorId: string; projectId: string; keyLabel: string }): Promise<Buffer> => {+ const sign = async (args: Parameters<typeof signWithKeyId>[0]): Promise<Buffer> =>+ (await signWithKeyId(args)).signature;++ const getPublicKey = async (args: {+ connectorId: string;+ projectId: string;+ keyLabel: string;+ keyId?: string | null;+ }): Promise<Buffer> => {const { row, credentials } = await $loadConnector(args.connectorId, args.projectId);- const result = await routing.dispatchPkcs11<{ publicKey: string }>({- connector: { gatewayId: row.gatewayId, gatewayPoolId: row.gatewayPoolId },- credentials,- endpoint: "/v1/get-public-key",- params: { keyLabel: args.keyLabel }- });+ const result = await routing+ .dispatchPkcs11<{ publicKey: string }>({+ connector: { gatewayId: row.gatewayId, gatewayPoolId: row.gatewayPoolId },+ credentials,+ endpoint: "/v1/get-public-key",+ params: { keyLabel: args.keyLabel, keyId: args.keyId ?? "" }+ })+ .catch((err: unknown) => $rethrowKeyError(err, args.keyLabel, args.keyId));return Buffer.from(result.publicKey, "base64");};+ const listHsmConnectorKeys = async (+ dto: { connectorId: string; keyLabel: string },+ actor: THsmConnectorServiceActor+ ) => {+ const row = await hsmConnectorDAL.findById(dto.connectorId);+ if (!row) throw new NotFoundError({ message: `HSM Connector ${dto.connectorId} not found.` });++ await assertProjectPermission(actor, row.projectId, ProjectPermissionHsmConnectorActions.Attach);++ const credentials = await $decryptCredentials(row);+ const result = await routing+ .dispatchPkcs11<{ keys: THsmConnectorKey[] }>({+ connector: { gatewayId: row.gatewayId, gatewayPoolId: row.gatewayPoolId },+ credentials,+ endpoint: "/v1/find-keys",+ params: { keyLabel: dto.keyLabel }+ })+ .catch((err: unknown) => {+ if (isPkcs11Error(err, Pkcs11ErrorCode.UnsupportedGatewayVersion)) {+ throw new BadRequestError({+ message: "The HSM Connector's gateway is too old to look up keys. Update the gateway to the latest version."+ });+ }+ throw err;+ });+ return { keys: result.keys };+ };+const assertAttachPermission = async (actor: Pick<THsmConnectorServiceActor, "type" | "id" | "authMethod" | "orgId">,connectorId: string,@@ -504,6 +592,8 @@ export const hsmConnectorServiceFactory = ({assertAttachPermission,generateKeyPair,sign,- getPublicKey+ signWithKeyId,+ getPublicKey,+ listHsmConnectorKeys};};diff --git a/backend/src/services/hsm-connector/hsm-connector-types.ts b/backend/src/services/hsm-connector/hsm-connector-types.tsindex 61a1ecaeec..dd225ab397 100644--- a/backend/src/services/hsm-connector/hsm-connector-types.ts+++ b/backend/src/services/hsm-connector/hsm-connector-types.ts@@ -68,4 +68,10 @@ export type THsmConnectorSanitized = {updatedAt: Date;};+export type THsmConnectorKey = {+ label: string;+ keyId: string;+ keyAlgorithm: string;+};+export type THsmConnectorServiceActor = OrgServiceActor;diff --git a/backend/src/services/signer/signer-enums.ts b/backend/src/services/signer/signer-enums.tsindex 20291f0ece..b52dddf405 100644--- a/backend/src/services/signer/signer-enums.ts+++ b/backend/src/services/signer/signer-enums.ts@@ -26,6 +26,7 @@ export enum CertKeySource {export enum HsmKeyAlgorithm {RSA_2048 = "RSA_2048",+ RSA_3072 = "RSA_3072",RSA_4096 = "RSA_4096",ECC_P256 = "ECC_P256",ECC_P384 = "ECC_P384"diff --git a/backend/src/services/signer/signer-issuance-fns.test.ts b/backend/src/services/signer/signer-issuance-fns.test.tsnew file mode 100644index 0000000000..afb468e6e0--- /dev/null+++ b/backend/src/services/signer/signer-issuance-fns.test.ts@@ -0,0 +1,165 @@+import { webcrypto } from "node:crypto";++import * as x509 from "@peculiar/x509";+import { beforeAll, describe, expect, it } from "vitest";++import { assertHsmKeyMatchesCertificate } from "./signer-issuance-fns";++type TCase = {+ name: string;+ gen: RsaHashedKeyGenParams | EcKeyGenParams;+ sign: AlgorithmIdentifier | EcdsaParams;+ mechanism: string;+};++const CASES: TCase[] = [+ {+ name: "RSA-3072",+ gen: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256", publicExponent: new Uint8Array([1, 0, 1]), modulusLength: 3072 },+ sign: { name: "RSASSA-PKCS1-v1_5" },+ mechanism: "CKM_SHA256_RSA_PKCS"+ },+ {+ name: "ECDSA P-256",+ gen: { name: "ECDSA", namedCurve: "P-256" },+ sign: { name: "ECDSA", hash: "SHA-256" },+ mechanism: "CKM_ECDSA_SHA256"+ },+ {+ name: "ECDSA P-384",+ gen: { name: "ECDSA", namedCurve: "P-384" },+ sign: { name: "ECDSA", hash: "SHA-256" },+ mechanism: "CKM_ECDSA_SHA256"+ }+];++const generateKeys = async (gen: TCase["gen"]) =>+ (await webcrypto.subtle.generateKey(gen, true, ["sign", "verify"])) as CryptoKeyPair;++const createCertificate = async (gen: TCase["gen"], keys: CryptoKeyPair) =>+ x509.X509CertificateGenerator.createSelfSigned({+ serialNumber: "01",+ name: "CN=Example Code Signing",+ notBefore: new Date(Date.now() - 86_400_000),+ notAfter: new Date(Date.now() + 86_400_000),+ signingAlgorithm: gen as Algorithm,+ keys+ });++const signedWithPublicKeys: (Buffer | null)[] = [];++const fakeHsm = (testCase: TCase, privateKey: CryptoKey, publicKeySpki?: Buffer) => ({+ getPublicKey: async () => {+ if (!publicKeySpki) throw new Error("PKCS#11 request failed (key_not_found): Key not found on this HSM");+ return publicKeySpki;+ },+ signWithKeyId: async (args: { mechanism: string; data: Buffer; isDigest: boolean; publicKeySpki: Buffer | null }) => {+ expect(args.mechanism).toBe(testCase.mechanism);+ signedWithPublicKeys.push(args.publicKeySpki);+ expect(args.isDigest).toBe(false);+ return {+ signature: Buffer.from(await webcrypto.subtle.sign(testCase.sign, privateKey, args.data)),+ keyId: "0a1b"+ };+ }+});++beforeAll(() => {+ x509.cryptoProvider.set(webcrypto as unknown as Crypto);+});++describe.each(CASES)("assertHsmKeyMatchesCertificate: $name", (testCase) => {+ const input = { hsmConnectorId: "connector", projectId: "project", hsmKeyLabel: "example-key" };++ it("should accept the key the certificate was issued for and return its key ID", async () => {+ const keys = await generateKeys(testCase.gen);+ const certificate = await createCertificate(testCase.gen, keys);++ await expect(+ assertHsmKeyMatchesCertificate(+ { hsmConnectorService: fakeHsm(testCase, keys.privateKey) },+ { ...input, certificate }+ )+ ).resolves.toEqual({ hsmKeyId: "0a1b" });+ expect(signedWithPublicKeys.at(-1)?.equals(Buffer.from(certificate.publicKey.rawData))).toBe(true);+ });++ it("should reject without signing when the HSM's public key for the label differs from the certificate", async () => {+ const certificateKeys = await generateKeys(testCase.gen);+ const otherKeys = await generateKeys(testCase.gen);+ const certificate = await createCertificate(testCase.gen, certificateKeys);+ const otherSpki = Buffer.from(await webcrypto.subtle.exportKey("spki", otherKeys.publicKey));+ const hsm = {+ getPublicKey: async () => otherSpki,+ signWithKeyId: async () => {+ throw new Error("sign must not be called");+ }+ };++ await expect(+ assertHsmKeyMatchesCertificate({ hsmConnectorService: hsm }, { ...input, certificate })+ ).rejects.toThrow("does not match the certificate's public key");+ });++ it("should fall back to a challenge signature when the HSM can't read the public key", async () => {+ const keys = await generateKeys(testCase.gen);+ const certificate = await createCertificate(testCase.gen, keys);+ const hsm = {+ ...fakeHsm(testCase, keys.privateKey),+ getPublicKey: async () => {+ throw new Error("PKCS#11 request failed (internal): Operation failed");+ }+ };++ await expect(+ assertHsmKeyMatchesCertificate({ hsmConnectorService: hsm }, { ...input, certificate })+ ).resolves.toEqual({ hsmKeyId: "0a1b" });+ });++ it("should surface HSM errors other than a missing public key without signing", async () => {+ const keys = await generateKeys(testCase.gen);+ const certificate = await createCertificate(testCase.gen, keys);+ const hsm = {+ getPublicKey: async () => {+ throw new Error("PKCS#11 request failed (pin_incorrect): The HSM rejected the PIN");+ },+ signWithKeyId: async () => {+ throw new Error("sign must not be called");+ }+ };++ await expect(+ assertHsmKeyMatchesCertificate({ hsmConnectorService: hsm }, { ...input, certificate })+ ).rejects.toThrow("(pin_incorrect)");+ });++ it("should explain an older gateway rejecting a duplicate label without signing", async () => {+ const keys = await generateKeys(testCase.gen);+ const certificate = await createCertificate(testCase.gen, keys);+ const hsm = {+ getPublicKey: async () => {+ throw new Error("PKCS#11 request failed (bad_request): Invalid request");+ },+ signWithKeyId: async () => {+ throw new Error("sign must not be called");+ }+ };++ await expect(+ assertHsmKeyMatchesCertificate({ hsmConnectorService: hsm }, { ...input, certificate })+ ).rejects.toThrow("Check that exactly one private key in the HSM Connector's slot has this label.");+ });++ it("should reject a key that does not match the certificate", async () => {+ const certificateKeys = await generateKeys(testCase.gen);+ const otherKeys = await generateKeys(testCase.gen);+ const certificate = await createCertificate(testCase.gen, certificateKeys);++ await expect(+ assertHsmKeyMatchesCertificate(+ { hsmConnectorService: fakeHsm(testCase, otherKeys.privateKey) },+ { ...input, certificate }+ )+ ).rejects.toThrow("does not match the certificate's public key");+ });+});diff --git a/backend/src/services/signer/signer-issuance-fns.ts b/backend/src/services/signer/signer-issuance-fns.tsindex a8b2547ace..db8a73e7e8 100644--- a/backend/src/services/signer/signer-issuance-fns.ts+++ b/backend/src/services/signer/signer-issuance-fns.ts@@ -6,6 +6,7 @@ import { crypto } from "@app/lib/crypto/cryptography";import { isPqcAlgorithm } from "@app/lib/crypto/pqc";import { buildCsrWithExternalSigner } from "@app/lib/csr/build-csr-with-external-signer";import { BadRequestError } from "@app/lib/errors";+import { isPkcs11Error, Pkcs11ErrorCode } from "@app/lib/gateway-v2/pkcs11-rpc";import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";@@ -202,6 +203,8 @@ export const hsmKeyAlgorithmToCertKeyAlgorithm = (hsmAlg: HsmKeyAlgorithm): Certswitch (hsmAlg) {case HsmKeyAlgorithm.RSA_2048:return CertKeyAlgorithm.RSA_2048;+ case HsmKeyAlgorithm.RSA_3072:+ return CertKeyAlgorithm.RSA_3072;case HsmKeyAlgorithm.RSA_4096:return CertKeyAlgorithm.RSA_4096;case HsmKeyAlgorithm.ECC_P256:@@ -219,6 +222,8 @@ export const mapCertKeyAlgorithmToHsmKeyAlgorithm = (certAlg: string): HsmKeyAlgswitch (certAlg) {case CertKeyAlgorithm.RSA_2048:return HsmKeyAlgorithm.RSA_2048;+ case CertKeyAlgorithm.RSA_3072:+ return HsmKeyAlgorithm.RSA_3072;case CertKeyAlgorithm.RSA_4096:return HsmKeyAlgorithm.RSA_4096;case CertKeyAlgorithm.ECDSA_P256:@@ -235,7 +240,7 @@ export const mapCertKeyAlgorithmToHsmKeyAlgorithm = (certAlg: string): HsmKeyAlgexport const issueHsmBackedSignerCertificate = async (deps: THsmBackedDeps,input: THsmBackedInput-): Promise<{ certificateId: string; hsmKeyLabel: string }> => {+): Promise<{ certificateId: string; hsmKeyLabel: string; hsmKeyId: string | null }> => {const ca = await deps.certificateAuthorityDAL.findByIdWithAssociatedCa(input.caId);if (!ca || ca.projectId !== input.projectId) {throw new BadRequestError({@@ -253,7 +258,7 @@ export const issueHsmBackedSignerCertificate = async (const keyLabelSuffix = `signer-${crypto.nativeCrypto.randomUUID()}`;- const { publicKeySpkiDer, keyLabel } = await deps.hsmConnectorService.generateKeyPair({+ const { publicKeySpkiDer, keyLabel, keyId } = await deps.hsmConnectorService.generateKeyPair({connectorId: input.hsmConnectorId,projectId: input.projectId,keyLabel: keyLabelSuffix,@@ -268,6 +273,8 @@ export const issueHsmBackedSignerCertificate = async (connectorId: input.hsmConnectorId,projectId: input.projectId,keyLabel,+ keyId,+ publicKeySpki: publicKeySpkiDer,mechanism,data: tbsBytes,isDigest@@ -298,6 +305,7 @@ export const issueHsmBackedSignerCertificate = async (keySource: CertKeySource.Hsm,hsmConnectorId: input.hsmConnectorId,hsmKeyLabel: keyLabel,+ hsmKeyId: keyId,hsmPublicKeySpki: publicKeySpkiDer,keyAlgorithm: hsmKeyAlgorithmToCertKeyAlgorithm(input.hsmKeyAlgorithm)},@@ -307,7 +315,7 @@ export const issueHsmBackedSignerCertificate = async (};const certificateId = input.tx ? await run(input.tx) : await deps.projectDAL.transaction(run);- return { certificateId, hsmKeyLabel: keyLabel };+ return { certificateId, hsmKeyLabel: keyLabel, hsmKeyId: keyId };};type THsmBackedRenewInput = {@@ -317,6 +325,7 @@ type THsmBackedRenewInput = {certificateTtlDays: number;hsmConnectorId: string;hsmKeyLabel: string;+ hsmKeyId?: string | null;hsmKeyAlgorithm: HsmKeyAlgorithm;expectedPublicKeySpkiDer?: Buffer;tx?: Knex;@@ -329,7 +338,7 @@ type THsmBackedRenewDeps = THsmBackedDeps & {export const renewHsmBackedSignerCertificate = async (deps: THsmBackedRenewDeps,input: THsmBackedRenewInput-): Promise<{ certificateId: string; hsmKeyLabel: string }> => {+): Promise<{ certificateId: string; hsmKeyLabel: string; hsmKeyId: string | null }> => {const ca = await deps.certificateAuthorityDAL.findByIdWithAssociatedCa(input.caId);if (!ca || ca.projectId !== input.projectId) {throw new BadRequestError({ message: `Certificate authority '${input.caId}' was not found.` });@@ -346,7 +355,8 @@ export const renewHsmBackedSignerCertificate = async (const publicKeySpkiDer = await deps.hsmConnectorService.getPublicKey({connectorId: input.hsmConnectorId,projectId: input.projectId,- keyLabel: input.hsmKeyLabel+ keyLabel: input.hsmKeyLabel,+ keyId: input.hsmKeyId});if (input.expectedPublicKeySpkiDer) {const stored = input.expectedPublicKeySpkiDer;@@ -366,6 +376,8 @@ export const renewHsmBackedSignerCertificate = async (connectorId: input.hsmConnectorId,projectId: input.projectId,keyLabel: input.hsmKeyLabel,+ keyId: input.hsmKeyId,+ publicKeySpki: publicKeySpkiDer,mechanism,data: tbsBytes,isDigest@@ -396,6 +408,8 @@ export const renewHsmBackedSignerCertificate = async (keySource: CertKeySource.Hsm,hsmConnectorId: input.hsmConnectorId,hsmKeyLabel: input.hsmKeyLabel,+ hsmKeyId: input.hsmKeyId ?? null,+ hsmPublicKeySpki: publicKeySpkiDer,keyAlgorithm: hsmKeyAlgorithmToCertKeyAlgorithm(input.hsmKeyAlgorithm)},tx@@ -404,5 +418,96 @@ export const renewHsmBackedSignerCertificate = async (};const certificateId = input.tx ? await run(input.tx) : await deps.projectDAL.transaction(run);- return { certificateId, hsmKeyLabel: input.hsmKeyLabel };+ return { certificateId, hsmKeyLabel: input.hsmKeyLabel, hsmKeyId: input.hsmKeyId ?? null };+};++const PUBLIC_KEY_PRECHECK_FALLBACK_CODES = [+ Pkcs11ErrorCode.KeyNotFound,+ Pkcs11ErrorCode.MechanismInvalid,+ Pkcs11ErrorCode.Internal+];++export const assertHsmKeyMatchesCertificate = async (+ deps: { hsmConnectorService: Pick<THsmConnectorServiceFactory, "signWithKeyId" | "getPublicKey"> },+ input: {+ hsmConnectorId: string;+ projectId: string;+ hsmKeyLabel: string;+ hsmKeyId?: string | null;+ certificate: x509.X509Certificate;+ }+): Promise<{ hsmKeyId: string | null }> => {+ const keyMismatchError = () =>+ new BadRequestError({+ message: input.hsmKeyId+ ? `The HSM key with the label '${input.hsmKeyLabel}' and key ID '${input.hsmKeyId}' does not match the certificate's public key. Select the private key the certificate was issued for.`+ : `The HSM key labeled '${input.hsmKeyLabel}' does not match the certificate's public key. Check that the label points to the private key the certificate was issued for.`+ });++ const keyRejectedError = () =>+ new BadRequestError({+ message: `The HSM rejected the key labeled '${input.hsmKeyLabel}'. Check that exactly one private key in the HSM Connector's slot has this label.`+ });++ const publicKey = crypto.nativeCrypto.createPublicKey({+ key: Buffer.from(input.certificate.publicKey.rawData),+ format: "der",+ type: "spki"+ });+ const isEcdsa = publicKey.asymmetricKeyType === "ec";+ if (!isEcdsa && publicKey.asymmetricKeyType !== "rsa") {+ throw new BadRequestError({+ message: `The certificate uses an unsupported key type '${publicKey.asymmetricKeyType}'. Only RSA and ECDSA keys are supported.`+ });+ }++ const hsmPublicKey = await deps.hsmConnectorService+ .getPublicKey({+ connectorId: input.hsmConnectorId,+ projectId: input.projectId,+ keyLabel: input.hsmKeyLabel,+ keyId: input.hsmKeyId+ })+ .then((spki) => crypto.nativeCrypto.createPublicKey({ key: spki, format: "der", type: "spki" }))+ .catch((err: unknown) => {+ if (PUBLIC_KEY_PRECHECK_FALLBACK_CODES.some((code) => isPkcs11Error(err, code))) return null;+ if (isPkcs11Error(err, Pkcs11ErrorCode.BadRequest)) throw keyRejectedError();+ throw err;+ });+ if (hsmPublicKey && !hsmPublicKey.equals(publicKey)) {+ throw keyMismatchError();+ }++ const challenge = crypto.randomBytes(32);+ const signed = await deps.hsmConnectorService+ .signWithKeyId({+ connectorId: input.hsmConnectorId,+ projectId: input.projectId,+ keyLabel: input.hsmKeyLabel,+ keyId: input.hsmKeyId,+ publicKeySpki: Buffer.from(input.certificate.publicKey.rawData),+ mechanism: isEcdsa ? "CKM_ECDSA_SHA256" : "CKM_SHA256_RSA_PKCS",+ data: challenge,+ isDigest: false+ })+ .catch((err: unknown) => {+ if (isPkcs11Error(err, Pkcs11ErrorCode.KeyTypeMismatch)) {+ throw keyMismatchError();+ }+ if (isPkcs11Error(err, Pkcs11ErrorCode.BadRequest)) {+ throw keyRejectedError();+ }+ throw err;+ });++ const isMatch = crypto.nativeCrypto.verify(+ "sha256",+ challenge,+ isEcdsa ? { key: publicKey, dsaEncoding: "ieee-p1363" } : publicKey,+ signed.signature+ );+ if (!isMatch) {+ throw keyMismatchError();+ }+ return { hsmKeyId: signed.keyId };};diff --git a/backend/src/services/signer/signer-issuance-job-dal.ts b/backend/src/services/signer/signer-issuance-job-dal.tsindex 0d2c3849c6..7a09abcc5f 100644--- a/backend/src/services/signer/signer-issuance-job-dal.ts+++ b/backend/src/services/signer/signer-issuance-job-dal.ts@@ -39,6 +39,27 @@ export const signerIssuanceJobDALFactory = (db: TDbClient) => {}};+ const completeIfPending = async (+ jobId: string,+ certificateId: string,+ tx?: Knex+ ): Promise<TPkiSignerCertificateIssuanceJobs | null> => {+ try {+ const [row] = await (tx || db)(TableName.PkiSignerCertificateIssuanceJobs)+ .where({ id: jobId, status: SignerIssuanceJobStatus.Pending })+ .update({+ status: SignerIssuanceJobStatus.Completed,+ certificateId,+ failureReason: null,+ updatedAt: new Date()+ } as Record<string, unknown>)+ .returning("*");+ return row ?? null;+ } catch (error) {+ throw new DatabaseError({ error, name: "CompleteSignerIssuanceJob" });+ }+ };+const claimForAttempt = async (jobId: string,expectedAttempts: number,@@ -76,5 +97,5 @@ export const signerIssuanceJobDALFactory = (db: TDbClient) => {}};- return { ...orm, findDuePending, cancelOpenForSigner, claimForAttempt, findLatestForSigner };+ return { ...orm, findDuePending, cancelOpenForSigner, completeIfPending, claimForAttempt, findLatestForSigner };};diff --git a/backend/src/services/signer/signer-issuance-service.ts b/backend/src/services/signer/signer-issuance-service.tsindex 6110cb629d..04e92b3a73 100644--- a/backend/src/services/signer/signer-issuance-service.ts+++ b/backend/src/services/signer/signer-issuance-service.ts@@ -1,11 +1,12 @@/* eslint-disable no-await-in-loop, @typescript-eslint/no-use-before-define, @typescript-eslint/no-unsafe-argument */import * as x509 from "@peculiar/x509";+import { Knex } from "knex";import { TPkiSignerCertificateIssuanceJobs } from "@app/db/schemas";import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";import { crypto } from "@app/lib/crypto/cryptography";import { buildCsrWithExternalSigner } from "@app/lib/csr/build-csr-with-external-signer";-import { BadRequestError } from "@app/lib/errors";+import { BadRequestError, ConflictError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";@@ -79,7 +80,7 @@ export type TSignerIssuanceServiceFactory = ReturnType<typeof signerIssuanceServtype TSignerIssuanceServiceDeps = {signerIssuanceJobDAL: TSignerIssuanceJobDALFactory;- signerDAL: Pick<TSignerDALFactory, "updateById" | "transaction" | "findById">;+ signerDAL: Pick<TSignerDALFactory, "updateById" | "transaction" | "findById" | "findOne">;certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create" | "updateById">;@@ -91,7 +92,7 @@ type TSignerIssuanceServiceDeps = {>;cronJob: TCronJobFactory;hsmConnectorService: Pick<THsmConnectorServiceFactory, "generateKeyPair" | "sign" | "assertAttachPermission">;- certificateDAL: Pick<TCertificateDALFactory, "updateById" | "findById">;+ certificateDAL: Pick<TCertificateDALFactory, "updateById" | "findById" | "findByIdForUpdate">;};type TRequestIssuanceInput = {@@ -105,6 +106,7 @@ type TRequestIssuanceInput = {hsmConnectorId: string;hsmKeyAlgorithm: HsmKeyAlgorithm;hsmKeyLabel?: string;+ hsmKeyId?: string | null;hsmPublicKeySpki?: Buffer;actor?: Pick<THsmConnectorServiceActor, "type" | "id" | "authMethod" | "orgId">;};@@ -212,9 +214,11 @@ export const signerIssuanceServiceFactory = ({}const reuseExistingKey = Boolean(input.hsm.hsmKeyLabel && input.hsm.hsmPublicKeySpki);let keyLabel: string;+ let keyId: string | null;let publicKeySpkiDer: Buffer;if (reuseExistingKey) {keyLabel = input.hsm.hsmKeyLabel as string;+ keyId = input.hsm.hsmKeyId ?? null;publicKeySpkiDer = Buffer.from(input.hsm.hsmPublicKeySpki as Buffer);} else {const keyLabelSuffix = `signer-${crypto.nativeCrypto.randomUUID()}`;@@ -225,6 +229,7 @@ export const signerIssuanceServiceFactory = ({keyAlgorithm: input.hsm.hsmKeyAlgorithm});keyLabel = generated.keyLabel;+ keyId = generated.keyId;publicKeySpkiDer = generated.publicKeySpkiDer;}const built = await buildCsrWithExternalSigner({@@ -236,6 +241,8 @@ export const signerIssuanceServiceFactory = ({connectorId: input.hsm!.hsmConnectorId,projectId: input.projectId,keyLabel,+ keyId,+ publicKeySpki: publicKeySpkiDer,mechanism: mech,data: tbs,isDigest@@ -260,6 +267,7 @@ export const signerIssuanceServiceFactory = ({keySource: CertKeySource.Hsm,hsmConnectorId: input.hsm!.hsmConnectorId,hsmKeyLabel: keyLabel,+ hsmKeyId: keyId,hsmPublicKeySpki: publicKeySpkiDer,externalOrderRef: digicertExternalOrderRef,nextPollAt: new Date()@@ -335,7 +343,7 @@ export const signerIssuanceServiceFactory = ({const ageMs = now.getTime() - new Date(snapshot.createdAt).getTime();if (ageMs > windowMs) {const hours = Math.round(windowMs / (60 * 60 * 1000));- await markJobFailedIfStillPending(+ await markJobFailed(snapshot,`Signer issuance was pending for more than ${hours} hours. The upstream Certificate Authority never finished issuing the certificate; abandoning.`);@@ -423,20 +431,6 @@ export const signerIssuanceServiceFactory = ({};const markJobFailed = async (job: TPkiSignerCertificateIssuanceJobs, reason: string) => {- await signerIssuanceJobDAL.updateById(job.id, {- status: SignerIssuanceJobStatus.Failed,- failureReason: reason.slice(0, 1000)- });- await signerDAL.updateById(job.signerId, {- status: SignerStatus.Failed,- certificateFailureReason: reason.slice(0, 1000)- });- logger.info(- `signer issuance: job marked Failed [jobId=${job.id}] [signerId=${job.signerId}] [reason=${reason.slice(0, 200)}]`- );- };-- const markJobFailedIfStillPending = async (job: TPkiSignerCertificateIssuanceJobs, reason: string) => {const trimmed = reason.slice(0, 1000);const rows = await signerIssuanceJobDAL.update({ id: job.id, status: SignerIssuanceJobStatus.Pending },@@ -469,8 +463,21 @@ export const signerIssuanceServiceFactory = ({// The signer may carry a placeholder CN (reissuing into a DigiCert order whose subject DigiCert// owns), so the issued cert is the source of truth for the common name.const issuedCert = await certificateDAL.findById(certificateId);+ let isSuperseded = false;try {await signerDAL.transaction(async (tx) => {+ const completedJob = await signerIssuanceJobDAL.completeIfPending(job.id, certificateId, tx);+ if (!completedJob) {+ isSuperseded = true;+ return;+ }+ await certificateDAL.findByIdForUpdate(certificateId, tx);+ const signerUsingCertificate = await signerDAL.findOne({ certificateId }, tx);+ if (signerUsingCertificate && signerUsingCertificate.id !== job.signerId) {+ throw new ConflictError({+ message: `The issued certificate is already used by signer '${signerUsingCertificate.name}'.`+ });+ }if (isHsmJob) {const certAlg = job.keyAlgorithm as CertKeyAlgorithm;await certificateDAL.updateById(@@ -479,6 +486,7 @@ export const signerIssuanceServiceFactory = ({keySource: CertKeySource.Hsm,hsmConnectorId: job.hsmConnectorId,hsmKeyLabel: job.hsmKeyLabel,+ hsmKeyId: job.hsmKeyId ?? null,hsmPublicKeySpki: job.hsmPublicKeySpki ?? null,keyAlgorithm: certAlg},@@ -495,15 +503,6 @@ export const signerIssuanceServiceFactory = ({},tx);- await signerIssuanceJobDAL.updateById(- job.id,- {- status: SignerIssuanceJobStatus.Completed,- certificateId,- failureReason: null- },- tx- );});} catch (txErr) {const reason = formatSignerIssuanceErrorReason(@@ -515,6 +514,12 @@ export const signerIssuanceServiceFactory = ({await markJobFailed(job, reason);return;}+ if (isSuperseded) {+ logger.info(+ `signer issuance: job was superseded before completion, certificate not attached [jobId=${job.id}] [signerId=${job.signerId}] [certificateId=${certificateId}]`+ );+ return;+ }logger.info(`signer issuance: signer attached [jobId=${job.id}] [signerId=${job.signerId}] [certificateId=${certificateId}]`);@@ -824,6 +829,7 @@ export const signerIssuanceServiceFactory = ({keyAlgorithm: job.keyAlgorithm as CertKeyAlgorithm,hsmConnectorId: job.hsmConnectorId ?? null,hsmKeyLabel: job.hsmKeyLabel ?? null,+ hsmKeyId: job.hsmKeyId ?? null,hsmPublicKeySpki: job.hsmPublicKeySpki ?? null,externalOrder:digicert?.orderId != null@@ -832,6 +838,9 @@ export const signerIssuanceServiceFactory = ({};};+ const cancelOpenJobs = async (signerId: string, reason: string, tx?: Knex) =>+ signerIssuanceJobDAL.cancelOpenForSigner(signerId, reason, tx);+const runPendingJobNow = async (signerId: string): Promise<void> => {const job = await signerIssuanceJobDAL.transaction((tx) => signerIssuanceJobDAL.findLatestForSigner(signerId, tx));if (!job || job.status !== SignerIssuanceJobStatus.Pending) return;@@ -842,6 +851,7 @@ export const signerIssuanceServiceFactory = ({requestIssuance,processJob,runPendingJobNow,+ cancelOpenJobs,getLatestIssuanceKeyConfig,start};diff --git a/backend/src/services/signer/signer-service.ts b/backend/src/services/signer/signer-service.tsindex 8af7f9da54..5d830e67ea 100644--- a/backend/src/services/signer/signer-service.ts+++ b/backend/src/services/signer/signer-service.ts@@ -2,6 +2,7 @@ import { ForbiddenError } from "@casl/ability";import { packRules } from "@casl/ability/extra";import * as x509 from "@peculiar/x509";import { KeyObject } from "crypto";+import { Knex } from "knex";import {AccessScope,@@ -30,7 +31,7 @@ import {Pkcs11Mechanism,wrapRsaPkcs1DigestInfo} from "@app/lib/csr/pkcs11-algorithm-map";-import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { BadRequestError, ConflictError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";@@ -63,12 +64,13 @@ import {import { ActorType } from "../auth/auth-type";import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";import { TCertificateDALFactory } from "../certificate/certificate-dal";-import { getCertificateCredentials } from "../certificate/certificate-fns";+import { extractCertificateAlgorithms, getCertificateCredentials } from "../certificate/certificate-fns";import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-dal";import { CertExtendedKeyUsage, CertKeyAlgorithm, CertStatus, CrlReason } from "../certificate/certificate-types";import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";import { CaStatus, CaType } from "../certificate-authority/certificate-authority-enums";import { TDigiCertCertificateAuthorityFns } from "../certificate-authority/digicert/digicert-certificate-authority-fns";+import { MAX_CS_VALIDITY_DAYS } from "../certificate-authority/digicert/digicert-code-signing-fns";import { TInternalCertificateAuthorityServiceFactory } from "../certificate-authority/internal/internal-certificate-authority-service";import { TKmsServiceFactory } from "../kms/kms-service";import { TMembershipDALFactory } from "../membership/membership-dal";@@ -86,6 +88,7 @@ import {} from "./signer-enums";import { formatSignerIssuanceErrorReason } from "./signer-issuance-errors";import {+ assertHsmKeyMatchesCertificate,issueHsmBackedSignerCertificate,issueSignerCertificate,mapCertKeyAlgorithmToHsmKeyAlgorithm,@@ -106,7 +109,9 @@ import {TListSigningOperationsDTO,TReissueCertificateDTO,TSignDataDTO,+ TSignerCertificateInput,TSignerExternalCaConfig,+ TSignerExternalConfigurationInput,TUpdateSignerDTO} from "./signer-types";import { TSigningOperationDALFactory } from "./signing-operation-dal";@@ -114,6 +119,15 @@ import { TSigningOperationDALFactory } from "./signing-operation-dal";const MAX_DATA_BYTES = 128;const DEFAULT_CERTIFICATE_TTL_DAYS = 365;+const IMPORTABLE_HSM_KEY_ALGORITHMS: readonly string[] = [+ CertKeyAlgorithm.RSA_3072,+ CertKeyAlgorithm.RSA_4096,+ CertKeyAlgorithm.ECDSA_P256,+ CertKeyAlgorithm.ECDSA_P384+];++const IMPORTED_CERTIFICATE_FALLBACK_COMMON_NAME = "Code signing certificate";+const CODE_SIGNING_SUPPORTED_EXTERNAL_CA_TYPES = new Set<CaType>([CaType.AWS_PCA,CaType.AZURE_AD_CS,@@ -150,18 +164,24 @@ type TSignerServiceFactoryDep = {signingOperationDAL: TSigningOperationDALFactory;hsmConnectorService: Pick<THsmConnectorServiceFactory,- "sign" | "generateKeyPair" | "getPublicKey" | "assertAttachPermission"+ "sign" | "signWithKeyId" | "generateKeyPair" | "getPublicKey" | "assertAttachPermission">;- certificateDAL: Pick<TCertificateDALFactory, "findById" | "updateById">;+ certificateDAL: Pick<TCertificateDALFactory, "findById" | "updateById" | "findByIdForUpdate">;certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create">;certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;signerIssuanceService: Pick<TSignerIssuanceServiceFactory,- "requestIssuance" | "getLatestIssuanceKeyConfig" | "runPendingJobNow"+ "requestIssuance" | "getLatestIssuanceKeyConfig" | "runPendingJobNow" | "cancelOpenJobs">;internalCertificateAuthorityService: Pick<TInternalCertificateAuthorityServiceFactory, "signCertFromCa">;- digicertFns: Pick<TDigiCertCertificateAuthorityFns, "revokeCertificate" | "assertCodeSigningOrderReusable">;+ digicertFns: Pick<+ TDigiCertCertificateAuthorityFns,+ | "revokeCertificate"+ | "assertCodeSigningOrderReusable"+ | "fetchIssuedCodeSigningCertificate"+ | "downloadCodeSigningCertificate"+ >;projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "encryptWithKmsKey" | "generateKmsKey">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;@@ -268,6 +288,17 @@ type TResolvedInfisicalReissue = {};type TResolvedReissueTarget = TResolvedHsmReissue | TResolvedInfisicalReissue;+export const assertExternalConfigurationMatchesCaType = (+ externalConfiguration: TSignerExternalConfigurationInput | undefined,+ caType: CaType | null+) => {+ if (externalConfiguration?.caType && externalConfiguration.caType !== caType) {+ throw new BadRequestError({+ message: `externalConfiguration.caType '${externalConfiguration.caType}' does not match the type of the selected certificate authority ('${caType ?? "none"}').`+ });+ }+};+export const resolveReissueTarget = ({dto,signer,@@ -406,6 +437,93 @@ export const signerServiceFactory = ({return certificateId;};+ const $parseDigiCertOrderId = (+ value: string | undefined,+ caType: CaType | null,+ field: "reissueFromExternalOrderId" | "importFromExternalOrderId"+ ): number | undefined => {+ if (!value) return undefined;+ if (caType !== CaType.DIGICERT) {+ throw new BadRequestError({+ message: `${field === "reissueFromExternalOrderId" ? "Reissuing from an existing order" : "Using the certificate from an existing order"} is only supported for DigiCert code signing certificate authorities.`+ });+ }+ const orderId = Number(value);+ if (!Number.isInteger(orderId) || orderId <= 0) {+ throw new BadRequestError({ message: `${field} must be a valid DigiCert order id.` });+ }+ return orderId;+ };++ const $importExistingDigiCertCertificate = async (input: {+ caId: string;+ projectId: string;+ orderId: number;+ certificate?: TSignerCertificateInput;+ actor: Parameters<typeof hsmConnectorService.assertAttachPermission>[0];+ signerId?: string;+ }) => {+ const { caId, projectId, orderId } = input;+ const hsmConnectorId = input.certificate?.hsmConnectorId;+ const hsmKeyLabel = input.certificate?.hsmKeyLabel;+ const requestedHsmKeyId = input.certificate?.hsmKeyId;+ if (input.certificate?.keySource !== CertKeySource.Hsm || !hsmConnectorId || !hsmKeyLabel) {+ throw new BadRequestError({+ message:+ "Using an existing DigiCert certificate requires an HSM Connector and the label of the certificate's private key on that HSM."+ });+ }+ await hsmConnectorService.assertAttachPermission(input.actor, hsmConnectorId, projectId);++ const { pemBundle, certificate } = await digicertFns.fetchIssuedCodeSigningCertificate(caId, orderId);+ const { keyAlgorithm } = extractCertificateAlgorithms(certificate);+ if (!keyAlgorithm || !IMPORTABLE_HSM_KEY_ALGORITHMS.includes(keyAlgorithm)) {+ throw new BadRequestError({+ message: `The certificate in DigiCert order ${orderId} uses an unsupported key type (${keyAlgorithm ?? "unknown"}). Supported key types are RSA-3072, RSA-4096, ECDSA P-256, and ECDSA P-384.`+ });+ }++ const { hsmKeyId } = await assertHsmKeyMatchesCertificate(+ { hsmConnectorService },+ { hsmConnectorId, projectId, hsmKeyLabel, hsmKeyId: requestedHsmKeyId, certificate }+ );++ const { certificateId } = await digicertFns.downloadCodeSigningCertificate({ caId, orderId, pemBundle });++ const validityDays = Math.round(+ (certificate.notAfter.getTime() - certificate.notBefore.getTime()) / (24 * 60 * 60 * 1000)+ );+ return {+ orderId,+ certificateId,+ hsm: {+ keySource: CertKeySource.Hsm,+ hsmConnectorId,+ hsmKeyLabel,+ hsmKeyId: hsmKeyId ?? requestedHsmKeyId ?? null,+ hsmPublicKeySpki: Buffer.from(certificate.publicKey.rawData)+ },+ commonName: certificate.subjectName.getField("CN")[0] || IMPORTED_CERTIFICATE_FALLBACK_COMMON_NAME,+ certificateTtlDays: Math.min(Math.max(validityDays, 1), MAX_CS_VALIDITY_DAYS),+ keyAlgorithm: keyAlgorithm as CertKeyAlgorithm+ };+ };++ const $attachImportedCertificate = async (+ imported: Awaited<ReturnType<typeof $importExistingDigiCertCertificate>>,+ signerId: string | undefined,+ tx: Knex+ ) => {+ await certificateDAL.findByIdForUpdate(imported.certificateId, tx);+ const signerUsingCertificate = await signerDAL.findOne({ certificateId: imported.certificateId }, tx);+ if (signerUsingCertificate && signerUsingCertificate.id !== signerId) {+ throw new ConflictError({+ message: `The certificate in DigiCert order ${imported.orderId} is already used by signer '${signerUsingCertificate.name}'.`+ });+ }+ await certificateDAL.updateById(imported.certificateId, imported.hsm, tx);+ };+const create = async (dto: TCreateSignerDTO) => {const { permission } = await permissionService.getProjectPermission({actor: dto.actor,@@ -473,7 +591,7 @@ export const signerServiceFactory = ({let resolvedCaId: string | null = null;let resolvedCaType: CaType | null = null;if (usingCa) {- if (!dto.commonName) {+ if (!dto.commonName && !dto.externalConfiguration?.importFromExternalOrderId) {throw new BadRequestError({ message: "commonName is required when issuing a certificate from a CA." });}const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(dto.caId as string);@@ -488,30 +606,28 @@ export const signerServiceFactory = ({}if (resolvedCaType) assertCaTypeSupportsCodeSigning(resolvedCaType);+ assertExternalConfigurationMatchesCaType(dto.externalConfiguration, resolvedCaType);let createDigicertLifecycle: { mode: "reissue"; previousOrderId: number } | undefined;const createExternalConfig = dto.externalConfiguration;- const reissueFromExternalOrderId =- createExternalConfig?.caType === CaType.DIGICERT ? createExternalConfig.reissueFromExternalOrderId : undefined;- if (reissueFromExternalOrderId) {- if (resolvedCaType !== CaType.DIGICERT) {- throw new BadRequestError({- message:- "Reissuing from an existing order is only supported for DigiCert code signing certificate authorities."- });- }- const previousOrderId = Number(reissueFromExternalOrderId);- if (!Number.isInteger(previousOrderId) || previousOrderId <= 0) {- throw new BadRequestError({ message: "reissueFromExternalOrderId must be a valid DigiCert order id." });- }- await digicertFns.assertCodeSigningOrderReusable(resolvedCaId as string, previousOrderId);- createDigicertLifecycle = { mode: "reissue", previousOrderId };+ const reissueOrderId = $parseDigiCertOrderId(+ createExternalConfig?.reissueFromExternalOrderId,+ resolvedCaType,+ "reissueFromExternalOrderId"+ );+ const importOrderId = $parseDigiCertOrderId(+ createExternalConfig?.importFromExternalOrderId,+ resolvedCaType,+ "importFromExternalOrderId"+ );+ if (reissueOrderId) {+ await digicertFns.assertCodeSigningOrderReusable(resolvedCaId as string, reissueOrderId);+ createDigicertLifecycle = { mode: "reissue", previousOrderId: reissueOrderId };}const isExternalCa = resolvedCaType !== null && resolvedCaType !== CaType.INTERNAL;- const adcsTemplate =- createExternalConfig?.caType === CaType.ADCS ? createExternalConfig.template?.trim() || undefined : undefined;+ const adcsTemplate = createExternalConfig?.template?.trim() || undefined;if (adcsTemplate && resolvedCaType !== CaType.ADCS) {throw new BadRequestError({message:@@ -537,7 +653,19 @@ export const signerServiceFactory = ({});}- const keyAlgorithm: CertKeyAlgorithm = (dto.keyAlgorithm as CertKeyAlgorithm) ?? CertKeyAlgorithm.RSA_2048;+ const importedCertificate =+ importOrderId && resolvedCaId+ ? await $importExistingDigiCertCertificate({+ caId: resolvedCaId,+ projectId: dto.projectId,+ orderId: importOrderId,+ certificate: dto.certificate,+ actor: { type: dto.actor, id: dto.actorId, authMethod: dto.actorAuthMethod, orgId: dto.actorOrgId }+ })+ : null;++ const keyAlgorithm: CertKeyAlgorithm =+ importedCertificate?.keyAlgorithm ?? (dto.keyAlgorithm as CertKeyAlgorithm) ?? CertKeyAlgorithm.RSA_2048;let issuedCertificateId: string | null = null;if (usingCa && resolvedCaId && !isExternalCa) {@@ -552,11 +680,17 @@ export const signerServiceFactory = ({});}- const finalCertificateId = usingExistingCert ? (dto.certificateId as string) : issuedCertificateId;- const initialStatus: SignerStatus = isExternalCa ? SignerStatus.Pending : SignerStatus.Active;+ const finalCertificateId = usingExistingCert+ ? (dto.certificateId as string)+ : (importedCertificate?.certificateId ?? issuedCertificateId);+ const initialStatus: SignerStatus =+ isExternalCa && !importedCertificate ? SignerStatus.Pending : SignerStatus.Active;try {const result = await signerDAL.transaction(async (tx) => {+ if (importedCertificate) {+ await $attachImportedCertificate(importedCertificate, undefined, tx);+ }const project = await projectDAL.findOne({ id: dto.projectId }, tx);if (!project) {throw new NotFoundError({ message: "Certificate Manager has not been set up for this organization." });@@ -582,8 +716,10 @@ export const signerServiceFactory = ({description: dto.description,certificateId: finalCertificateId,caId: resolvedCaId,- commonName: usingCa ? dto.commonName : null,- certificateTtlDays: usingCa ? (dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS) : null,+ commonName: usingCa ? (importedCertificate?.commonName ?? dto.commonName) : null,+ certificateTtlDays: usingCa+ ? (importedCertificate?.certificateTtlDays ?? dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS)+ : null,certificateRenewBeforeDays: usingCa ? (dto.certificateRenewBeforeDays ?? null) : null,keyAlgorithm,status: initialStatus,@@ -790,7 +926,7 @@ export const signerServiceFactory = ({return { ...signer, approvalPolicyId: policy.id };});- if (usingCa && resolvedCaId && isExternalCa && resolvedCaType) {+ if (usingCa && resolvedCaId && isExternalCa && resolvedCaType && !importedCertificate) {try {const certificateInput = dto.certificate;await signerIssuanceService.requestIssuance({@@ -1148,6 +1284,7 @@ export const signerServiceFactory = ({const $reissueExternalSigner = async (ctx: TReissueExecutionContext) => {const { dto, signer, reissueCaType, target, currentCert, recoveredKeyConfig, commonName, certificateTtlDays } = ctx;+ const reusedHsmKeyRow = currentCert?.hsmKeyLabel ? currentCert : recoveredKeyConfig;const reissueHsm = target.isHsm? {hsmConnectorId: target.hsmConnectorId,@@ -1155,6 +1292,7 @@ export const signerServiceFactory = ({hsmKeyLabel: target.switchingKeySource? undefined: (currentCert?.hsmKeyLabel ?? recoveredKeyConfig?.hsmKeyLabel ?? undefined),+ hsmKeyId: target.switchingKeySource ? undefined : reusedHsmKeyRow?.hsmKeyId,hsmPublicKeySpki: target.switchingKeySource? undefined: (currentCert?.hsmPublicKeySpki ?? recoveredKeyConfig?.hsmPublicKeySpki ?? undefined),@@ -1217,6 +1355,7 @@ export const signerServiceFactory = ({certificateTtlDays,hsmConnectorId: target.hsmConnectorId,hsmKeyLabel: currentCert.hsmKeyLabel,+ hsmKeyId: currentCert.hsmKeyId,expectedPublicKeySpkiDer: currentCert.hsmPublicKeySpki ?? undefined,hsmKeyAlgorithm: target.hsmKeyAlgorithm});@@ -1278,28 +1417,58 @@ export const signerServiceFactory = ({const reissueCaType: CaType = (ca.externalCa?.type as CaType | undefined) ?? CaType.INTERNAL;assertCaTypeSupportsCodeSigning(reissueCaType);+ assertExternalConfigurationMatchesCaType(dto.externalConfiguration, reissueCaType);const reissueIsExternal = reissueCaType !== CaType.INTERNAL;const reissueExternalConfig = dto.externalConfiguration;- const reissueFromExternalOrderId =- reissueExternalConfig?.caType === CaType.DIGICERT ? reissueExternalConfig.reissueFromExternalOrderId : undefined;- let explicitReissueOrderId: number | undefined;- if (reissueFromExternalOrderId) {- if (reissueCaType !== CaType.DIGICERT) {- throw new BadRequestError({- message:- "Reissuing from an existing order is only supported for DigiCert code signing certificate authorities."- });- }- explicitReissueOrderId = Number(reissueFromExternalOrderId);- if (!Number.isInteger(explicitReissueOrderId) || explicitReissueOrderId <= 0) {- throw new BadRequestError({ message: "reissueFromExternalOrderId must be a valid DigiCert order id." });- }+ const explicitReissueOrderId = $parseDigiCertOrderId(+ reissueExternalConfig?.reissueFromExternalOrderId,+ reissueCaType,+ "reissueFromExternalOrderId"+ );+ const importOrderId = $parseDigiCertOrderId(+ reissueExternalConfig?.importFromExternalOrderId,+ reissueCaType,+ "importFromExternalOrderId"+ );+ if (explicitReissueOrderId) {await digicertFns.assertCodeSigningOrderReusable(ca.id, explicitReissueOrderId);}- const providedAdcsTemplate =- reissueExternalConfig?.caType === CaType.ADCS ? reissueExternalConfig.template?.trim() || undefined : undefined;+ if (importOrderId) {+ const imported = await $importExistingDigiCertCertificate({+ caId: ca.id,+ projectId: signer.projectId,+ orderId: importOrderId,+ certificate: dto.certificate,+ actor: { type: dto.actor, id: dto.actorId, authMethod: dto.actorAuthMethod, orgId: dto.actorOrgId },+ signerId: signer.id+ });+ return signerDAL.transaction(async (tx) => {+ await signerIssuanceService.cancelOpenJobs(+ signer.id,+ "Superseded by an existing DigiCert certificate attached to the signer.",+ tx+ );+ await $attachImportedCertificate(imported, signer.id, tx);+ return signerDAL.updateById(+ signer.id,+ {+ caId: ca.id,+ commonName: imported.commonName,+ certificateTtlDays: imported.certificateTtlDays,+ keyAlgorithm: imported.keyAlgorithm,+ externalCaConfig: null,+ certificateId: imported.certificateId,+ status: SignerStatus.Active,+ certificateFailureReason: null+ },+ tx+ );+ });+ }++ const providedAdcsTemplate = reissueExternalConfig?.template?.trim() || undefined;if (providedAdcsTemplate && reissueCaType !== CaType.ADCS) {throw new BadRequestError({message:@@ -1754,16 +1923,17 @@ export const signerServiceFactory = ({mech.mechanism === Pkcs11Mechanism.RsaPkcs? wrapRsaPkcs1DigestInfo(dto.signingAlgorithm, dataBuffer): dataBuffer;- let raw = await hsmConnectorService.sign({+ const signature = await hsmConnectorService.sign({connectorId: certificate.hsmConnectorId as string,projectId,keyLabel: certificate.hsmKeyLabel as string,+ keyId: certificate.hsmKeyId,+ publicKeySpki: certificate.hsmPublicKeySpki ?? null,mechanism: mech.mechanism,data: hsmData,isDigest: dto.isDigest});- if (mech.isEcdsa) raw = ecdsaRawRsToDer(raw);- signatureBuffer = raw;+ signatureBuffer = mech.isEcdsa ? ecdsaRawRsToDer(signature) : signature;} else {const privateKeyPem = certPrivateKey as Buffer;const svc = signingService(keyAlgorithm);@@ -2052,6 +2222,7 @@ export const signerServiceFactory = ({hsmConnectorId: autoRenewCert.hsmConnectorId,hsmKeyAlgorithm: mapCertKeyAlgorithmToHsmKeyAlgorithm(autoRenewCert.keyAlgorithm),hsmKeyLabel: autoRenewCert.hsmKeyLabel ?? undefined,+ hsmKeyId: autoRenewCert.hsmKeyId,hsmPublicKeySpki: autoRenewCert.hsmPublicKeySpki ?? undefined}: undefined;@@ -2101,6 +2272,7 @@ export const signerServiceFactory = ({certificateTtlDays: ttlDays,hsmConnectorId: existingCert.hsmConnectorId,hsmKeyLabel: existingCert.hsmKeyLabel,+ hsmKeyId: existingCert.hsmKeyId,expectedPublicKeySpkiDer: existingCert.hsmPublicKeySpki ?? undefined,hsmKeyAlgorithm: mapCertKeyAlgorithmToHsmKeyAlgorithm(existingCert.keyAlgorithm)});diff --git a/backend/src/services/signer/signer-types.ts b/backend/src/services/signer/signer-types.tsindex 2ffdb442f9..f636963c18 100644--- a/backend/src/services/signer/signer-types.ts+++ b/backend/src/services/signer/signer-types.ts@@ -28,17 +28,16 @@ export type TCreateSignerApprovalPolicyInput = {export type TSignerCertificateInput = {keySource?: CertKeySource;hsmConnectorId?: string;+ hsmKeyLabel?: string;+ hsmKeyId?: string;};-export type TSignerExternalConfigurationInput =- | {- caType: CaType.DIGICERT;- reissueFromExternalOrderId?: string;- }- | {- caType: CaType.ADCS;- template?: string;- };+export type TSignerExternalConfigurationInput = {+ caType?: CaType.DIGICERT | CaType.ADCS;+ reissueFromExternalOrderId?: string;+ importFromExternalOrderId?: string;+ template?: string;+};const RE_NO_NEWLINES = new RE2("^[^\\r\\n]+$");diff --git a/docs/documentation/platform/pki/code-signing/signers.mdx b/docs/documentation/platform/pki/code-signing/signers.mdxindex 6a3fd3bc0d..4ef8124075 100644--- a/docs/documentation/platform/pki/code-signing/signers.mdx+++ b/docs/documentation/platform/pki/code-signing/signers.mdx@@ -145,7 +145,7 @@ Open the Signer and choose **Options → Edit settings**. The edit sheet walks yChange which CA issues the certificate and its identity.- **Certificate Authority**: swap to another CA. Saving with a different CA reissues the certificate immediately from the new CA.- - **Reuse an existing order**: offered by some CAs (DigiCert code signing). Point the Signer at an existing order to reuse that order slot instead of placing a new one. Common Name and Validity are inherited from the order.+ - **Existing order**: offered by some CAs (DigiCert code signing). Select an existing order, then choose whether to [use its existing key or reissue the certificate](/documentation/platform/pki/guides/code-signing/digicert-code-signing#use-an-existing-order). Common Name and Validity come from the order.- **Common Name** and **Validity (days)**: edit them to change the identity on the certificate. Saving reissues the certificate with the new values, and the signer switches to the new certificate.- **Renew before (days)**: edit any time, 1 to 30, must be less than Validity.@@ -160,7 +160,7 @@ Open the Signer and choose **Options → Edit settings**. The edit sheet walks y- **Key algorithm**: pick a different algorithm. Changing it generates a new key and reissues the certificate.<Note>- Renewals always issue a new certificate from the same CA with a fresh key pair. Old artifacts remain valid under the old certificate. New sign operations use the new one.+ Renewals issue a new certificate from the same CA. HSM-backed signers keep the same HSM key, and other signers get a new key pair. Old artifacts remain valid under the old certificate. New sign operations use the new one.</Note>Press **Save** to apply the changes.diff --git a/docs/documentation/platform/pki/guides/code-signing/digicert-code-signing.mdx b/docs/documentation/platform/pki/guides/code-signing/digicert-code-signing.mdxindex dbdfccec1d..fec3034ac3 100644--- a/docs/documentation/platform/pki/guides/code-signing/digicert-code-signing.mdx+++ b/docs/documentation/platform/pki/guides/code-signing/digicert-code-signing.mdx@@ -27,18 +27,69 @@ DigiCert's code-signing workflow includes an out-of-band approval step that theA **Pending** signer is checked on a schedule. To poll DigiCert immediately, use **Check issuance now** from the signer's actions menu. Hovering the **Pending** status on the signer's detail page shows the DigiCert **order number** so you can open that order in DigiCert to approve it or resend the approval email.-### Reuse an existing order+### Use an existing order-Each DigiCert order consumes a subscription slot on your CertCentral account. If a code-signing order already exists in this CA's organization, a Signer can issue into that order instead of spending another slot. This includes orders placed directly in DigiCert, not just ones Infisical created.+Each DigiCert order consumes a subscription slot on your CertCentral account. If a code-signing order already exists in this CA's organization and product, a Signer can use that order instead of placing a new one. This works for orders placed directly in DigiCert too. The Common Name and Validity come from the order.-Reuse is scoped to the CA's configured organization and product, so only orders from that organization and product can be selected. The Common Name and Validity come from the chosen order rather than from the Signer.+When you pick an order, the **Use existing key** toggle decides what happens to its certificate:++- On: the Signer uses the order's issued certificate and its existing private key, and nothing is reissued+- Off: DigiCert reissues the certificate in the order and revokes the previous certificate++#### Use existing key++Use this option to bring certificates you already have into Infisical. The certificate stays valid wherever else it's in use.++The certificate and its key need to meet these requirements:++- The order's certificate is issued and hasn't expired+- The certificate's private key is in the slot of one of your [HSM Connectors](/documentation/platform/pki/settings/hsm-connectors)+- The key is RSA-3072, RSA-4096, ECDSA P-256, or ECDSA P-384++If the key doesn't match the certificate, the request fails and nothing changes.++<Tabs>+ <Tab title="Infisical UI">+ <Steps>+ <Step>+ In the Create Signer wizard's **Certificate** step, select the order in **Existing order**.+ </Step>+ <Step>+ In the **Signing Key** step, select the **HSM Connector**, turn on **Use existing key**, and enter the label of the certificate's private key in **Key label**. If more than one key in the slot has that label, select the key in **Key ID**.+ </Step>+ </Steps>++ To switch an existing signer to the certificate, follow the same steps in **Edit Signer**.+ </Tab>+ <Tab title="API">+ On [Create Signer](/api-reference/endpoints/code-signing/signers/create) or [Reissue](/api-reference/endpoints/code-signing/signers/reissue-certificate), set `externalConfiguration.importFromExternalOrderId` to the order ID and `certificate.hsmKeyLabel` to the key's label. If more than one private key in the slot has that label, also set `certificate.hsmKeyId` to the key's hex-encoded `CKA_ID`:++ ```json+ {+ "certificate": {+ "keySource": "hsm",+ "hsmConnectorId": "<hsm-connector-id>",+ "hsmKeyLabel": "<key-label>",+ "hsmKeyId": "<optional-hex-key-id>"+ },+ "externalConfiguration": {+ "importFromExternalOrderId": "<order-id>"+ }+ }+ ```+ </Tab>+</Tabs>++To renew the certificate with the same HSM key before it expires, set **Renew before**.++#### Reissue the certificate<Tabs><Tab title="Infisical UI">- In the Create Signer wizard's **Certificate** step, open **Reuse an existing order** and pick one of the listed issued orders. The Common Name and Validity fields are hidden because they're inherited from the order. Leave the field empty to place a new order.+ In the Create Signer wizard's **Certificate** step, select the order in **Existing order**. In the **Signing Key** step, leave **Use existing key** off. Leave **Existing order** empty to place a new order.</Tab><Tab title="API">- Set `externalConfiguration.reissueFromExternalOrderId` to the order id on [Create Signer](/api-reference/endpoints/code-signing/signers/create) or [Reissue](/api-reference/endpoints/code-signing/signers/reissue-certificate).+ Set `externalConfiguration.reissueFromExternalOrderId` to the order ID on [Create Signer](/api-reference/endpoints/code-signing/signers/create) or [Reissue](/api-reference/endpoints/code-signing/signers/reissue-certificate).</Tab></Tabs>@@ -50,9 +101,11 @@ Reuse is scoped to the CA's configured organization and product, so only ordersEditing a signer's Common Name, validity, key source, key algorithm, or CA triggers a fresh issuance. The signer returns to **Pending** until the new certificate issues, and DigiCert revokes the previous certificate within 72 hours.+If you switch the signer to an order's [issued certificate](#use-existing-key), nothing is issued and the signer uses that certificate right away.+## Reissue and renewal-- **Reissue** (changing the key source, key algorithm, or pointing at an existing order) hits DigiCert's reissue endpoint, which keeps the same order and its validity and replaces the certificate.+- **Reissue** (changing the key source, key algorithm, or reissuing into an existing order) hits DigiCert's reissue endpoint, which keeps the same order and its validity and replaces the certificate.- **Auto-renewal** (when **Renew before** is set) places a new order linked to the prior one so DigiCert tracks certificate history. If DigiCert reports the prior order as not eligible for renewal, Infisical falls back to a fresh, unlinked order.## Deleting a signerdiff --git a/frontend/src/hooks/api/hsmConnectors/queries.tsx b/frontend/src/hooks/api/hsmConnectors/queries.tsxindex f6554cf183..40738d5d89 100644--- a/frontend/src/hooks/api/hsmConnectors/queries.tsx+++ b/frontend/src/hooks/api/hsmConnectors/queries.tsx@@ -4,6 +4,7 @@ import { apiRequest } from "@app/config/request";import {THsmConnector,+ THsmConnectorKey,THsmConnectorLinkedCertificate,THsmConnectorLinkedCertificateAuthority} from "./types";@@ -12,6 +13,7 @@ export const hsmConnectorKeys = {all: ["hsm-connectors"] as const,list: () => [...hsmConnectorKeys.all, "list"] as const,byId: (id: string) => [...hsmConnectorKeys.all, "by-id", id] as const,+ keys: (id: string, label: string) => [...hsmConnectorKeys.all, "keys", id, label] as const,linkedResourcesAll: (id: string) => [...hsmConnectorKeys.all, "linked-resources", id] as const,linkedResources: (id: string, pagination: { offset: number; limit: number }) =>[...hsmConnectorKeys.linkedResourcesAll(id), pagination] as const@@ -84,3 +86,23 @@ export const useListHsmConnectorLinkedResources = (enabled: Boolean(connectorId) && (options?.enabled ?? true)});};++export const useListHsmConnectorKeys = (+ connectorId: string | null | undefined,+ label: string,+ options?: Omit<UseQueryOptions<THsmConnectorKey[]>, "queryKey" | "queryFn">+) => {+ return useQuery({+ retry: false,+ ...options,+ queryKey: hsmConnectorKeys.keys(connectorId ?? "", label),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ keys: THsmConnectorKey[] }>(+ `/api/v1/cert-manager/hsm-connectors/${connectorId}/keys`,+ { params: { label } }+ );+ return data.keys;+ },+ enabled: Boolean(connectorId) && Boolean(label) && (options?.enabled ?? true)+ });+};diff --git a/frontend/src/hooks/api/hsmConnectors/types.ts b/frontend/src/hooks/api/hsmConnectors/types.tsindex 26aec9d398..48a3a00352 100644--- a/frontend/src/hooks/api/hsmConnectors/types.ts+++ b/frontend/src/hooks/api/hsmConnectors/types.ts@@ -56,6 +56,11 @@ export type THsmConnectorTestResult = {members: THsmConnectorTestMemberResult[];};+export type THsmConnectorKey = {+ keyId: string;+ keyAlgorithm: string;+};+export type THsmConnectorLinkedCertificate = {id: string;commonName: string;diff --git a/frontend/src/hooks/api/signers/mutations.tsx b/frontend/src/hooks/api/signers/mutations.tsxindex 7d3f21b006..838ab946b2 100644--- a/frontend/src/hooks/api/signers/mutations.tsx+++ b/frontend/src/hooks/api/signers/mutations.tsx@@ -129,11 +129,16 @@ export const useReissueSignerCertificate = () => {);return data;},- onSuccess: (signer) => {+ onSuccess: (signer, { externalConfiguration }) => {queryClient.invalidateQueries({ queryKey: signerKeys.byId(signer.id) });queryClient.invalidateQueries({ queryKey: signerKeys.list(signer.projectId) });queryClient.invalidateQueries({ queryKey: signerKeys.certificate(signer.id) });- createNotification({ text: "Certificate re-issue scheduled", type: "success" });+ createNotification({+ text: externalConfiguration?.importFromExternalOrderId+ ? "Signer switched to the order's certificate"+ : "Certificate re-issue scheduled",+ type: "success"+ });}});};diff --git a/frontend/src/hooks/api/signers/types.ts b/frontend/src/hooks/api/signers/types.tsindex 5c011151c0..65ada8c741 100644--- a/frontend/src/hooks/api/signers/types.ts+++ b/frontend/src/hooks/api/signers/types.ts@@ -5,15 +5,11 @@ export type TGetUserSignerPermissionDTO = {signerId: string;};-export type TSignerExternalConfiguration =- | {- caType: CaType.DIGICERT;- reissueFromExternalOrderId?: string;- }- | {- caType: CaType.ADCS;- template?: string;- };+export type TSignerExternalConfiguration = {+ reissueFromExternalOrderId?: string;+ importFromExternalOrderId?: string;+ template?: string;+};export enum SignerStatus {Pending = "pending",@@ -357,6 +353,8 @@ export type TCreateSignerApprovalPolicyInput = {export type TSignerCertificateInput = {keySource?: CertKeySource;hsmConnectorId?: string;+ hsmKeyLabel?: string;+ hsmKeyId?: string;};export type TCreateSignerDTO = {@@ -393,10 +391,7 @@ export type TReissueSignerCertificateDTO = {commonName?: string;certificateTtlDays?: number;keyAlgorithm?: SignerKeyAlgorithm;- certificate?: {- keySource: CertKeySource;- hsmConnectorId?: string;- };+ certificate?: TSignerCertificateInput;externalConfiguration?: TSignerExternalConfiguration;};diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsxindex 4382a2696a..e22277c59c 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx@@ -1,29 +1,25 @@import { useEffect } from "react";import { Controller, useForm } from "react-hook-form";import { Link, useParams } from "@tanstack/react-router";-import { InfoIcon } from "lucide-react";import {+ Combobox,Field,FieldContent,FieldDescription,FieldError,FieldGroup,FieldLabel,- FilterableSelect,- Input,- Tooltip,- TooltipContent,- TooltipTrigger+ Input} from "@app/components/v3";import { ROUTE_PATHS } from "@app/const/routes";-import { useDigiCertConnectionListOrders } from "@app/hooks/api/appConnections/digicert";import { getCaIssuanceCapabilities } from "@app/hooks/api/ca";import { CaType } from "@app/hooks/api/ca/enums";import { AdcsTemplateField } from "../../../components/AdcsTemplateField";+import { DigiCertExistingOrderField } from "../../../components/DigiCertExistingOrderField";import { CertificateForm } from "./schemas";-import { CaGroup, CaOption } from "./types";+import { CaOption } from "./types";type CertificateStepProps = {form: ReturnType<typeof useForm<CertificateForm>>;@@ -40,43 +36,17 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateStconst digicertCfg = selectedCa?.digicert;const canReuseOrder = caps.supportsExistingOrderReuse && Boolean(digicertCfg);- const { data: codeSigningOrders = [], isLoading: isOrdersLoading } =- useDigiCertConnectionListOrders(- digicertCfg?.appConnectionId ?? "",- digicertCfg?.organizationId ?? 0,- digicertCfg?.productNameId ?? "",- { enabled: canReuseOrder }- );-- const orderOptions = codeSigningOrders.map((o) => ({- value: String(o.orderId),- label: `${o.commonName || o.organizationName || "Code signing certificate"} (#${o.orderId})`,- commonName: o.commonName- }));- type OrderOption = (typeof orderOptions)[number];-- const reissueOrderId = form.watch("reissueFromExternalOrderId");- const isReissue = Boolean(reissueOrderId);+ const externalOrderId = form.watch("externalOrderId");+ const hasExternalOrder = Boolean(externalOrderId);const isAdcs = selectedCa?.caType === CaType.ADCS;const adcsConnectionId = selectedCa?.adcs?.appConnectionId;useEffect(() => {- if (!canReuseOrder && reissueOrderId) {- form.setValue("reissueFromExternalOrderId", null);- }- }, [canReuseOrder, reissueOrderId, form]);-- useEffect(() => {- if (- canReuseOrder &&- !isOrdersLoading &&- reissueOrderId &&- !codeSigningOrders.some((order) => String(order.orderId) === reissueOrderId)- ) {- form.setValue("reissueFromExternalOrderId", null);+ if (!canReuseOrder && externalOrderId) {+ form.setValue("externalOrderId", null);}- }, [canReuseOrder, isOrdersLoading, reissueOrderId, codeSigningOrders, form]);+ }, [canReuseOrder, externalOrderId, form]);return (<FieldGroup>@@ -89,25 +59,21 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateStCertificate Authority <span className="text-danger">*</span></FieldLabel><FieldContent>- <FilterableSelect<CaOption>+ <Combobox<CaOption>+ isClearable={false}isLoading={isCasLoading}options={caOptions}value={caOptions.find((o) => o.id === field.value) ?? null}- onChange={(selected) => {- const opt = selected as CaOption | null;- field.onChange(opt?.id ?? "");- }}+ onValueChange={(opt) => field.onChange(opt.id)}getOptionLabel={(opt) => opt.name}getOptionValue={(opt) => opt.id}- groupBy={caOptions.length > 0 ? "groupType" : undefined}- getGroupHeaderLabel={- caOptions.length > 0- ? (groupType: CaGroup) =>- groupType === "internal" ? "Internal CAs" : "External CAs"- : undefined+ getOptionGroup={(opt) =>+ opt.groupType === "internal" ? "Internal CAs" : "External CAs"}placeholder="Select a Certificate Authority..."- noOptionsMessage={() => "No active CAs available."}+ searchPlaceholder="Search Certificate Authorities..."+ searchAriaLabel="Search Certificate Authorities"+ emptyMessage="No active CAs available."isError={Boolean(error)}/><FieldDescription>@@ -140,59 +106,11 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateSt/>)}- {canReuseOrder && (- <Controller- name="reissueFromExternalOrderId"- control={form.control}- render={({ field }) => (- <Field>- <FieldLabel>- <span className="inline-flex items-center gap-1.5">- Reuse an existing order (optional)- <Tooltip>- <TooltipTrigger asChild>- <InfoIcon className="h-3.5 w-3.5 text-muted" />- </TooltipTrigger>- <TooltipContent className="max-w-xs">- Issue into an existing order instead of creating a new one. The name and- validity are inherited from that order.- </TooltipContent>- </Tooltip>- </span>- </FieldLabel>- <FieldContent>- <FilterableSelect<OrderOption>- isLoading={isOrdersLoading}- isClearable- options={orderOptions}- value={orderOptions.find((o) => o.value === field.value) ?? null}- onChange={(selected) => {- const opt = selected as OrderOption | null;- field.onChange(opt?.value ?? null);- form.setValue(- "commonName",- opt ? opt.commonName || "Code signing certificate" : ""- );- }}- getOptionLabel={(opt) => opt.label}- getOptionValue={(opt) => opt.value}- placeholder="Issue a new certificate"- noOptionsMessage={() => "No existing orders found."}- />- <FieldDescription>Leave empty to issue a new certificate.</FieldDescription>- {field.value && (- <FieldDescription className="text-warning">- Reissuing replaces the certificate in this order. DigiCert revokes the previous- one within 72 hours, after which it can no longer be used to sign.- </FieldDescription>- )}- </FieldContent>- </Field>- )}- />+ {canReuseOrder && digicertCfg && (+ <DigiCertExistingOrderField form={form} digicert={digicertCfg} />)}- {!isReissue && (+ {!hasExternalOrder && (<Controllername="commonName"control={form.control}@@ -211,7 +129,7 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateSt/>)}- {!isReissue && (+ {!hasExternalOrder && (<Controllername="certificateTtlDays"control={form.control}diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsxindex 0d0ea6c29f..d11c87908b 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx@@ -3,7 +3,6 @@ import { useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { PenTool } from "lucide-react";-import { createNotification } from "@app/components/notifications";import {Button,DocumentationLinkBadge,@@ -28,10 +27,15 @@ import {CertKeySource,SignerKeyAlgorithm,SignerMemberRole,+ TSignerExternalConfiguration,useCreateSigner} from "@app/hooks/api/signers";import { useGetOrgUsers } from "@app/hooks/api/users";+import {+ ExternalOrderMode,+ isUsingExistingCertificate+} from "../../../components/DigiCertExistingOrderField";import { SignerKeyStep } from "../../../components/SignerKeyStep";import { PkiDocsUrls } from "../../../pki-docs-urls";import { ApprovalPolicyStep } from "./ApprovalPolicyStep";@@ -158,7 +162,11 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =keyAlgorithm: state.keyAlgorithm,keySource: state.keySource,hsmConnectorId: state.hsmConnectorId,- reissueFromExternalOrderId: state.reissueFromExternalOrderId,+ externalOrderId: state.externalOrderId,+ externalOrderMode: state.externalOrderMode,+ hsmKeyLabel: state.hsmKeyLabel,+ hsmKeyId: state.hsmKeyId,+ hsmKeyIdRequired: state.hsmKeyIdRequired,adcsTemplate: state.adcsTemplate}});@@ -185,7 +193,11 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =keyAlgorithm: SignerKeyAlgorithm.RSA_2048,keySource: CertKeySource.Infisical,hsmConnectorId: null,- reissueFromExternalOrderId: null,+ externalOrderId: null,+ externalOrderMode: ExternalOrderMode.Reissue,+ hsmKeyLabel: "",+ hsmKeyId: "",+ hsmKeyIdRequired: false,adcsTemplate: ""});};@@ -215,26 +227,25 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =}: undefined;+ const usingExistingCertificate = isUsingExistingCertificate(state);const certificate =state.keySource === CertKeySource.Hsm && state.hsmConnectorId? {keySource: CertKeySource.Hsm,- hsmConnectorId: state.hsmConnectorId+ hsmConnectorId: state.hsmConnectorId,+ hsmKeyLabel: usingExistingCertificate ? state.hsmKeyLabel : undefined,+ hsmKeyId: usingExistingCertificate && state.hsmKeyId ? state.hsmKeyId : undefined}: undefined;const selectedCaType = caOptions.find((o) => o.id === state.caId)?.caType;- let externalConfiguration;- if (state.reissueFromExternalOrderId) {- externalConfiguration = {- caType: CaType.DIGICERT,- reissueFromExternalOrderId: state.reissueFromExternalOrderId- } as const;+ let externalConfiguration: TSignerExternalConfiguration | undefined;+ if (state.externalOrderId) {+ externalConfiguration = usingExistingCertificate+ ? { importFromExternalOrderId: state.externalOrderId }+ : { reissueFromExternalOrderId: state.externalOrderId };} else if (selectedCaType === CaType.ADCS && state.adcsTemplate.trim()) {- externalConfiguration = {- caType: CaType.ADCS,- template: state.adcsTemplate.trim()- } as const;+ externalConfiguration = { template: state.adcsTemplate.trim() };}await createSigner.mutateAsync({@@ -242,10 +253,10 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =name: state.name,description: state.description || undefined,caId: state.caId,- commonName: state.commonName,- certificateTtlDays: state.certificateTtlDays,+ commonName: usingExistingCertificate ? undefined : state.commonName,+ certificateTtlDays: usingExistingCertificate ? undefined : state.certificateTtlDays,certificateRenewBeforeDays: state.certificateRenewBeforeDays,- keyAlgorithm: state.keyAlgorithm,+ keyAlgorithm: usingExistingCertificate ? undefined : state.keyAlgorithm,members: state.pendingMembers.map((m) => ({kind: m.kind,id: m.id,@@ -257,11 +268,8 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =});handleClose(false);- } catch (err) {- createNotification({- type: "error",- text: err instanceof Error ? err.message : "Failed to create signer"- });+ // eslint-disable-next-line no-empty+ } catch {} finally {setSubmitting(false);}@@ -280,7 +288,11 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =keyAlgorithm: values.keyAlgorithm,keySource: values.keySource,hsmConnectorId: values.hsmConnectorId ?? null,- reissueFromExternalOrderId: values.reissueFromExternalOrderId ?? null,+ externalOrderId: values.externalOrderId ?? null,+ externalOrderMode: values.externalOrderMode,+ hsmKeyLabel: values.hsmKeyLabel ?? "",+ hsmKeyId: values.hsmKeyId ?? "",+ hsmKeyIdRequired: values.hsmKeyIdRequired ?? false,adcsTemplate: values.adcsTemplate ?? ""}));};@@ -300,7 +312,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) ="commonName","certificateTtlDays","certificateRenewBeforeDays",- "reissueFromExternalOrderId"+ "externalOrderId"]);if (!ok) return;if (@@ -315,7 +327,13 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =return;}if (step === 2) {- const ok = await certificateForm.trigger(["keySource", "keyAlgorithm", "hsmConnectorId"]);+ const ok = await certificateForm.trigger([+ "keySource",+ "keyAlgorithm",+ "hsmConnectorId",+ "hsmKeyLabel",+ "hsmKeyId"+ ]);if (!ok) return;persistCertificateForm();setStep(3);diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.tsindex a56e5c03d7..9b82d66e80 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts@@ -7,6 +7,11 @@ import {} from "@app/hooks/api/signers";import { slugSchema } from "@app/lib/schemas";+import {+ ExternalOrderMode,+ isUsingExistingCertificate+} from "../../../components/DigiCertExistingOrderField";+export const basicsSchema = z.object({name: slugSchema({ min: 1, max: 64, field: "Name" }),description: z.string().trim().max(256).optional()@@ -38,8 +43,11 @@ export const certificateSchema = zkeyAlgorithm: z.nativeEnum(SignerKeyAlgorithm).default(SignerKeyAlgorithm.RSA_2048),keySource: z.nativeEnum(CertKeySource).default(CertKeySource.Infisical),hsmConnectorId: z.string().uuid().optional().nullable(),- // DigiCert code signing only: reissue into this existing order instead of placing a new one.- reissueFromExternalOrderId: z.string().nullable().optional().default(null),+ externalOrderId: z.string().nullable().optional().default(null),+ externalOrderMode: z.nativeEnum(ExternalOrderMode).default(ExternalOrderMode.Reissue),+ hsmKeyLabel: z.string().trim().max(128).optional().default(""),+ hsmKeyId: z.string().trim().max(256).optional().default(""),+ hsmKeyIdRequired: z.boolean().optional().default(false),// AD CS only: the certificate template this signer requests when issuing.adcsTemplate: z.string().trim().optional().default("")})@@ -56,9 +64,18 @@ export const certificateSchema = zmessage: "Pick an HSM Connector.",path: ["hsmConnectorId"]})+ .refine((data) => !isUsingExistingCertificate(data) || Boolean(data.hsmKeyLabel), {+ message: "Enter the label of the certificate's private key on the HSM.",+ path: ["hsmKeyLabel"]+ })+ .refine(+ (data) => !isUsingExistingCertificate(data) || !data.hsmKeyIdRequired || Boolean(data.hsmKeyId),+ { message: "Select which key to use.", path: ["hsmKeyId"] }+ ).refine((data) =>data.keySource !== CertKeySource.Hsm ||+ isUsingExistingCertificate(data) ||HSM_SUPPORTED_KEY_ALGORITHMS.includes(data.keyAlgorithm),{message:diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.tsindex 9bdef1b23f..aad19498cd 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts@@ -1,6 +1,7 @@import { CaType } from "@app/hooks/api/ca/enums";import { CertKeySource, SignerKeyAlgorithm, SignerMemberRole } from "@app/hooks/api/signers";+import { ExternalOrderMode } from "../../../components/DigiCertExistingOrderField";import { PkiDocsUrls } from "../../../pki-docs-urls";export type CaGroup = "internal" | "external";@@ -52,7 +53,11 @@ export type WizardState = {keyAlgorithm: SignerKeyAlgorithm;keySource: CertKeySource;hsmConnectorId: string | null;- reissueFromExternalOrderId: string | null;+ externalOrderId: string | null;+ externalOrderMode: ExternalOrderMode;+ hsmKeyLabel: string;+ hsmKeyId: string;+ hsmKeyIdRequired: boolean;adcsTemplate: string;pendingMembers: PendingMember[];policySteps: PolicyStep[];@@ -70,7 +75,11 @@ export const INITIAL_WIZARD_STATE: WizardState = {keyAlgorithm: SignerKeyAlgorithm.RSA_2048,keySource: CertKeySource.Infisical,hsmConnectorId: null,- reissueFromExternalOrderId: null,+ externalOrderId: null,+ externalOrderMode: ExternalOrderMode.Reissue,+ hsmKeyLabel: "",+ hsmKeyId: "",+ hsmKeyIdRequired: false,adcsTemplate: "",pendingMembers: [],policySteps: [],diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsxindex 02408e5f91..6228210ae5 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx@@ -1,27 +1,23 @@import { useEffect } from "react";import { Controller, useForm } from "react-hook-form";-import { InfoIcon } from "lucide-react";import {+ Combobox,Field,FieldContent,FieldDescription,FieldError,FieldGroup,FieldLabel,- FilterableSelect,- Input,- Tooltip,- TooltipContent,- TooltipTrigger+ Input} from "@app/components/v3";-import { useDigiCertConnectionListOrders } from "@app/hooks/api/appConnections/digicert";import { getCaIssuanceCapabilities } from "@app/hooks/api/ca";import { CaType } from "@app/hooks/api/ca/enums";import { AdcsTemplateField } from "../../../components/AdcsTemplateField";+import { DigiCertExistingOrderField } from "../../../components/DigiCertExistingOrderField";import { CertificateForm } from "./schemas";-import { CaGroup, CaOption } from "./types";+import { CaOption } from "./types";type CertificateStepProps = {form: ReturnType<typeof useForm<CertificateForm>>;@@ -36,43 +32,17 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateStconst digicertCfg = selectedCa?.digicert;const canReuseOrder = caps.supportsExistingOrderReuse && Boolean(digicertCfg);- const { data: codeSigningOrders = [], isLoading: isOrdersLoading } =- useDigiCertConnectionListOrders(- digicertCfg?.appConnectionId ?? "",- digicertCfg?.organizationId ?? 0,- digicertCfg?.productNameId ?? "",- { enabled: canReuseOrder }- );-- const orderOptions = codeSigningOrders.map((o) => ({- value: String(o.orderId),- label: `${o.commonName || o.organizationName || "Code signing certificate"} (#${o.orderId})`,- commonName: o.commonName- }));- type OrderOption = (typeof orderOptions)[number];-- const reissueOrderId = form.watch("reissueFromExternalOrderId");- const isReissue = Boolean(reissueOrderId);+ const externalOrderId = form.watch("externalOrderId");+ const hasExternalOrder = Boolean(externalOrderId);const isAdcs = selectedCa?.caType === CaType.ADCS;const adcsConnectionId = selectedCa?.adcs?.appConnectionId;useEffect(() => {- if (!canReuseOrder && reissueOrderId) {- form.setValue("reissueFromExternalOrderId", null);- }- }, [canReuseOrder, reissueOrderId, form]);-- useEffect(() => {- if (- canReuseOrder &&- !isOrdersLoading &&- reissueOrderId &&- !codeSigningOrders.some((order) => String(order.orderId) === reissueOrderId)- ) {- form.setValue("reissueFromExternalOrderId", null);+ if (!canReuseOrder && externalOrderId) {+ form.setValue("externalOrderId", null);}- }, [canReuseOrder, isOrdersLoading, reissueOrderId, codeSigningOrders, form]);+ }, [canReuseOrder, externalOrderId, form]);return (<FieldGroup>@@ -85,25 +55,21 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateStCertificate Authority <span className="text-danger">*</span></FieldLabel><FieldContent>- <FilterableSelect<CaOption>+ <Combobox<CaOption>+ isClearable={false}isLoading={isCasLoading}options={caOptions}value={caOptions.find((o) => o.id === field.value) ?? null}- onChange={(selected) => {- const opt = selected as CaOption | null;- field.onChange(opt?.id ?? "");- }}+ onValueChange={(opt) => field.onChange(opt.id)}getOptionLabel={(opt) => opt.name}getOptionValue={(opt) => opt.id}- groupBy={caOptions.length > 0 ? "groupType" : undefined}- getGroupHeaderLabel={- caOptions.length > 0- ? (groupType: CaGroup) =>- groupType === "internal" ? "Internal CAs" : "External CAs"- : undefined+ getOptionGroup={(opt) =>+ opt.groupType === "internal" ? "Internal CAs" : "External CAs"}placeholder="Select a Certificate Authority..."- noOptionsMessage={() => "No active CAs available."}+ searchPlaceholder="Search Certificate Authorities..."+ searchAriaLabel="Search Certificate Authorities"+ emptyMessage="No active CAs available."isError={Boolean(error)}/><FieldDescription>@@ -124,59 +90,11 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateSt/>)}- {canReuseOrder && (- <Controller- name="reissueFromExternalOrderId"- control={form.control}- render={({ field }) => (- <Field>- <FieldLabel>- <span className="inline-flex items-center gap-1.5">- Reuse an existing order (optional)- <Tooltip>- <TooltipTrigger asChild>- <InfoIcon className="h-3.5 w-3.5 text-muted" />- </TooltipTrigger>- <TooltipContent className="max-w-xs">- Issue into an existing order instead of creating a new one. The name and- validity are inherited from that order.- </TooltipContent>- </Tooltip>- </span>- </FieldLabel>- <FieldContent>- <FilterableSelect<OrderOption>- isLoading={isOrdersLoading}- isClearable- options={orderOptions}- value={orderOptions.find((o) => o.value === field.value) ?? null}- onChange={(selected) => {- const opt = selected as OrderOption | null;- field.onChange(opt?.value ?? null);- form.setValue(- "commonName",- opt ? opt.commonName || "Code signing certificate" : ""- );- }}- getOptionLabel={(opt) => opt.label}- getOptionValue={(opt) => opt.value}- placeholder="Issue a new certificate"- noOptionsMessage={() => "No existing orders found."}- />- <FieldDescription>Leave empty to issue a new certificate.</FieldDescription>- {field.value && (- <FieldDescription className="text-warning">- Reissuing replaces the certificate in this order. DigiCert revokes the previous- one within 72 hours, after which it can no longer be used to sign.- </FieldDescription>- )}- </FieldContent>- </Field>- )}- />+ {canReuseOrder && digicertCfg && (+ <DigiCertExistingOrderField form={form} digicert={digicertCfg} />)}- {!isReissue && (+ {!hasExternalOrder && (<Controllername="commonName"control={form.control}@@ -202,7 +120,7 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateSt/>)}- {!isReissue && (+ {!hasExternalOrder && (<Controllername="certificateTtlDays"control={form.control}diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsxindex d7244b2bbc..62b7bb9e96 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx@@ -3,7 +3,6 @@ import { useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { PenTool } from "lucide-react";-import { createNotification } from "@app/components/notifications";import {Button,DocumentationLinkBadge,@@ -29,11 +28,22 @@ import {useUpdateSigner} from "@app/hooks/api/signers";+import {+ ExternalOrderMode,+ isUsingExistingCertificate+} from "../../../components/DigiCertExistingOrderField";import { SignerKeyStep } from "../../../components/SignerKeyStep";import { PkiDocsUrls } from "../../../pki-docs-urls";import { BasicsStep } from "./BasicsStep";import { CertificateStep } from "./CertificateStep";-import { BasicsForm, basicsSchema, CertificateForm, certificateSchema } from "./schemas";+import {+ BasicsForm,+ basicsSchema,+ CertificateForm,+ createCertificateSchema,+ isSameKeyLocation,+ TCurrentSignerKey+} from "./schemas";import { CaOption, STEPS } from "./types";type Props = {@@ -107,8 +117,15 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {values: { name: signer.name, description: signer.description ?? "" }});+ const currentKey: TCurrentSignerKey = {+ keyAlgorithm: currentKeyAlgorithm,+ keySource: currentKeySource,+ hsmConnectorId: currentHsmConnectorId,+ caId: signer.caId ?? ""+ };+const certificateForm = useForm<CertificateForm>({- resolver: zodResolver(certificateSchema),+ resolver: zodResolver(createCertificateSchema(currentKey)),values: {caId: signer.caId ?? "",certificateRenewBeforeDays: signer.certificateRenewBeforeDays ?? null,@@ -117,7 +134,11 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {keySource: currentKeySource,keyAlgorithm: currentKeyAlgorithm,hsmConnectorId: currentHsmConnectorId,- reissueFromExternalOrderId: null,+ externalOrderId: null,+ externalOrderMode: ExternalOrderMode.Reissue,+ hsmKeyLabel: "",+ hsmKeyId: "",+ hsmKeyIdRequired: false,adcsTemplate: signerAdcsTemplate}});@@ -138,7 +159,8 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {const watchedKeySource = certificateForm.watch("keySource");const watchedHsmConnectorId = certificateForm.watch("hsmConnectorId");const watchedKeyAlgorithm = certificateForm.watch("keyAlgorithm");- const watchedReissueOrderId = certificateForm.watch("reissueFromExternalOrderId");+ const watchedExternalOrderId = certificateForm.watch("externalOrderId");+ const watchedExternalOrderMode = certificateForm.watch("externalOrderMode");const watchedAdcsTemplate = certificateForm.watch("adcsTemplate");const selectedCa = caOptions.find((o) => o.id === watchedCaId) ?? null;@@ -160,14 +182,18 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {(watchedKeySource === CertKeySource.Hsm &&(watchedHsmConnectorId ?? null) !== currentHsmConnectorId);const keyAlgorithmChanged = watchedKeyAlgorithm !== currentKeyAlgorithm;- const isReissueFromOrder = Boolean(watchedReissueOrderId);+ const isFromExternalOrder = Boolean(watchedExternalOrderId);+ const usingExistingCertificate = isUsingExistingCertificate({+ externalOrderId: watchedExternalOrderId,+ externalOrderMode: watchedExternalOrderMode+ });const adcsTemplateChanged = isAdcs && (watchedAdcsTemplate?.trim() ?? "") !== signerAdcsTemplate;const shouldReissue =caSwap ||subjectChanged ||keySourceChanged ||keyAlgorithmChanged ||- isReissueFromOrder ||+ isFromExternalOrder ||adcsTemplateChanged;const handleOpenChange = (open: boolean) => {@@ -182,7 +208,11 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {keySource: currentKeySource,keyAlgorithm: currentKeyAlgorithm,hsmConnectorId: currentHsmConnectorId,- reissueFromExternalOrderId: null,+ externalOrderId: null,+ externalOrderMode: ExternalOrderMode.Reissue,+ hsmKeyLabel: "",+ hsmKeyId: "",+ hsmKeyIdRequired: false,adcsTemplate: signerAdcsTemplate});}@@ -211,12 +241,23 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {await reissueCertificate.mutateAsync({signerId: signer.id,caId: cert.caId,- commonName: !isReissueFromOrder && subjectChanged ? cert.commonName : undefined,+ commonName: !isFromExternalOrder && subjectChanged ? cert.commonName : undefined,certificateTtlDays:- !isReissueFromOrder && subjectChanged ? cert.certificateTtlDays : undefined,- keyAlgorithm: keySourceChanged || keyAlgorithmChanged ? cert.keyAlgorithm : undefined,- certificate:- keySourceChanged || keyAlgorithmChanged+ !isFromExternalOrder && subjectChanged ? cert.certificateTtlDays : undefined,+ keyAlgorithm:+ !usingExistingCertificate && (keySourceChanged || keyAlgorithmChanged)+ ? cert.keyAlgorithm+ : undefined,+ certificate: (() => {+ if (usingExistingCertificate) {+ return {+ keySource: CertKeySource.Hsm,+ hsmConnectorId: cert.hsmConnectorId ?? undefined,+ hsmKeyLabel: cert.hsmKeyLabel,+ hsmKeyId: cert.hsmKeyId || undefined+ };+ }+ return keySourceChanged || keyAlgorithmChanged? {keySource: cert.keySource,hsmConnectorId:@@ -224,19 +265,16 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {? (cert.hsmConnectorId ?? undefined): undefined}- : undefined,+ : undefined;+ })(),externalConfiguration: (() => {- if (cert.reissueFromExternalOrderId) {- return {- caType: CaType.DIGICERT as const,- reissueFromExternalOrderId: cert.reissueFromExternalOrderId- };+ if (cert.externalOrderId) {+ return usingExistingCertificate+ ? { importFromExternalOrderId: cert.externalOrderId }+ : { reissueFromExternalOrderId: cert.externalOrderId };}if (isAdcs) {- return {- caType: CaType.ADCS as const,- template: cert.adcsTemplate?.trim() || undefined- };+ return { template: cert.adcsTemplate?.trim() || undefined };}return undefined;})()@@ -253,11 +291,8 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {}handleOpenChange(false);- } catch (err) {- createNotification({- type: "error",- text: err instanceof Error ? err.message : "Failed to update signer"- });+ // eslint-disable-next-line no-empty+ } catch {} finally {setSubmitting(false);}@@ -282,7 +317,13 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {return;}if (step === 2) {- const ok = await certificateForm.trigger(["keySource", "keyAlgorithm", "hsmConnectorId"]);+ const ok = await certificateForm.trigger([+ "keySource",+ "keyAlgorithm",+ "hsmConnectorId",+ "hsmKeyLabel",+ "hsmKeyId"+ ]);if (!ok) return;await onSave();}@@ -295,7 +336,11 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {const currentStep = STEPS[step];const isLast = step === STEPS.length - 1;// eslint-disable-next-line no-nested-ternary- const ctaLabel = isLast ? (shouldReissue ? "Save and reissue" : "Save") : "Continue";+ const ctaLabel = isLast+ ? shouldReissue && !usingExistingCertificate+ ? "Save and reissue"+ : "Save"+ : "Continue";return (<Sheet open={isOpen} onOpenChange={handleOpenChange}>@@ -366,6 +411,18 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {minRsaKeyBits={minRsaKeyBits}hsmConnectorOptions={hsmConnectorOptions}isHsmConnectorsLoading={isHsmConnectorsLoading}+ currentKeyAlgorithm={+ isSameKeyLocation(+ {+ keySource: watchedKeySource,+ hsmConnectorId: watchedHsmConnectorId,+ caId: watchedCaId+ },+ currentKey+ )+ ? currentKeyAlgorithm+ : undefined+ }/>)}</div>@@ -388,9 +445,12 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {<SheetFooter className="shrink-0 items-center justify-between border-t"><span className="text-xs text-warning">- {shouldReissue- ? "Saving reissues the certificate immediately. The signer switches to the new certificate."- : ""}+ {/* eslint-disable-next-line no-nested-ternary */}+ {usingExistingCertificate+ ? "Saving switches the signer to the certificate already issued in this order."+ : shouldReissue+ ? "Saving reissues the certificate immediately. The signer switches to the new certificate."+ : ""}</span><div className="flex items-center gap-3"><span className="text-xs text-muted">diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.tsindex b3497907e2..d8af2d788a 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts@@ -7,64 +7,99 @@ import {} from "@app/hooks/api/signers";import { slugSchema } from "@app/lib/schemas";+import {+ ExternalOrderMode,+ isUsingExistingCertificate+} from "../../../components/DigiCertExistingOrderField";+export const basicsSchema = z.object({name: slugSchema({ min: 1, max: 64, field: "Name" }),description: z.string().trim().max(256).optional().or(z.literal(""))});export type BasicsForm = z.infer<typeof basicsSchema>;-export const certificateSchema = z- .object({- caId: z.string().uuid("Certificate Authority is required"),- certificateRenewBeforeDays: z- .preprocess(- (v) => {- if (v === "" || v === null || v === undefined) return null;- const n = typeof v === "number" ? v : Number(v);- return Number.isNaN(n) ? v : n;- },- z.union([- z- .number()- .int("Must be a whole number of days")- .min(1, "Must be at least 1 day")- .max(30, "Must be at most 30 days"),- z.null()- ])- )- .default(null),- commonName: z.string().trim().min(1, "Common Name is required").max(256).optional(),- certificateTtlDays: z.coerce.number().int().min(1).max(3650).optional(),- keySource: z.nativeEnum(CertKeySource).default(CertKeySource.Infisical),- keyAlgorithm: z.nativeEnum(SignerKeyAlgorithm).default(SignerKeyAlgorithm.RSA_2048),- hsmConnectorId: z.string().uuid().optional().nullable(),- // DigiCert code signing only: reissue into this existing order instead of placing a new one.- reissueFromExternalOrderId: z.string().nullable().optional().default(null),- // AD CS only: the certificate template this signer requests when issuing.- adcsTemplate: z.string().trim().optional().default("")- })- .refine(- (data) =>- data.certificateRenewBeforeDays == null ||- data.certificateTtlDays == null ||- data.certificateRenewBeforeDays < data.certificateTtlDays,- {- message: "Renew before must be less than the certificate validity (days).",- path: ["certificateRenewBeforeDays"]- }- )- .refine((data) => data.keySource !== CertKeySource.Hsm || Boolean(data.hsmConnectorId), {- message: "Pick an HSM Connector.",- path: ["hsmConnectorId"]- })- .refine(- (data) =>- data.keySource !== CertKeySource.Hsm ||- HSM_SUPPORTED_KEY_ALGORITHMS.includes(data.keyAlgorithm),- {- message:- "This algorithm is not supported by HSM-backed keys. Pick RSA-2048, RSA-4096, ECDSA P-256, or ECDSA P-384.",- path: ["keyAlgorithm"]- }- );-export type CertificateForm = z.infer<typeof certificateSchema>;+export type TCurrentSignerKey = {+ keyAlgorithm: SignerKeyAlgorithm;+ keySource: CertKeySource;+ hsmConnectorId: string | null;+ caId: string;+};++export const isSameKeyLocation = (+ data: { keySource: CertKeySource; hsmConnectorId?: string | null; caId: string },+ currentKey: TCurrentSignerKey+) =>+ data.keySource === currentKey.keySource &&+ (data.hsmConnectorId ?? null) === currentKey.hsmConnectorId &&+ data.caId === currentKey.caId;++export const createCertificateSchema = (currentKey: TCurrentSignerKey) =>+ z+ .object({+ caId: z.string().uuid("Certificate Authority is required"),+ certificateRenewBeforeDays: z+ .preprocess(+ (v) => {+ if (v === "" || v === null || v === undefined) return null;+ const n = typeof v === "number" ? v : Number(v);+ return Number.isNaN(n) ? v : n;+ },+ z.union([+ z+ .number()+ .int("Must be a whole number of days")+ .min(1, "Must be at least 1 day")+ .max(30, "Must be at most 30 days"),+ z.null()+ ])+ )+ .default(null),+ commonName: z.string().trim().min(1, "Common Name is required").max(256).optional(),+ certificateTtlDays: z.coerce.number().int().min(1).max(3650).optional(),+ keySource: z.nativeEnum(CertKeySource).default(CertKeySource.Infisical),+ keyAlgorithm: z.nativeEnum(SignerKeyAlgorithm).default(SignerKeyAlgorithm.RSA_2048),+ hsmConnectorId: z.string().uuid().optional().nullable(),+ externalOrderId: z.string().nullable().optional().default(null),+ externalOrderMode: z.nativeEnum(ExternalOrderMode).default(ExternalOrderMode.Reissue),+ hsmKeyLabel: z.string().trim().max(128).optional().default(""),+ hsmKeyId: z.string().trim().max(256).optional().default(""),+ hsmKeyIdRequired: z.boolean().optional().default(false),+ // AD CS only: the certificate template this signer requests when issuing.+ adcsTemplate: z.string().trim().optional().default("")+ })+ .refine(+ (data) =>+ data.certificateRenewBeforeDays == null ||+ data.certificateTtlDays == null ||+ data.certificateRenewBeforeDays < data.certificateTtlDays,+ {+ message: "Renew before must be less than the certificate validity (days).",+ path: ["certificateRenewBeforeDays"]+ }+ )+ .refine((data) => data.keySource !== CertKeySource.Hsm || Boolean(data.hsmConnectorId), {+ message: "Pick an HSM Connector.",+ path: ["hsmConnectorId"]+ })+ .refine((data) => !isUsingExistingCertificate(data) || Boolean(data.hsmKeyLabel), {+ message: "Enter the label of the certificate's private key on the HSM.",+ path: ["hsmKeyLabel"]+ })+ .refine(+ (data) =>+ !isUsingExistingCertificate(data) || !data.hsmKeyIdRequired || Boolean(data.hsmKeyId),+ { message: "Select which key to use.", path: ["hsmKeyId"] }+ )+ .refine(+ (data) =>+ data.keySource !== CertKeySource.Hsm ||+ isUsingExistingCertificate(data) ||+ (isSameKeyLocation(data, currentKey) && data.keyAlgorithm === currentKey.keyAlgorithm) ||+ HSM_SUPPORTED_KEY_ALGORITHMS.includes(data.keyAlgorithm),+ {+ message:+ "This algorithm is not supported by HSM-backed keys. Pick RSA-2048, RSA-4096, ECDSA P-256, or ECDSA P-384.",+ path: ["keyAlgorithm"]+ }+ );+export type CertificateForm = z.infer<ReturnType<typeof createCertificateSchema>>;diff --git a/frontend/src/pages/cert-manager/components/DigiCertExistingOrderField.tsx b/frontend/src/pages/cert-manager/components/DigiCertExistingOrderField.tsxnew file mode 100644index 0000000000..02270c2e29--- /dev/null+++ b/frontend/src/pages/cert-manager/components/DigiCertExistingOrderField.tsx@@ -0,0 +1,113 @@+import { useEffect } from "react";+import { Controller, UseFormReturn } from "react-hook-form";+import { InfoIcon } from "lucide-react";++import {+ Combobox,+ Field,+ FieldContent,+ FieldDescription,+ FieldLabel,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { useDigiCertConnectionListOrders } from "@app/hooks/api/appConnections/digicert";++export enum ExternalOrderMode {+ UseExisting = "use-existing",+ Reissue = "reissue"+}++export const isUsingExistingCertificate = (data: {+ externalOrderId?: string | null;+ externalOrderMode?: ExternalOrderMode;+}) => Boolean(data.externalOrderId) && data.externalOrderMode === ExternalOrderMode.UseExisting;++type DigiCertExistingOrderFieldProps = {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ form: UseFormReturn<any>;+ digicert: { appConnectionId: string; organizationId: number; productNameId: string };+};++export const DigiCertExistingOrderField = ({ form, digicert }: DigiCertExistingOrderFieldProps) => {+ const { data: codeSigningOrders = [], isLoading: isOrdersLoading } =+ useDigiCertConnectionListOrders(+ digicert.appConnectionId,+ digicert.organizationId,+ digicert.productNameId+ );++ const now = Date.now();+ const orderOptions = codeSigningOrders+ .filter(+ (o) =>+ o.status.toLowerCase() === "issued" &&+ (!o.validTill || new Date(o.validTill).getTime() > now)+ )+ .map((o) => ({+ value: String(o.orderId),+ label: `${o.commonName || o.organizationName || "Code signing certificate"} (#${o.orderId})`,+ commonName: o.commonName+ }));+ type OrderOption = (typeof orderOptions)[number];++ const externalOrderId = form.watch("externalOrderId") as string | null;++ useEffect(() => {+ if (+ !isOrdersLoading &&+ externalOrderId &&+ !orderOptions.some((option) => option.value === externalOrderId)+ ) {+ form.setValue("externalOrderId", null);+ }+ }, [isOrdersLoading, externalOrderId, orderOptions, form]);++ return (+ <Controller+ name="externalOrderId"+ control={form.control}+ render={({ field }) => (+ <Field>+ <FieldLabel>+ <span className="inline-flex items-center gap-1.5">+ Existing order (optional)+ <Tooltip>+ <TooltipTrigger asChild>+ <InfoIcon className="h-3.5 w-3.5 text-muted" />+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ Use an order you already have instead of creating a new one. The name and validity+ come from that order.+ </TooltipContent>+ </Tooltip>+ </span>+ </FieldLabel>+ <FieldContent>+ <Combobox<OrderOption>+ isLoading={isOrdersLoading}+ options={orderOptions}+ value={orderOptions.find((o) => o.value === field.value) ?? null}+ onValueChange={(opt) => {+ field.onChange(opt?.value ?? null);+ form.setValue(+ "commonName",+ opt ? opt.commonName || "Code signing certificate" : ""+ );+ }}+ getOptionLabel={(opt) => opt.label}+ getOptionValue={(opt) => opt.value}+ placeholder="Issue a new certificate"+ searchPlaceholder="Search orders..."+ searchAriaLabel="Search orders"+ clearAriaLabel="Clear existing order"+ emptyMessage="No existing orders found."+ />+ <FieldDescription>Leave empty to issue a new certificate.</FieldDescription>+ </FieldContent>+ </Field>+ )}+ />+ );+};diff --git a/frontend/src/pages/cert-manager/components/SignerKeyStep.tsx b/frontend/src/pages/cert-manager/components/SignerKeyStep.tsxindex 159a1b16ad..f417a13b4b 100644--- a/frontend/src/pages/cert-manager/components/SignerKeyStep.tsx+++ b/frontend/src/pages/cert-manager/components/SignerKeyStep.tsx@@ -1,21 +1,24 @@import { ReactNode, useEffect } from "react";import { Control, Controller, useController, useWatch } from "react-hook-form";-import { AlertTriangleIcon } from "lucide-react";+import { AxiosError } from "axios";+import { AlertTriangleIcon, InfoIcon } from "lucide-react";import {Badge,+ Combobox,Field,FieldContent,FieldDescription,FieldError,FieldGroup,FieldLabel,- FilterableSelect,+ Input,Select,SelectContent,SelectItem,SelectTrigger,SelectValue,+ Toggle,Tooltip,TooltipContent,TooltipTrigger@@ -25,6 +28,8 @@ import {ProjectPermissionHsmConnectorActions,ProjectPermissionSub} from "@app/context/ProjectPermissionContext/types";+import { useDebounce } from "@app/hooks";+import { THsmConnectorKey, useListHsmConnectorKeys } from "@app/hooks/api/hsmConnectors";import {CertKeySource,HSM_SUPPORTED_KEY_ALGORITHMS,@@ -32,6 +37,15 @@ import {signerKeyAlgorithmLabels} from "@app/hooks/api/signers";+import { ExternalOrderMode, isUsingExistingCertificate } from "./DigiCertExistingOrderField";++const shortenKeyId = (keyId: string) => (keyId.length > 8 ? `${keyId.slice(0, 8)}...` : keyId);++const formatHsmKeyOption = (key: THsmConnectorKey) =>+ key.keyAlgorithm+ ? `ID ${shortenKeyId(key.keyId)} (${key.keyAlgorithm.replace("_", " ")})`+ : `ID ${shortenKeyId(key.keyId)}`;+export type HsmConnectorOption = { id: string; name: string; slotLabel: string };type SignerKeyStepProps = {@@ -41,6 +55,7 @@ type SignerKeyStepProps = {hsmConnectorOptions: HsmConnectorOption[];isHsmConnectorsLoading: boolean;minRsaKeyBits?: number;+ currentKeyAlgorithm?: SignerKeyAlgorithm;};export const SignerKeyStep = ({@@ -48,7 +63,8 @@ export const SignerKeyStep = ({requiresHsm,hsmConnectorOptions,isHsmConnectorsLoading,- minRsaKeyBits+ minRsaKeyBits,+ currentKeyAlgorithm}: SignerKeyStepProps) => {const { subscription } = useSubscription();const isHsmLicensed = Boolean(subscription?.hsm);@@ -60,8 +76,71 @@ export const SignerKeyStep = ({const keySource = useWatch({ control, name: "keySource" });const isHsm = keySource === CertKeySource.Hsm;+ const externalOrderId = useWatch({ control, name: "externalOrderId" }) as+ | string+ | null+ | undefined;+ const externalOrderMode = useWatch({ control, name: "externalOrderMode" }) as ExternalOrderMode;+ const usingExistingCertificate = isUsingExistingCertificate({+ externalOrderId,+ externalOrderMode+ });++ const hsmConnectorId = useWatch({ control, name: "hsmConnectorId" }) as string | null | undefined;+ const {+ field: hsmKeyLabelField,+ fieldState: { error: hsmKeyLabelError }+ } = useController({ control, name: "hsmKeyLabel" });+ const {+ field: hsmKeyIdField,+ fieldState: { error: hsmKeyIdError }+ } = useController({ control, name: "hsmKeyId" });+ const { field: hsmKeyIdRequiredField } = useController({ control, name: "hsmKeyIdRequired" });+ const [debouncedKeyLabel] = useDebounce(((hsmKeyLabelField.value as string) ?? "").trim());+ const {+ data: matchingHsmKeys,+ isFetching: isHsmKeyLookupPending,+ error: hsmKeyLookupError+ } = useListHsmConnectorKeys(hsmConnectorId, debouncedKeyLabel, {+ enabled: isHsm && usingExistingCertificate+ });+ const hsmKeyChoices = (matchingHsmKeys ?? []).filter((key) => Boolean(key.keyId));+ const canChooseHsmKey = (matchingHsmKeys?.length ?? 0) > 1 && hsmKeyChoices.length > 0;++ useEffect(() => {+ const keys = matchingHsmKeys ?? [];+ hsmKeyIdRequiredField.onChange(keys.length > 1 && keys.some((key) => Boolean(key.keyId)));+ if (keys.length === 1) {+ hsmKeyIdField.onChange(keys[0].keyId);+ } else if (!keys.some((key) => key.keyId === hsmKeyIdField.value)) {+ hsmKeyIdField.onChange("");+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [matchingHsmKeys]);++ let hsmKeyLookupHint = "The label of the certificate's private key on the HSM.";+ if (isHsmKeyLookupPending) {+ hsmKeyLookupHint = "Looking up the key...";+ } else if (matchingHsmKeys?.length === 1) {+ hsmKeyLookupHint = matchingHsmKeys[0].keyId+ ? `Found the key (ID ${shortenKeyId(matchingHsmKeys[0].keyId)}).`+ : "Found the key.";+ } else if (matchingHsmKeys && matchingHsmKeys.length > 1) {+ hsmKeyLookupHint = canChooseHsmKey+ ? `${matchingHsmKeys.length} keys have this label. Select one below.`+ : `${matchingHsmKeys.length} keys have this label and none has a key ID. Give the keys unique labels.`;+ }+ let hsmKeyLookupProblem: string | undefined;+ if (hsmKeyLookupError) {+ hsmKeyLookupProblem =+ (hsmKeyLookupError as AxiosError<{ message?: string }>)?.response?.data?.message ??+ "Could not look up the key.";+ } else if (matchingHsmKeys?.length === 0) {+ hsmKeyLookupProblem = "No private key with this label in the connector's slot.";+ }const isAlgorithmAllowed = (algo: SignerKeyAlgorithm): boolean => {+ if (algo === currentKeyAlgorithm) return true;if (isHsm && !HSM_SUPPORTED_KEY_ALGORITHMS.includes(algo)) return false;if (minRsaKeyBits && algo.startsWith("RSA_") && Number(algo.slice(4)) < minRsaKeyBits)return false;@@ -71,11 +150,21 @@ export const SignerKeyStep = ({const { field: keyAlgorithmField } = useController({ control, name: "keyAlgorithm" });useEffect(() => {- if (algorithmOptions.length > 0 && !isAlgorithmAllowed(keyAlgorithmField.value)) {+ if (+ !usingExistingCertificate &&+ algorithmOptions.length > 0 &&+ !isAlgorithmAllowed(keyAlgorithmField.value)+ ) {keyAlgorithmField.onChange(algorithmOptions[0]);}// eslint-disable-next-line react-hooks/exhaustive-deps- }, [isHsm, minRsaKeyBits, keyAlgorithmField.value]);+ }, [+ isHsm,+ minRsaKeyBits,+ keyAlgorithmField.value,+ usingExistingCertificate,+ currentKeyAlgorithm+ ]);let keySourceHint: ReactNode = "Infisical manages the keypair.";if (requiresHsm) {@@ -142,18 +231,18 @@ export const SignerKeyStep = ({HSM Connector <span className="text-danger">*</span></FieldLabel><FieldContent>- <FilterableSelect<HsmConnectorOption>+ <Combobox<HsmConnectorOption>+ isClearable={false}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);- }}+ onValueChange={(opt) => field.onChange(opt.id)}getOptionLabel={(opt) => `${opt.name} (slot ${opt.slotLabel})`}getOptionValue={(opt) => opt.id}placeholder="Select an HSM Connector..."- noOptionsMessage={() =>+ searchPlaceholder="Search HSM Connectors..."+ searchAriaLabel="Search HSM Connectors"+ emptyMessage={hsmConnectorOptions.length === 0? "No HSM Connectors configured. Add one in Settings → HSM Connectors.": "No match."@@ -168,28 +257,114 @@ export const SignerKeyStep = ({/>)}- <Field>- <FieldLabel>- Key algorithm <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <Select value={keyAlgorithmField.value} onValueChange={keyAlgorithmField.onChange}>- <SelectTrigger className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- {algorithmOptions.map((value) => (- <SelectItem key={value} value={value}>- {signerKeyAlgorithmLabels[value]}- </SelectItem>- ))}- </SelectContent>- </Select>- <FieldDescription>- RSA is widely compatible; ECDSA is smaller and faster.- </FieldDescription>- </FieldContent>- </Field>+ {isHsm && externalOrderId && (+ <Controller+ name="externalOrderMode"+ control={control}+ render={({ field }) => (+ <Field orientation="horizontal">+ <FieldContent>+ <div className="flex items-center gap-1.5">+ <FieldLabel htmlFor="use-existing-key">Use existing key</FieldLabel>+ <Tooltip>+ <TooltipTrigger asChild>+ <InfoIcon className="h-3.5 w-3.5 text-muted" />+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ When off, DigiCert reissues the certificate and revokes the current one.+ </TooltipContent>+ </Tooltip>+ </div>+ <FieldDescription>+ Sign with the certificate already issued in this order and its key on the HSM.+ </FieldDescription>+ </FieldContent>+ <Toggle+ id="use-existing-key"+ variant="project"+ checked={field.value === ExternalOrderMode.UseExisting}+ onCheckedChange={(checked) =>+ field.onChange(+ checked ? ExternalOrderMode.UseExisting : ExternalOrderMode.Reissue+ )+ }+ />+ </Field>+ )}+ />+ )}++ {isHsm && usingExistingCertificate && (+ <Field>+ <FieldLabel>+ Key label <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Input+ {...hsmKeyLabelField}+ value={hsmKeyLabelField.value ?? ""}+ placeholder="acme-code-signing-2026"+ isError={Boolean(hsmKeyLabelError || hsmKeyLookupProblem)}+ />+ <FieldDescription>{hsmKeyLookupHint}</FieldDescription>+ <FieldError+ errors={[+ hsmKeyLabelError,+ hsmKeyLookupProblem ? { message: hsmKeyLookupProblem } : undefined+ ]}+ />+ </FieldContent>+ </Field>+ )}++ {isHsm && usingExistingCertificate && canChooseHsmKey && (+ <Field>+ <FieldLabel>+ Key ID <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Select value={hsmKeyIdField.value || undefined} onValueChange={hsmKeyIdField.onChange}>+ <SelectTrigger className="w-full" isError={Boolean(hsmKeyIdError)}>+ <SelectValue placeholder="Select a key..." />+ </SelectTrigger>+ <SelectContent position="popper">+ {hsmKeyChoices.map((key) => (+ <SelectItem key={key.keyId} value={key.keyId}>+ {formatHsmKeyOption(key)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldDescription>The key's CKA_ID on the HSM.</FieldDescription>+ <FieldError errors={[hsmKeyIdError]} />+ </FieldContent>+ </Field>+ )}++ {!usingExistingCertificate && (+ <Field>+ <FieldLabel>+ Key algorithm <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Select value={keyAlgorithmField.value} onValueChange={keyAlgorithmField.onChange}>+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ {algorithmOptions.map((value) => (+ <SelectItem key={value} value={value}>+ {signerKeyAlgorithmLabels[value]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldDescription>+ RSA is widely compatible; ECDSA is smaller and faster.+ </FieldDescription>+ </FieldContent>+ </Field>+ )}</FieldGroup>);};