Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Address PR comments
Carlos Monastyrski245582fd4703
diff --git a/backend/src/server/routes/v1/hsm-connector-router-schemas.ts b/backend/src/server/routes/v1/hsm-connector-router-schemas.tsindex 6c435301ce..842c17ad73 100644--- a/backend/src/server/routes/v1/hsm-connector-router-schemas.ts+++ b/backend/src/server/routes/v1/hsm-connector-router-schemas.ts@@ -2,7 +2,7 @@ import { z } from "zod";import { slugSchema } from "@app/server/lib/schemas";import { CaStatus, InternalCaType } from "@app/services/certificate-authority/certificate-authority-enums";-import { HsmConnectorCredentialsSchema } from "@app/services/hsm-connector/hsm-connector-fns";+import { HsmConnectorCredentialsSchema, HsmKeyLabelSchema } from "@app/services/hsm-connector/hsm-connector-fns";const HSM_CONNECTOR_NAME_MAX = 32;const HSM_CONNECTOR_DESCRIPTION_MAX = 256;@@ -105,7 +105,7 @@ export const HsmConnectorLinkedResourcesResponseSchema = z.object({});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.")+ label: HsmKeyLabelSchema.describe("The exact label (CKA_LABEL) of the private keys to look up.")});export const HsmConnectorKeysResponseSchema = z.object({diff --git a/backend/src/server/routes/v1/hsm-connector-router.ts b/backend/src/server/routes/v1/hsm-connector-router.tsindex 3fa7b1747b..8d96872f88 100644--- a/backend/src/server/routes/v1/hsm-connector-router.ts+++ b/backend/src/server/routes/v1/hsm-connector-router.ts@@ -253,7 +253,7 @@ export const createHsmConnectorRouter =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 },+ { connectorId: req.params.connectorId, projectId: resolveProjectId(req), keyLabel: req.query.label },req.permission);return { keys };diff --git a/backend/src/server/routes/v1/signer-routers/schemas.ts b/backend/src/server/routes/v1/signer-routers/schemas.tsindex 8f0cb7b4a7..f992ee4978 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 { HsmKeyLabelSchema } from "@app/services/hsm-connector/hsm-connector-fns";import { CertKeySource } from "@app/services/signer/signer-enums";const RE_NO_NEWLINES = new RE2("^[^\\r\\n]+$");@@ -41,12 +42,7 @@ export const SignerExternalConfigurationSchema = z.object({export const SignerCertificateInputSchema = z.object({keySource: z.enum([CertKeySource.Infisical, CertKeySource.Hsm]).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")+ hsmKeyLabel: HsmKeyLabelSchema.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."diff --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 d9f3f3a46f..f721f31139 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@@ -746,6 +746,7 @@ export const DigiCertCertificateAuthorityFns = ({assertCodeSigningOrderReusable: codeSigningFns.assertCodeSigningOrderReusable,getCodeSigningOrderStatus: codeSigningFns.getCodeSigningOrderStatus,fetchIssuedCodeSigningCertificate: codeSigningFns.fetchIssuedCodeSigningCertificate,+ prepareCodeSigningCertificate: codeSigningFns.prepareCodeSigningCertificate,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 be5e02c703..c2078f508f 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,4 +1,5 @@import * as x509 from "@peculiar/x509";+import { Knex } from "knex";import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError } from "@app/lib/errors";@@ -44,6 +45,15 @@ const CS_SERVER_PLATFORM_OTHER = -1;// When a renewal_of_order_id link is rejected with one of these codes, retry as a fresh order.const CS_RENEWAL_INELIGIBLE_CODES = ["order_not_eligible_for_renewal", "order_renewed_already"];+export type TPreparedCodeSigningCertificate =+ | { certificatePem: string; existingCertificateId: string; insert: null }+ | {+ certificatePem: string;+ existingCertificateId: null;+ insert: (tx: Knex) => Promise<string>;+ findConcurrentInsert: () => Promise<string | null>;+ };+type TDigiCertCodeSigningFnsDeps = {appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;@@ -324,7 +334,7 @@ export const digiCertCodeSigningFns = ({return { pemBundle, certificate };};- const downloadCodeSigningCertificate = async ({+ const prepareCodeSigningCertificate = async ({caId,orderId,digicertCertificateId,@@ -342,7 +352,7 @@ export const digiCertCodeSigningFns = ({signatureAlgorithm?: string;applicationId?: string | null;profileId?: string | null;- }): Promise<{ certificateId: string; certificatePem: string }> => {+ }): Promise<TPreparedCodeSigningCertificate> => {const { ca, client } = await loadDigiCertCsContext(caId);if (!providedPemBundle && !digicertCertificateId) {throw new BadRequestError({ message: `DigiCert order ${orderId} has no certificate to download.` });@@ -352,10 +362,14 @@ export const digiCertCodeSigningFns = ({const certObj = new x509.X509Certificate(leaf);const parsedFields = extractExternallyIssuedCertificateFields(certObj);+ const differentCaError = 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.`+ });- const existingCert = await certificateDAL.findOne({ caId: ca.id, serialNumber: certObj.serialNumber });+ const existingCert = await certificateDAL.findOne({ serialNumber: certObj.serialNumber });if (existingCert) {- return { certificateId: existingCert.id, certificatePem: leaf };+ if (existingCert.caId !== ca.id) throw differentCaError;+ return { certificatePem: leaf, existingCertificateId: existingCert.id, insert: null };}const certificateManagerKmsId = await getProjectKmsCertificateKeyId({@@ -371,55 +385,73 @@ 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 insert = async (tx: Knex) => {+ 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+ );++ return cert.id;+ };- await certificateBodyDAL.create(- {- certId: cert.id,- encryptedCertificate,- encryptedCertificateChain- },- tx+ return {+ certificatePem: leaf,+ existingCertificateId: null,+ insert,+ findConcurrentInsert: async () => {+ const concurrentCert = await certificateDAL.transaction((tx) =>+ certificateDAL.findOne({ serialNumber: certObj.serialNumber }, tx));+ if (concurrentCert && concurrentCert.caId !== ca.id) throw differentCaError;+ return concurrentCert?.id ?? null;+ }+ };+ };- 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;- });+ const downloadCodeSigningCertificate = async (+ args: Parameters<typeof prepareCodeSigningCertificate>[0]+ ): Promise<{ certificateId: string; certificatePem: string }> => {+ const prepared = await prepareCodeSigningCertificate(args);+ if (!prepared.insert) {+ return { certificateId: prepared.existingCertificateId, certificatePem: prepared.certificatePem };+ }+ const { insert, findConcurrentInsert } = prepared;++ const createdCertificateId = await certificateDAL.transaction(insert).catch(async (error: unknown) => {+ if ((error as { error?: { code?: string } })?.error?.code === DatabaseErrorCode.UniqueViolation) {+ const concurrentCertificateId = await findConcurrentInsert();+ if (concurrentCertificateId) return concurrentCertificateId;+ }+ throw error;+ });- return { certificateId: createdCertificateId, certificatePem: leaf };+ return { certificateId: createdCertificateId, certificatePem: prepared.certificatePem };};return {@@ -430,6 +462,7 @@ export const digiCertCodeSigningFns = ({assertCodeSigningOrderReusable,getCodeSigningOrderStatus,fetchIssuedCodeSigningCertificate,+ prepareCodeSigningCertificate,downloadCodeSigningCertificate};};diff --git a/backend/src/services/hsm-connector/hsm-connector-fns.ts b/backend/src/services/hsm-connector/hsm-connector-fns.tsindex 92aba521af..e2b01f7389 100644--- a/backend/src/services/hsm-connector/hsm-connector-fns.ts+++ b/backend/src/services/hsm-connector/hsm-connector-fns.ts@@ -5,6 +5,18 @@ import { KmsDataKey } from "@app/services/kms/kms-types";import type { THsmConnectorServiceFactoryDep } from "./hsm-connector-service";import type { THsmConnectorCredentials } from "./hsm-connector-types";+const HSM_KEY_LABEL_MAX_BYTES = 256;++export const HsmKeyLabelSchema = z+ .string()+ .trim()+ .min(1)+ .max(128)+ .refine(+ (v) => Buffer.byteLength(v, "utf8") <= HSM_KEY_LABEL_MAX_BYTES,+ `Key label must be at most ${HSM_KEY_LABEL_MAX_BYTES} bytes`+ );+export const HSM_CREDENTIALS_LIMITS = {slotLabelMax: 128,pinMax: 512,diff --git a/backend/src/services/hsm-connector/hsm-connector-service.ts b/backend/src/services/hsm-connector/hsm-connector-service.tsindex 01b4fc7880..2f50994c50 100644--- a/backend/src/services/hsm-connector/hsm-connector-service.ts+++ b/backend/src/services/hsm-connector/hsm-connector-service.ts@@ -56,6 +56,7 @@ export type THsmConnectorServiceFactoryDep = {export type THsmConnectorServiceFactory = ReturnType<typeof hsmConnectorServiceFactory>;const OLD_GATEWAY_BAD_REQUEST_MESSAGE = "Invalid request";+const GATEWAY_MAX_SIGN_DATA_BYTES = 64 * 1024;export const hsmConnectorServiceFactory = ({hsmConnectorDAL,@@ -437,7 +438,7 @@ export const hsmConnectorServiceFactory = ({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.`+ message: `More than one key in the HSM Connector's slot has the label '${keyLabel}', and the gateway is too old to select a key by key ID. Update the gateway to the latest version.`});}if (isPkcs11Error(err, Pkcs11ErrorCode.SignatureMismatch)) {@@ -487,6 +488,11 @@ export const hsmConnectorServiceFactory = ({data: Buffer;isDigest: boolean;}): Promise<{ signature: Buffer; keyId: string | null }> => {+ if (args.data.length > GATEWAY_MAX_SIGN_DATA_BYTES) {+ throw new BadRequestError({+ message: `The data to sign is ${args.data.length} bytes, more than the ${GATEWAY_MAX_SIGN_DATA_BYTES} bytes the HSM Connector's gateway accepts.`+ });+ }const { row, credentials } = await $loadConnector(args.connectorId, args.projectId);const result = await routing.dispatchPkcs11<{ signature: string; keyId?: string }>({@@ -537,15 +543,12 @@ export const hsmConnectorServiceFactory = ({};const listHsmConnectorKeys = async (- dto: { connectorId: string; keyLabel: string },+ dto: { connectorId: string; projectId: 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);+ await assertProjectPermission(actor, dto.projectId, ProjectPermissionHsmConnectorActions.Attach);+ const { row, credentials } = await $loadConnector(dto.connectorId, dto.projectId);- const credentials = await $decryptCredentials(row);const result = await routing.dispatchPkcs11<{ keys: THsmConnectorKey[] }>({connector: { gatewayId: row.gatewayId, gatewayPoolId: row.gatewayPoolId },diff --git a/backend/src/services/signer/signer-dal.ts b/backend/src/services/signer/signer-dal.tsindex 14b00a523d..5e3f478108 100644--- a/backend/src/services/signer/signer-dal.ts+++ b/backend/src/services/signer/signer-dal.ts@@ -177,16 +177,18 @@ export const signerDALFactory = (db: TDbClient) => {}};- const findOneByCurrentHsmKey = async (- hsmConnectorId: string,+ const findOneInOrgByCurrentHsmPublicKey = async (+ projectId: string,hsmPublicKeySpki: Buffer,excludeSignerId: string | undefined,tx?: Knex): Promise<TPkiSigners | undefined> => {try {- let query = (tx || db.replicaNode())(TableName.PkiSigners)+ const conn = tx || db.replicaNode();+ let query = conn(TableName.PkiSigners).join(TableName.Certificate, `${TableName.PkiSigners}.certificateId`, `${TableName.Certificate}.id`)- .where(`${TableName.Certificate}.hsmConnectorId`, hsmConnectorId)+ .join(TableName.Project, `${TableName.PkiSigners}.projectId`, `${TableName.Project}.id`)+ .where(`${TableName.Project}.orgId`, conn(TableName.Project).select("orgId").where("id", projectId)).where(`${TableName.Certificate}.hsmPublicKeySpki`, hsmPublicKeySpki).select(selectAllTableCols(TableName.PkiSigners));if (excludeSignerId) {@@ -194,7 +196,7 @@ export const signerDALFactory = (db: TDbClient) => {}return (await query.first()) as TPkiSigners | undefined;} catch (error) {- throw new DatabaseError({ error, name: "FindSignerByCurrentHsmKey" });+ throw new DatabaseError({ error, name: "FindSignerInOrgByCurrentHsmPublicKey" });}};@@ -204,6 +206,6 @@ export const signerDALFactory = (db: TDbClient) => {findByStatusWithCertificate,findByProjectId,countByProjectId,- findOneByCurrentHsmKey+ findOneInOrgByCurrentHsmPublicKey};};diff --git a/backend/src/services/signer/signer-issuance-service.ts b/backend/src/services/signer/signer-issuance-service.tsindex 04e92b3a73..10f5c94c63 100644--- a/backend/src/services/signer/signer-issuance-service.ts+++ b/backend/src/services/signer/signer-issuance-service.ts@@ -410,19 +410,26 @@ export const signerIssuanceServiceFactory = ({);return;}- const rows = await signerIssuanceJobDAL.update(- { id: job.id, status: SignerIssuanceJobStatus.Pending },- {- nextPollAt: new Date(Date.now() + RETRY_BACKOFF_MS),- failureReason: reason+ await signerDAL.transaction(async (tx) => {+ const rows = await signerIssuanceJobDAL.update(+ { id: job.id, status: SignerIssuanceJobStatus.Pending },+ {+ nextPollAt: new Date(Date.now() + RETRY_BACKOFF_MS),+ failureReason: reason+ },+ tx+ );+ if (rows.length > 0) {+ await signerDAL.updateById(+ job.signerId,+ {+ status: SignerStatus.Pending,+ certificateFailureReason: reason+ },+ tx+ );}- );- if (rows.length > 0) {- await signerDAL.updateById(job.signerId, {- status: SignerStatus.Pending,- certificateFailureReason: reason- });- }+ });logger.error(err,`signer issuance: attempt failed, will retry [jobId=${job.id}] [signerId=${job.signerId}] [attempts=${job.attempts}/${job.maxAttempts}]`@@ -432,15 +439,24 @@ export const signerIssuanceServiceFactory = ({const markJobFailed = async (job: TPkiSignerCertificateIssuanceJobs, reason: string) => {const trimmed = reason.slice(0, 1000);- const rows = await signerIssuanceJobDAL.update(- { id: job.id, status: SignerIssuanceJobStatus.Pending },- { status: SignerIssuanceJobStatus.Failed, failureReason: trimmed }- );- if (rows.length === 0) return;- await signerDAL.updateById(job.signerId, {- status: SignerStatus.Failed,- certificateFailureReason: trimmed+ const markedFailed = await signerDAL.transaction(async (tx) => {+ const rows = await signerIssuanceJobDAL.update(+ { id: job.id, status: SignerIssuanceJobStatus.Pending },+ { status: SignerIssuanceJobStatus.Failed, failureReason: trimmed },+ tx+ );+ if (rows.length === 0) return false;+ await signerDAL.updateById(+ job.signerId,+ {+ status: SignerStatus.Failed,+ certificateFailureReason: trimmed+ },+ tx+ );+ return true;});+ if (!markedFailed) return;logger.info(`signer issuance: job marked Failed [jobId=${job.id}] [signerId=${job.signerId}] [reason=${trimmed.slice(0, 200)}]`);diff --git a/backend/src/services/signer/signer-service.ts b/backend/src/services/signer/signer-service.tsindex 823c7f780d..daf73da35b 100644--- a/backend/src/services/signer/signer-service.ts+++ b/backend/src/services/signer/signer-service.ts@@ -31,6 +31,7 @@ import {Pkcs11Mechanism,wrapRsaPkcs1DigestInfo} from "@app/lib/csr/pkcs11-algorithm-map";+import { DatabaseErrorCode } from "@app/lib/error-codes";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";@@ -180,7 +181,7 @@ type TSignerServiceFactoryDep = {| "revokeCertificate"| "assertCodeSigningOrderReusable"| "fetchIssuedCodeSigningCertificate"- | "downloadCodeSigningCertificate"+ | "prepareCodeSigningCertificate">;projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "encryptWithKmsKey" | "generateKmsKey">;@@ -488,14 +489,15 @@ export const signerServiceFactory = ({{ hsmConnectorId, projectId, hsmKeyLabel, hsmKeyId: requestedHsmKeyId, certificate });- const { certificateId } = await digicertFns.downloadCodeSigningCertificate({ caId, orderId, pemBundle });+ const preparedCertificate = await digicertFns.prepareCodeSigningCertificate({ caId, orderId, pemBundle });const validityDays = Math.round((certificate.notAfter.getTime() - certificate.notBefore.getTime()) / (24 * 60 * 60 * 1000));return {orderId,- certificateId,+ projectId,+ preparedCertificate,hsm: {keySource: CertKeySource.Hsm,hsmConnectorId,@@ -514,15 +516,19 @@ export const signerServiceFactory = ({signerId: string | undefined,tx: Knex) => {- await certificateDAL.findByIdForUpdate(imported.certificateId, tx);- const signerUsingCertificate = await signerDAL.findOne({ certificateId: imported.certificateId }, tx);+ const { preparedCertificate } = imported;+ const certificateId = preparedCertificate.insert+ ? await preparedCertificate.insert(tx)+ : preparedCertificate.existingCertificateId;+ await certificateDAL.findByIdForUpdate(certificateId, tx);+ const signerUsingCertificate = await signerDAL.findOne({ 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}'.`});}- const signerUsingKey = await signerDAL.findOneByCurrentHsmKey(- imported.hsm.hsmConnectorId,+ const signerUsingKey = await signerDAL.findOneInOrgByCurrentHsmPublicKey(+ imported.projectId,imported.hsm.hsmPublicKeySpki,signerId,tx@@ -532,7 +538,24 @@ export const signerServiceFactory = ({message: `The private key of the certificate in DigiCert order ${imported.orderId} is already used by another signer. Each signer needs its own key.`});}- await certificateDAL.updateById(imported.certificateId, imported.hsm, tx);+ await certificateDAL.updateById(certificateId, imported.hsm, tx);+ return certificateId;+ };++ const $rethrowConcurrentImport = async (+ error: unknown,+ imported: Awaited<ReturnType<typeof $importExistingDigiCertCertificate>> | null+ ) => {+ if (+ imported?.preparedCertificate.insert &&+ error instanceof DatabaseError &&+ (error.error as { code?: string })?.code === DatabaseErrorCode.UniqueViolation &&+ (await imported.preparedCertificate.findConcurrentInsert())+ ) {+ throw new ConflictError({+ message: `The certificate in DigiCert order ${imported.orderId} was attached to a signer by another request at the same time. Refresh and try again.`+ });+ }};const create = async (dto: TCreateSignerDTO) => {@@ -691,17 +714,15 @@ export const signerServiceFactory = ({});}- const finalCertificateId = usingExistingCert- ? (dto.certificateId as string)- : (importedCertificate?.certificateId ?? issuedCertificateId);+ const finalCertificateId = usingExistingCert ? (dto.certificateId as string) : 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 importedCertificateId = importedCertificate+ ? await $attachImportedCertificate(importedCertificate, undefined, tx)+ : null;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." });@@ -725,7 +746,7 @@ export const signerServiceFactory = ({projectId: dto.projectId,name: dto.name,description: dto.description,- certificateId: finalCertificateId,+ certificateId: importedCertificateId ?? finalCertificateId,caId: resolvedCaId,commonName: usingCa ? (importedCertificate?.commonName ?? dto.commonName) : null,certificateTtlDays: usingCa@@ -979,6 +1000,7 @@ export const signerServiceFactory = ({return result;} catch (error) {+ await $rethrowConcurrentImport(error, importedCertificate);// 23505 = unique constraint violationif (error instanceof DatabaseError && (error.error as { code?: string })?.code === "23505") {throw new BadRequestError({@@ -1455,28 +1477,33 @@ export const signerServiceFactory = ({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- );- });+ return signerDAL+ .transaction(async (tx) => {+ await signerIssuanceService.cancelOpenJobs(+ signer.id,+ "Superseded by an existing DigiCert certificate attached to the signer.",+ tx+ );+ const importedCertificateId = 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: importedCertificateId,+ status: SignerStatus.Active,+ certificateFailureReason: null+ },+ tx+ );+ })+ .catch(async (error: unknown) => {+ await $rethrowConcurrentImport(error, imported);+ throw error;+ });}const providedAdcsTemplate = reissueExternalConfig?.template?.trim() || undefined;diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsxindex d11c87908b..7685cfd489 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx@@ -167,6 +167,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =hsmKeyLabel: state.hsmKeyLabel,hsmKeyId: state.hsmKeyId,hsmKeyIdRequired: state.hsmKeyIdRequired,+ hsmKeyUnresolved: state.hsmKeyUnresolved,adcsTemplate: state.adcsTemplate}});@@ -198,6 +199,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =hsmKeyLabel: "",hsmKeyId: "",hsmKeyIdRequired: false,+ hsmKeyUnresolved: false,adcsTemplate: ""});};@@ -293,6 +295,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =hsmKeyLabel: values.hsmKeyLabel ?? "",hsmKeyId: values.hsmKeyId ?? "",hsmKeyIdRequired: values.hsmKeyIdRequired ?? false,+ hsmKeyUnresolved: values.hsmKeyUnresolved ?? false,adcsTemplate: values.adcsTemplate ?? ""}));};diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.tsindex 9b82d66e80..0af456f5d4 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts@@ -48,6 +48,7 @@ export const certificateSchema = zhsmKeyLabel: z.string().trim().max(128).optional().default(""),hsmKeyId: z.string().trim().max(256).optional().default(""),hsmKeyIdRequired: z.boolean().optional().default(false),+ hsmKeyUnresolved: z.boolean().optional().default(false),// AD CS only: the certificate template this signer requests when issuing.adcsTemplate: z.string().trim().optional().default("")})@@ -72,6 +73,10 @@ export const certificateSchema = z(data) => !isUsingExistingCertificate(data) || !data.hsmKeyIdRequired || Boolean(data.hsmKeyId),{ message: "Select which key to use.", path: ["hsmKeyId"] })+ .refine((data) => !isUsingExistingCertificate(data) || !data.hsmKeyUnresolved, {+ message: "Wait for the key lookup, or enter the label of a private key on the HSM.",+ path: ["hsmKeyLabel"]+ }).refine((data) =>data.keySource !== CertKeySource.Hsm ||diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.tsindex aad19498cd..c47163ed85 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts@@ -58,6 +58,7 @@ export type WizardState = {hsmKeyLabel: string;hsmKeyId: string;hsmKeyIdRequired: boolean;+ hsmKeyUnresolved: boolean;adcsTemplate: string;pendingMembers: PendingMember[];policySteps: PolicyStep[];@@ -80,6 +81,7 @@ export const INITIAL_WIZARD_STATE: WizardState = {hsmKeyLabel: "",hsmKeyId: "",hsmKeyIdRequired: false,+ hsmKeyUnresolved: false,adcsTemplate: "",pendingMembers: [],policySteps: [],diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsxindex a8bace5d6d..80d4dd85a7 100644--- a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx@@ -15,7 +15,7 @@ import {StepperList,StepperStep} from "@app/components/v3";-import { useCreateHsmConnector } from "@app/hooks/api/hsmConnectors";+import { THsmConnector, useCreateHsmConnector } from "@app/hooks/api/hsmConnectors";import { AccessStep } from "./AccessStep";import { BasicsStep } from "./BasicsStep";@@ -33,9 +33,10 @@ import { INITIAL_WIZARD_STATE, STEPS, WizardState } from "./types";type Props = {isOpen: boolean;onOpenChange: (open: boolean) => void;+ onCreated?: (connector: THsmConnector) => void;};-export const CreateHsmConnectorWizard = ({ isOpen, onOpenChange }: Props) => {+export const CreateHsmConnectorWizard = ({ isOpen, onOpenChange, onCreated }: Props) => {const [step, setStep] = useState(0);const [state, setState] = useState<WizardState>(INITIAL_WIZARD_STATE);const [submitting, setSubmitting] = useState(false);@@ -77,7 +78,7 @@ export const CreateHsmConnectorWizard = ({ isOpen, onOpenChange }: Props) => {setSubmitting(true);try {const [kind, id] = finalState.reachedFrom.split(":");- await createMutation.mutateAsync({+ const connector = await createMutation.mutateAsync({name: finalState.name,description: finalState.description.trim() || undefined,gatewayId: kind === "gateway" ? id : undefined,@@ -93,11 +94,9 @@ export const CreateHsmConnectorWizard = ({ isOpen, onOpenChange }: Props) => {text: `HSM Connector "${finalState.name}" created and verified.`});handleClose(false);- } catch (err) {- createNotification({- type: "error",- text: err instanceof Error ? err.message : "Failed to create HSM Connector"- });+ onCreated?.(connector);+ // eslint-disable-next-line no-empty+ } catch {} finally {setSubmitting(false);}diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsxindex 62b7bb9e96..acb7eeda10 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx@@ -139,6 +139,7 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {hsmKeyLabel: "",hsmKeyId: "",hsmKeyIdRequired: false,+ hsmKeyUnresolved: false,adcsTemplate: signerAdcsTemplate}});@@ -213,6 +214,7 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {hsmKeyLabel: "",hsmKeyId: "",hsmKeyIdRequired: false,+ hsmKeyUnresolved: false,adcsTemplate: signerAdcsTemplate});}diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.tsindex d8af2d788a..29f9b1c0cc 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts@@ -64,6 +64,7 @@ export const createCertificateSchema = (currentKey: TCurrentSignerKey) =>hsmKeyLabel: z.string().trim().max(128).optional().default(""),hsmKeyId: z.string().trim().max(256).optional().default(""),hsmKeyIdRequired: z.boolean().optional().default(false),+ hsmKeyUnresolved: z.boolean().optional().default(false),// AD CS only: the certificate template this signer requests when issuing.adcsTemplate: z.string().trim().optional().default("")})@@ -90,6 +91,10 @@ export const createCertificateSchema = (currentKey: TCurrentSignerKey) =>!isUsingExistingCertificate(data) || !data.hsmKeyIdRequired || Boolean(data.hsmKeyId),{ message: "Select which key to use.", path: ["hsmKeyId"] })+ .refine((data) => !isUsingExistingCertificate(data) || !data.hsmKeyUnresolved, {+ message: "Wait for the key lookup, or enter the label of a private key on the HSM.",+ path: ["hsmKeyLabel"]+ }).refine((data) =>data.keySource !== CertKeySource.Hsm ||diff --git a/frontend/src/pages/cert-manager/components/SignerKeyStep.tsx b/frontend/src/pages/cert-manager/components/SignerKeyStep.tsxindex cccc92140e..b4938b6331 100644--- a/frontend/src/pages/cert-manager/components/SignerKeyStep.tsx+++ b/frontend/src/pages/cert-manager/components/SignerKeyStep.tsx@@ -1,4 +1,4 @@-import { ReactNode, useEffect } from "react";+import { ReactNode, useEffect, useState } from "react";import { Control, Controller, useController, useWatch } from "react-hook-form";import { AxiosError } from "axios";import { AlertTriangleIcon, InfoIcon } from "lucide-react";@@ -36,15 +36,12 @@ import {SignerKeyAlgorithm,signerKeyAlgorithmLabels} from "@app/hooks/api/signers";+import { CreateHsmConnectorWizard } from "@app/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard";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)}`;+ key.keyAlgorithm ? `ID ${key.keyId} (${key.keyAlgorithm.replace("_", " ")})` : `ID ${key.keyId}`;export type HsmConnectorOption = { id: string; name: string; slotLabel: string };@@ -73,6 +70,11 @@ export const SignerKeyStep = ({ProjectPermissionHsmConnectorActions.Attach,ProjectPermissionSub.HsmConnectors);+ const canCreateHsmConnector = permission.can(+ ProjectPermissionHsmConnectorActions.Create,+ ProjectPermissionSub.HsmConnectors+ );+ const [isCreateHsmConnectorOpen, setIsCreateHsmConnectorOpen] = useState(false);const keySource = useWatch({ control, name: "keySource" });const isHsm = keySource === CertKeySource.Hsm;@@ -96,10 +98,12 @@ export const SignerKeyStep = ({fieldState: { error: hsmKeyIdError }} = useController({ control, name: "hsmKeyId" });const { field: hsmKeyIdRequiredField } = useController({ control, name: "hsmKeyIdRequired" });- const [debouncedKeyLabel] = useDebounce(((hsmKeyLabelField.value as string) ?? "").trim());+ const { field: hsmKeyUnresolvedField } = useController({ control, name: "hsmKeyUnresolved" });+ const typedKeyLabel = ((hsmKeyLabelField.value as string) ?? "").trim();+ const [debouncedKeyLabel] = useDebounce(typedKeyLabel);const {data: matchingHsmKeys,- isFetching: isHsmKeyLookupPending,+ isFetching: isHsmKeyLookupFetching,error: hsmKeyLookupError} = useListHsmConnectorKeys(hsmConnectorId, debouncedKeyLabel, {enabled: isHsm && usingExistingCertificate@@ -107,8 +111,16 @@ export const SignerKeyStep = ({const hsmKeyChoices = (matchingHsmKeys ?? []).filter((key) => Boolean(key.keyId));const canChooseHsmKey = (matchingHsmKeys?.length ?? 0) > 1 && hsmKeyChoices.length > 0;+ const isHsmKeyLookupPending =+ isHsmKeyLookupFetching || (Boolean(hsmConnectorId) && debouncedKeyLabel !== typedKeyLabel);+ useEffect(() => {+ hsmKeyUnresolvedField.onChange(isHsmKeyLookupPending || matchingHsmKeys?.length === 0);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [isHsmKeyLookupPending, matchingHsmKeys]);+useEffect(() => {const keys = matchingHsmKeys ?? [];+hsmKeyIdRequiredField.onChange(keys.length > 1 && keys.some((key) => Boolean(key.keyId)));if (keys.length === 1) {hsmKeyIdField.onChange(keys[0].keyId);@@ -123,7 +135,7 @@ export const SignerKeyStep = ({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 (ID ${matchingHsmKeys[0].keyId}).`: "Found the key.";} else if (matchingHsmKeys && matchingHsmKeys.length > 1) {hsmKeyLookupHint = canChooseHsmKey@@ -139,6 +151,11 @@ export const SignerKeyStep = ({hsmKeyLookupProblem = "No private key with this label in the connector's slot.";}+ const visibleHsmKeyLabelError = ((hsmKeyLabelField.value as string) ?? "").trim()+ ? undefined+ : hsmKeyLabelError;+ const visibleHsmKeyIdError = hsmKeyIdField.value ? undefined : hsmKeyIdError;+const isAlgorithmAllowed = (algo: SignerKeyAlgorithm): boolean => {if (algo === currentKeyAlgorithm) return true;if (isHsm && !HSM_SUPPORTED_KEY_ALGORITHMS.includes(algo)) return false;@@ -237,20 +254,35 @@ export const SignerKeyStep = ({options={hsmConnectorOptions}value={hsmConnectorOptions.find((o) => o.id === field.value) ?? null}onValueChange={(opt) => field.onChange(opt.id)}+ creation={+ canCreateHsmConnector+ ? {+ mode: "action",+ emptyLabel: "Add HSM Connector",+ formatLabel: () => "Add HSM Connector",+ onAction: () => setIsCreateHsmConnectorOpen(true)+ }+ : undefined+ }getOptionLabel={(opt) => `${opt.name} (slot ${opt.slotLabel})`}getOptionValue={(opt) => opt.id}placeholder="Select an HSM Connector..."searchPlaceholder="Search HSM Connectors..."searchAriaLabel="Search HSM Connectors"emptyMessage={- hsmConnectorOptions.length === 0- ? "No HSM Connectors configured. Add one in Settings → HSM Connectors."- : "No match."+ hsmConnectorOptions.length === 0 ? "No HSM Connectors configured." : "No match."}isError={Boolean(error)}/><FieldDescription>Which HSM connector to use.</FieldDescription><FieldError errors={[error]} />+ {canCreateHsmConnector && (+ <CreateHsmConnectorWizard+ isOpen={isCreateHsmConnectorOpen}+ onOpenChange={setIsCreateHsmConnectorOpen}+ onCreated={(connector) => field.onChange(connector.id)}+ />+ )}</FieldContent></Field>)}@@ -271,7 +303,8 @@ export const SignerKeyStep = ({<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.+ When off, a new key is generated on the HSM and DigiCert replaces the+ certificate in this order.</TooltipContent></Tooltip></div>@@ -280,8 +313,8 @@ export const SignerKeyStep = ({</FieldDescription>{field.value !== ExternalOrderMode.UseExisting && (<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.+ DigiCert revokes the order's current certificate within 72 hours of the+ replacement. After that, it can no longer be used to sign.</FieldDescription>)}</FieldContent>@@ -310,12 +343,12 @@ export const SignerKeyStep = ({{...hsmKeyLabelField}value={hsmKeyLabelField.value ?? ""}placeholder="acme-code-signing-2026"- isError={Boolean(hsmKeyLabelError || hsmKeyLookupProblem)}+ isError={Boolean(visibleHsmKeyLabelError || hsmKeyLookupProblem)}/><FieldDescription>{hsmKeyLookupHint}</FieldDescription><FieldErrorerrors={[- hsmKeyLabelError,+ visibleHsmKeyLabelError,hsmKeyLookupProblem ? { message: hsmKeyLookupProblem } : undefined]}/>@@ -330,7 +363,7 @@ export const SignerKeyStep = ({</FieldLabel><FieldContent><Select value={hsmKeyIdField.value || undefined} onValueChange={hsmKeyIdField.onChange}>- <SelectTrigger className="w-full" isError={Boolean(hsmKeyIdError)}>+ <SelectTrigger className="w-full" isError={Boolean(visibleHsmKeyIdError)}><SelectValue placeholder="Select a key..." /></SelectTrigger><SelectContent position="popper">@@ -342,7 +375,7 @@ export const SignerKeyStep = ({</SelectContent></Select><FieldDescription>The key's CKA_ID on the HSM.</FieldDescription>- <FieldError errors={[hsmKeyIdError]} />+ <FieldError errors={[visibleHsmKeyIdError]} /></FieldContent></Field>)}