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
Add DigiCert code-sign support
Carlos Monastyrski772c34df8363
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 9797132ac5..47abfb7e6d 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -4918,6 +4918,7 @@ interface CreatePkiSignerEvent {approvalPolicyId?: string | null;keySource?: CertKeySource;hsmConnectorId?: string | null;+ reissueFromExternalOrderId?: string | null;};}@@ -5006,6 +5007,7 @@ interface ReissuePkiSignerCertificateEvent {keySource?: string;hsmConnectorId?: string;hsmKeyAlgorithm?: string;+ reissueFromExternalOrderId?: string;};}diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex cfc47a237e..09755c873d 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -3319,6 +3319,7 @@ export const registerRoutes = async (certificateAuthorityDAL,signerIssuanceService,internalCertificateAuthorityService,+ digicertFns: digicertCaFns,projectDAL,kmsService,permissionService,diff --git a/backend/src/server/routes/v1/app-connection-routers/digicert-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/digicert-connection-router.tsindex 05ad021b4c..7975c7161d 100644--- a/backend/src/server/routes/v1/app-connection-routers/digicert-connection-router.ts+++ b/backend/src/server/routes/v1/app-connection-routers/digicert-connection-router.ts@@ -78,4 +78,77 @@ export const registerDigiCertConnectionRouter = async (server: FastifyZodProvidereturn server.services.appConnection.digicert.listProducts(connectionId, req.permission);}});++ server.route({+ method: "GET",+ url: `/:connectionId/organizations/:organizationId/code-signing-validation`,+ config: {+ rateLimit: readLimit+ },+ schema: {+ operationId: "getDigiCertOrgCodeSigningValidation",+ params: z.object({+ connectionId: z.string().uuid(),+ organizationId: z.coerce.number().int().positive()+ }),+ querystring: z.object({+ productNameId: z.string().trim().min(1)+ }),+ response: {+ 200: z.object({+ isValidated: z.boolean()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const { connectionId, organizationId } = req.params;+ const { productNameId } = req.query;+ return server.services.appConnection.digicert.getCodeSigningValidation(+ connectionId,+ organizationId,+ productNameId,+ req.permission+ );+ }+ });++ server.route({+ method: "GET",+ url: `/:connectionId/organizations/:organizationId/code-signing-orders`,+ config: {+ rateLimit: readLimit+ },+ schema: {+ operationId: "listDigiCertCodeSigningOrders",+ params: z.object({+ connectionId: z.string().uuid(),+ organizationId: z.coerce.number().int().positive()+ }),+ querystring: z.object({+ productNameId: z.string().trim().min(1)+ }),+ response: {+ 200: z+ .object({+ orderId: z.number(),+ commonName: z.string(),+ status: z.string(),+ validTill: z.string().optional()+ })+ .array()+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const { connectionId, organizationId } = req.params;+ const { productNameId } = req.query;+ return server.services.appConnection.digicert.listCodeSigningOrders(+ connectionId,+ organizationId,+ productNameId,+ req.permission+ );+ }+ });};diff --git a/backend/src/server/routes/v1/signer-routers/certificate-router.ts b/backend/src/server/routes/v1/signer-routers/certificate-router.tsindex 7f6aea752c..4d13d0496d 100644--- a/backend/src/server/routes/v1/signer-routers/certificate-router.ts+++ b/backend/src/server/routes/v1/signer-routers/certificate-router.ts@@ -32,7 +32,15 @@ export const registerSignerCertificateRouter = async (server: FastifyZodProviderkeySource: z.nativeEnum(CertKeySource),hsmConnectorId: z.string().uuid().optional()})+ .optional(),+ reissueFromExternalOrderId: z+ .string()+ .trim()+ .min(1).optional()+ .describe(+ "DigiCert code signing only: reissue into this existing order instead of placing a new order (reuses the subscription slot). Ignored by other CA types."+ )}).superRefine((data, ctx) => {if (data.certificate?.keySource !== CertKeySource.Hsm) return;@@ -76,7 +84,8 @@ export const registerSignerCertificateRouter = async (server: FastifyZodProvidercommonName: req.body.commonName,keyAlgorithm: req.body.keyAlgorithm,keySource: req.body.certificate?.keySource,- hsmConnectorId: req.body.certificate?.hsmConnectorId+ hsmConnectorId: req.body.certificate?.hsmConnectorId,+ reissueFromExternalOrderId: req.body.reissueFromExternalOrderId}}});diff --git a/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts b/backend/src/server/routes/v1/signer-routers/lifecycle-router.tsindex d730e156d9..dedda03be2 100644--- a/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts+++ b/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts@@ -45,6 +45,18 @@ export const registerSignerLifecycleRouter = async (server: FastifyZodProvider)hsmConnectorId: z.string().uuid().optional()}).optional(),+ externalConfiguration: z+ .object({+ reissueFromExternalOrderId: z+ .string()+ .trim()+ .min(1)+ .optional()+ .describe(+ "DigiCert code signing only: reissue into this existing order instead of placing a new order (reuses the subscription slot). Ignored by other CA types."+ )+ })+ .optional(),approvalPolicyId: z.string().uuid().optional(),members: z.array(@@ -100,7 +112,8 @@ export const registerSignerLifecycleRouter = async (server: FastifyZodProvider)certificateId: signer.certificateId,approvalPolicyId: signer.approvalPolicyId,keySource: req.body.certificate?.keySource,- hsmConnectorId: req.body.certificate?.hsmConnectorId+ hsmConnectorId: req.body.certificate?.hsmConnectorId,+ reissueFromExternalOrderId: req.body.externalConfiguration?.reissueFromExternalOrderId}}});diff --git a/backend/src/services/app-connection/digicert/digicert-connection-errors.ts b/backend/src/services/app-connection/digicert/digicert-connection-errors.tsindex 636324ec2c..9a4bf9d29e 100644--- a/backend/src/services/app-connection/digicert/digicert-connection-errors.ts+++ b/backend/src/services/app-connection/digicert/digicert-connection-errors.ts@@ -5,9 +5,10 @@ type TDigiCertErrorResponse = { errors?: { code?: string; message?: string }[] }export const extractDigiCertErrorMessage = (error: unknown) => {if (error instanceof AxiosError) {const data = error.response?.data as TDigiCertErrorResponse | undefined;- const firstError = data?.errors?.[0];- if (firstError?.message) {- return firstError.code ? `${firstError.message} (${firstError.code})` : firstError.message;+ // Include every error code, not just the first, so callers can match a code in any position.+ const errors = (data?.errors ?? []).filter((e) => e?.message || e?.code);+ if (errors.length) {+ return errors.map((e) => (e.code ? `${e.message ?? ""} (${e.code})` : e.message)).join("; ");}return error.message || "Unknown error";}diff --git a/backend/src/services/app-connection/digicert/digicert-connection-fns.ts b/backend/src/services/app-connection/digicert/digicert-connection-fns.tsindex f136db2efa..d0543b8d09 100644--- a/backend/src/services/app-connection/digicert/digicert-connection-fns.ts+++ b/backend/src/services/app-connection/digicert/digicert-connection-fns.ts@@ -23,8 +23,8 @@ export const getDigiCertConnectionListItem = () => {};};-export const getDigiCertApiBaseUrl = (region: DigiCertRegion): string => {- switch (region) {+export const getDigiCertApiBaseUrl = (input: { region: DigiCertRegion }): string => {+ switch (input.region) {case DigiCertRegion.EU:return IntegrationUrls.DIGICERT_SERVICES_API_URL_EU;case DigiCertRegion.US:@@ -35,7 +35,7 @@ export const getDigiCertApiBaseUrl = (region: DigiCertRegion): string => {export const validateDigiCertConnectionCredentials = async (config: TDigiCertConnectionConfig) => {const { credentials: inputCredentials } = config;- const baseUrl = getDigiCertApiBaseUrl(inputCredentials.region);+ const baseUrl = getDigiCertApiBaseUrl(inputCredentials);try {await request.get(`${baseUrl}/organization`, {@@ -70,8 +70,8 @@ type TDigiCertOrganizationsResponse = {export const listDigiCertOrganizations = async (appConnection: TDigiCertConnection): Promise<TDigiCertOrganization[]> => {- const { apiKey, region } = appConnection.credentials;- const baseUrl = getDigiCertApiBaseUrl(region);+ const { apiKey } = appConnection.credentials;+ const baseUrl = getDigiCertApiBaseUrl(appConnection.credentials);try {const { data } = await request.get<TDigiCertOrganizationsResponse>(`${baseUrl}/organization`, {@@ -97,6 +97,110 @@ export const listDigiCertOrganizations = async (}};+const DIGICERT_CS_VALIDATION_TYPE_BY_PRODUCT: Record<string, string> = {+ code_signing: "cs",+ code_signing_ev: "ev_cs"+};++type TDigiCertOrgValidationResponse = {+ validations?: { type?: string; status?: string }[];+};++export const isDigiCertOrgCodeSigningValidated = (+ validations: { type?: string; status?: string }[] | undefined,+ productNameId: string+): boolean => {+ const requiredType = DIGICERT_CS_VALIDATION_TYPE_BY_PRODUCT[productNameId] ?? "cs";+ return (validations ?? []).some(+ (validation) => validation.type === requiredType && (validation.status ?? "").toLowerCase() === "active"+ );+};++export const getDigiCertOrgCodeSigningValidation = async (+ appConnection: TDigiCertConnection,+ organizationId: number,+ productNameId: string+): Promise<{ isValidated: boolean }> => {+ const { apiKey } = appConnection.credentials;+ const baseUrl = getDigiCertApiBaseUrl(appConnection.credentials);++ try {+ const { data } = await request.get<TDigiCertOrgValidationResponse>(+ `${baseUrl}/organization/${organizationId}/validation`,+ {+ headers: {+ [DIGICERT_AUTH_HEADER]: apiKey,+ "Content-Type": "application/json"+ }+ }+ );++ return { isValidated: isDigiCertOrgCodeSigningValidated(data.validations, productNameId) };+ } catch (error: unknown) {+ if (error instanceof AxiosError) {+ throw new BadRequestError({+ message: `Failed to check DigiCert organization validation: ${extractDigiCertErrorMessage(error)}`+ });+ }+ throw error;+ }+};++type TDigiCertOrdersResponse = {+ orders?: {+ id: number;+ status?: string;+ certificate?: { common_name?: string; valid_till?: string };+ organization?: { name?: string };+ }[];+};++export type TDigiCertCodeSigningOrder = {+ orderId: number;+ commonName: string;+ status: string;+ validTill?: string;+};++export const listDigiCertCodeSigningOrders = async (+ appConnection: TDigiCertConnection,+ organizationId: number,+ productNameId: string+): Promise<TDigiCertCodeSigningOrder[]> => {+ const { apiKey } = appConnection.credentials;+ const baseUrl = getDigiCertApiBaseUrl(appConnection.credentials);++ try {+ const { data } = await request.get<TDigiCertOrdersResponse>(`${baseUrl}/order/certificate`, {+ headers: {+ [DIGICERT_AUTH_HEADER]: apiKey,+ "Content-Type": "application/json"+ },+ params: {+ "filters[product_name_id]": productNameId,+ "filters[organization_id]": organizationId,+ "filters[status]": "issued",+ limit: 1000+ }+ });++ return (data.orders ?? []).map((order) => ({+ orderId: order.id,+ // A code-signing cert's subject is the organization, so label the order by org name.+ commonName: order.organization?.name || order.certificate?.common_name || "",+ status: order.status ?? "",+ validTill: order.certificate?.valid_till+ }));+ } catch (error: unknown) {+ if (error instanceof AxiosError) {+ throw new BadRequestError({+ message: `Failed to list DigiCert code signing orders: ${extractDigiCertErrorMessage(error)}`+ });+ }+ throw error;+ }+};+type TDigiCertProductsResponse = {products: {name_id: string;@@ -107,11 +211,9 @@ type TDigiCertProductsResponse = {}[];};-const DIGICERT_SSL_PRODUCT_TYPE = "ssl_certificate";-export const listDigiCertProducts = async (appConnection: TDigiCertConnection): Promise<TDigiCertProduct[]> => {- const { apiKey, region } = appConnection.credentials;- const baseUrl = getDigiCertApiBaseUrl(region);+ const { apiKey } = appConnection.credentials;+ const baseUrl = getDigiCertApiBaseUrl(appConnection.credentials);try {const { data } = await request.get<TDigiCertProductsResponse>(`${baseUrl}/product`, {@@ -121,14 +223,12 @@ export const listDigiCertProducts = async (appConnection: TDigiCertConnection):}});- return (data.products ?? [])- .filter((product) => product.type === DIGICERT_SSL_PRODUCT_TYPE)- .map((product) => ({- nameId: product.name_id,- name: product.name,- type: product.type,- validationType: product.validation_type- }));+ return (data.products ?? []).map((product) => ({+ nameId: product.name_id,+ name: product.name,+ type: product.type,+ validationType: product.validation_type+ }));} catch (error: unknown) {if (error instanceof AxiosError) {throw new BadRequestError({diff --git a/backend/src/services/app-connection/digicert/digicert-connection-service.ts b/backend/src/services/app-connection/digicert/digicert-connection-service.tsindex adc7fcc03f..94784eba4a 100644--- a/backend/src/services/app-connection/digicert/digicert-connection-service.ts+++ b/backend/src/services/app-connection/digicert/digicert-connection-service.ts@@ -2,7 +2,12 @@ import { logger } from "@app/lib/logger";import { OrgServiceActor } from "@app/lib/types";import { AppConnection } from "../app-connection-enums";-import { listDigiCertOrganizations, listDigiCertProducts } from "./digicert-connection-fns";+import {+ getDigiCertOrgCodeSigningValidation,+ listDigiCertCodeSigningOrders,+ listDigiCertOrganizations,+ listDigiCertProducts+} from "./digicert-connection-fns";import { TDigiCertConnection } from "./digicert-connection-types";type TGetAppConnectionFunc = (@@ -32,8 +37,40 @@ export const digicertConnectionService = (getAppConnection: TGetAppConnectionFun}};+ const getCodeSigningValidation = async (+ connectionId: string,+ organizationId: number,+ productNameId: string,+ actor: OrgServiceActor+ ) => {+ const appConnection = await getAppConnection(AppConnection.DigiCert, connectionId, actor);+ try {+ return await getDigiCertOrgCodeSigningValidation(appConnection, organizationId, productNameId);+ } catch (error) {+ logger.error(error, `Failed to check DigiCert code signing validation [connectionId=${connectionId}]`);+ return { isValidated: false };+ }+ };++ const listCodeSigningOrders = async (+ connectionId: string,+ organizationId: number,+ productNameId: string,+ actor: OrgServiceActor+ ) => {+ const appConnection = await getAppConnection(AppConnection.DigiCert, connectionId, actor);+ try {+ return await listDigiCertCodeSigningOrders(appConnection, organizationId, productNameId);+ } catch (error) {+ logger.error(error, `Failed to list DigiCert code signing orders [connectionId=${connectionId}]`);+ return [];+ }+ };+return {listOrganizations,- listProducts+ listProducts,+ getCodeSigningValidation,+ listCodeSigningOrders};};diff --git a/backend/src/services/certificate-authority/digicert/digicert-api-client.ts b/backend/src/services/certificate-authority/digicert/digicert-api-client.tsindex 95056f1b84..97684e22cc 100644--- a/backend/src/services/certificate-authority/digicert/digicert-api-client.ts+++ b/backend/src/services/certificate-authority/digicert/digicert-api-client.ts@@ -1,14 +1,16 @@import { AxiosError } from "axios";import { request } from "@app/lib/config/request";-import { BadRequestError } from "@app/lib/errors";+import { BadRequestError, InternalServerError } from "@app/lib/errors";import { DIGICERT_AUTH_HEADER } from "@app/services/app-connection/digicert/digicert-connection-constants";import { extractDigiCertErrorMessage } from "@app/services/app-connection/digicert/digicert-connection-errors";import {TCheckValidationResponse,+ TDigiCertAlternateOrdersResponse,TOrderResponse,TOrderStatusChangesResponse,+ TOrganizationValidationsResponse,TPlaceOrderRequest,TPlaceOrderResponse} from "./digicert-certificate-authority-types";@@ -24,21 +26,36 @@ export const createDigiCertApiClient = (apiKey: string, baseURL: string) => {const wrap = <T>(fn: () => Promise<T>, action: string) =>fn().catch((error: unknown) => {if (error instanceof AxiosError) {- throw new BadRequestError({- message: `DigiCert ${action} failed: ${extractDigiCertErrorMessage(error)}`+ const status = error.response?.status;+ // 4xx (except 408/429) is terminal; everything else is transient and retried by the poller.+ if (status && status >= 400 && status < 500 && status !== 408 && status !== 429) {+ throw new BadRequestError({+ message: `DigiCert ${action} failed: ${extractDigiCertErrorMessage(error)}`+ });+ }+ // Throw a sanitized error, never the raw AxiosError whose config headers carry the API key.+ throw new InternalServerError({+ message: `DigiCert ${action} failed${status ? ` (status ${status})` : " (no response)"}`});}throw error;});- const placeOrder = async (productSlug: string, body: TPlaceOrderRequest) =>+ const placeOrder = async <TResp = TPlaceOrderResponse>(+ productSlug: string,+ body: TPlaceOrderRequest | Record<string, unknown>+ ) =>wrap(async () => {- const { data } = await request.post<TPlaceOrderResponse>(`${baseURL}/order/certificate/${productSlug}`, body, {- headers- });+ const { data } = await request.post<TResp>(`${baseURL}/order/certificate/${productSlug}`, body, { headers });return data;}, `order placement for product ${productSlug}`);+ const reissueOrder = async <TResp = TPlaceOrderResponse>(orderId: number, body: Record<string, unknown>) =>+ wrap(async () => {+ const { data } = await request.post<TResp>(`${baseURL}/order/certificate/${orderId}/reissue`, body, { headers });+ return data;+ }, `order reissue for ${orderId}`);+const getOrder = async (orderId: number) =>wrap(async () => {const { data } = await request.get<TOrderResponse>(`${baseURL}/order/certificate/${orderId}`, {@@ -67,6 +84,24 @@ export const createDigiCertApiClient = (apiKey: string, baseURL: string) => {return data;}, `certificate download for ${certificateId}`);+ const getOrganizationValidations = async (organizationId: number) =>+ wrap(async () => {+ const { data } = await request.get<TOrganizationValidationsResponse>(+ `${baseURL}/organization/${organizationId}/validation`,+ { headers }+ );+ return data;+ }, `organization validation lookup for ${organizationId}`);++ const getOrdersByAlternativeId = async (alternativeOrderId: string) =>+ wrap(async () => {+ const { data } = await request.get<TDigiCertAlternateOrdersResponse>(+ `${baseURL}/order/alternate/${encodeURIComponent(alternativeOrderId)}`,+ { headers }+ );+ return data;+ }, `alternate order lookup for ${alternativeOrderId}`);+const revokeOrder = async (orderId: number, comments: string) =>wrap(async () => {await request.put(`${baseURL}/order/certificate/${orderId}/revoke`, { comments }, { headers });@@ -84,9 +119,12 @@ export const createDigiCertApiClient = (apiKey: string, baseURL: string) => {return {placeOrder,+ reissueOrder,getOrder,checkValidation,+ getOrganizationValidations,downloadCertificatePem,+ getOrdersByAlternativeId,revokeOrder,listOrderStatusChanges};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 7bb2bacca1..564fd3712e 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@@ -12,7 +12,10 @@ import { TAppConnectionDALFactory } from "@app/services/app-connection/app-conneimport { AppConnection } from "@app/services/app-connection/app-connection-enums";import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";-import { getDigiCertApiBaseUrl } from "@app/services/app-connection/digicert/digicert-connection-fns";+import {+ getDigiCertApiBaseUrl,+ isDigiCertOrgCodeSigningValidated+} from "@app/services/app-connection/digicert/digicert-connection-fns";import { TDigiCertConnection } from "@app/services/app-connection/digicert/digicert-connection-types";import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";@@ -36,10 +39,17 @@ import {DigiCertOrderStatus,DigiCertPollOutcome} from "./digicert-certificate-authority-enums";+import { DigiCertCaPurpose } from "./digicert-certificate-authority-schemas";import {+ TCodeSigningOrderInfo,+ TCodeSigningOrderStatus,TCreateDigiCertCertificateAuthorityDTO,TDigiCertCertificateAuthority,TDigiCertCertificateRequestMetadata,+ TPlaceCodeSigningOrderRequest,+ TPlaceCodeSigningOrderResponse,+ TPlaceOrderResponse,+ TReissueCodeSigningOrderRequest,TUpdateDigiCertCertificateAuthorityDTO} from "./digicert-certificate-authority-types";@@ -77,6 +87,14 @@ export const castDbEntryToDigiCertCertificateAuthority = (const config = (ca.externalCa.configuration ?? {}) as {organizationId?: number;productNameId?: string;+ purpose?: DigiCertCaPurpose;+ verifiedContact?: {+ firstName: string;+ lastName: string;+ email: string;+ jobTitle: string;+ telephone: string;+ };};if (typeof config.organizationId !== "number" || !config.productNameId) {@@ -85,6 +103,8 @@ export const castDbEntryToDigiCertCertificateAuthority = (});}+ const purpose = config.purpose ?? DigiCertCaPurpose.Ssl;+return {id: ca.id,type: CaType.DIGICERT,@@ -95,7 +115,9 @@ export const castDbEntryToDigiCertCertificateAuthority = (configuration: {appConnectionId: ca.externalCa.appConnectionId,organizationId: config.organizationId,- productNameId: config.productNameId+ productNameId: config.productNameId,+ purpose,+ verifiedContact: config.verifiedContact},status: ca.status as CaStatus};@@ -123,10 +145,26 @@ export const getDigiCertClientCredentials = async (return {apiKey: credentials.apiKey,- baseUrl: getDigiCertApiBaseUrl(credentials.region)+ baseUrl: getDigiCertApiBaseUrl(credentials)};};+const DIGICERT_CS_PRODUCT_NAME_IDS = new Set(["code_signing", "code_signing_ev"]);++const assertPurposeMatchesProduct = (purpose: DigiCertCaPurpose, productNameId: string): void => {+ const isCsProduct = DIGICERT_CS_PRODUCT_NAME_IDS.has(productNameId);+ if (purpose === DigiCertCaPurpose.CodeSigning && !isCsProduct) {+ throw new BadRequestError({+ message: `Product '${productNameId}' is not a code-signing product. Pick one of: ${[...DIGICERT_CS_PRODUCT_NAME_IDS].join(", ")}`+ });+ }+ if (purpose === DigiCertCaPurpose.Ssl && isCsProduct) {+ throw new BadRequestError({+ message: `Product '${productNameId}' is a code-signing product but this CA is configured for SSL`+ });+ }+};+const PEM_CERTIFICATE_RE2 = new RE2("-----BEGIN CERTIFICATE-----[\\s\\S]*?-----END CERTIFICATE-----", "g");const TTL_RE2 = new RE2("^(\\d+)([dhm])$");@@ -197,6 +235,43 @@ export const DigiCertCertificateAuthorityFns = ({kmsService,projectDAL}: TDigiCertCertificateAuthorityFnsDeps) => {+ // DigiCert only requires a verified contact for the first code-signing order against an org it+ // hasn't validated yet; check upfront so the error surfaces at CA setup, not at issuance.+ const assertCsOrgValidatedOrContactProvided = async ({+ appConnectionId,+ organizationId,+ productNameId,+ verifiedContact+ }: {+ appConnectionId: string;+ organizationId: number;+ productNameId: string;+ verifiedContact?: unknown;+ }): Promise<void> => {+ if (verifiedContact) return;++ let isValidated = false;+ try {+ const { apiKey, baseUrl } = await getDigiCertClientCredentials(appConnectionId, appConnectionDAL, kmsService);+ const client = createDigiCertApiClient(apiKey, baseUrl);+ const { validations } = await client.getOrganizationValidations(organizationId);+ isValidated = isDigiCertOrgCodeSigningValidated(validations, productNameId);+ } catch (err) {+ logger.warn(+ err,+ `DigiCert org validation pre-check failed [organizationId=${organizationId}] — allowing without a verified contact`+ );+ return;+ }++ if (!isValidated) {+ throw new BadRequestError({+ message:+ "This DigiCert organization has not completed code signing validation yet. Add a verified contact (first name, last name, email, job title, telephone) so DigiCert can start organization validation."+ });+ }+ };+const createCertificateAuthority = async ({name,projectId,@@ -210,7 +285,7 @@ export const DigiCertCertificateAuthorityFns = ({configuration: TCreateDigiCertCertificateAuthorityDTO["configuration"];actor: OrgServiceActor;}) => {- const { appConnectionId, organizationId, productNameId } = configuration;+ const { appConnectionId, organizationId, productNameId, purpose, verifiedContact } = configuration;const appConnection = await appConnectionDAL.findById(appConnectionId);if (!appConnection) {@@ -228,6 +303,12 @@ export const DigiCertCertificateAuthorityFns = ({actor);+ assertPurposeMatchesProduct(purpose ?? DigiCertCaPurpose.Ssl, productNameId);++ if ((purpose ?? DigiCertCaPurpose.Ssl) === DigiCertCaPurpose.CodeSigning) {+ await assertCsOrgValidatedOrContactProvided({ appConnectionId, organizationId, productNameId, verifiedContact });+ }+const caEntity = await certificateAuthorityDAL.transaction(async (tx) => {try {const ca = await certificateAuthorityDAL.create(@@ -247,7 +328,9 @@ export const DigiCertCertificateAuthorityFns = ({type: CaType.DIGICERT,configuration: {organizationId,- productNameId+ productNameId,+ purpose: purpose ?? DigiCertCaPurpose.Ssl,+ ...(verifiedContact ? { verifiedContact } : {})}},tx@@ -286,9 +369,20 @@ export const DigiCertCertificateAuthorityFns = ({actor: OrgServiceActor;name?: string;}) => {+ // Network call (org validation lookup) must run outside the DB transaction.+ if (configuration && (configuration.purpose ?? DigiCertCaPurpose.Ssl) === DigiCertCaPurpose.CodeSigning) {+ assertPurposeMatchesProduct(DigiCertCaPurpose.CodeSigning, configuration.productNameId);+ await assertCsOrgValidatedOrContactProvided({+ appConnectionId: configuration.appConnectionId,+ organizationId: configuration.organizationId,+ productNameId: configuration.productNameId,+ verifiedContact: configuration.verifiedContact+ });+ }+const updatedCa = await certificateAuthorityDAL.transaction(async (tx) => {if (configuration) {- const { appConnectionId, organizationId, productNameId } = configuration;+ const { appConnectionId, organizationId, productNameId, purpose, verifiedContact } = configuration;const appConnection = await appConnectionDAL.findById(appConnectionId);if (!appConnection) {throw new NotFoundError({ message: `DigiCert app connection with ID '${appConnectionId}' not found` });@@ -310,6 +404,9 @@ export const DigiCertCertificateAuthorityFns = ({actor);+ const resolvedPurpose = purpose ?? DigiCertCaPurpose.Ssl;+ assertPurposeMatchesProduct(resolvedPurpose, productNameId);+await externalCertificateAuthorityDAL.update({caId: id,@@ -319,7 +416,9 @@ export const DigiCertCertificateAuthorityFns = ({appConnectionId,configuration: {organizationId,- productNameId+ productNameId,+ purpose: resolvedPurpose,+ ...(verifiedContact ? { verifiedContact } : {})}},tx@@ -463,9 +562,9 @@ export const DigiCertCertificateAuthorityFns = ({"cannot_renew_expired_order","product_not_eligible_for_renewal"];- let orderResponse: Awaited<ReturnType<typeof client.placeOrder>>;+ let orderResponse: TPlaceOrderResponse;try {- orderResponse = await client.placeOrder(productNameId, {+ orderResponse = await client.placeOrder<TPlaceOrderResponse>(productNameId, {...baseOrderPayload,...(renewalOfOrderId ? { renewal_of_order_id: renewalOfOrderId } : {})});@@ -477,7 +576,7 @@ export const DigiCertCertificateAuthorityFns = ({logger.warn(`DigiCert rejected renewal linkage (renewal_of_order_id=${renewalOfOrderId}) as not eligible; retrying as a fresh order [caId=${caId}]`);- orderResponse = await client.placeOrder(productNameId, baseOrderPayload);+ orderResponse = await client.placeOrder<TPlaceOrderResponse>(productNameId, baseOrderPayload);} else {throw err;}@@ -721,6 +820,289 @@ export const DigiCertCertificateAuthorityFns = ({);};+ const normalizeCodeSigningStatus = (raw: string): TCodeSigningOrderStatus => {+ const s = (raw || "").toLowerCase();+ if (s === "issued") return "issued";+ if (s === "rejected" || s === "canceled" || s === "expired" || s === "revoked") return s;+ if (+ s === "pending" ||+ s === "processing" ||+ s === "needs_approval" ||+ s === "waiting_pickup" ||+ s === "reissue_pending"+ ) {+ return s === "needs_approval" || s === "processing" ? s : "pending";+ }+ logger.warn(`DigiCert returned unrecognized CS order status [status=${raw}] — treating as pending`);+ return "pending";+ };++ // 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;++ // server_platform.id=-1 ("Other") is DigiCert's value for the customer-supplied-CSR lane.+ 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"];++ const loadDigiCertCsContext = async (caId: string, opts?: { requireCodeSigning?: boolean }) => {+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);+ if (!ca.externalCa || ca.externalCa.type !== CaType.DIGICERT) {+ throw new BadRequestError({ message: "CA is not a DigiCert certificate authority" });+ }+ const digicertCa = castDbEntryToDigiCertCertificateAuthority(ca);+ if (opts?.requireCodeSigning) {+ if (digicertCa.status !== CaStatus.ACTIVE) {+ throw new BadRequestError({ message: `DigiCert CA is disabled [caId=${caId}]` });+ }+ if (digicertCa.configuration.purpose !== DigiCertCaPurpose.CodeSigning) {+ throw new BadRequestError({+ message: `DigiCert CA '${digicertCa.name}' is configured for SSL, not code signing.`+ });+ }+ if (!DIGICERT_CS_PRODUCT_NAME_IDS.has(digicertCa.configuration.productNameId)) {+ throw new BadRequestError({+ message: `DigiCert CA points at product '${digicertCa.configuration.productNameId}' which is not a code-signing product.`+ });+ }+ }+ const { apiKey, baseUrl } = await getDigiCertClientCredentials(+ digicertCa.configuration.appConnectionId,+ appConnectionDAL,+ kmsService+ );+ return { ca, digicertCa, client: createDigiCertApiClient(apiKey, baseUrl) };+ };++ const orderCodeSigningCertificate = async ({+ caId,+ csr,+ commonName,+ signatureHash,+ ttlDays,+ renewalOfOrderId,+ alternativeOrderId,+ comments+ }: {+ caId: string;+ csr: string;+ commonName: string;+ signatureHash: "sha256" | "sha384" | "sha512";+ ttlDays: number;+ renewalOfOrderId?: number;+ alternativeOrderId?: string;+ comments?: string;+ }): Promise<{ orderId: number; certificateId: number | null }> => {+ if (ttlDays > MAX_CS_VALIDITY_DAYS) {+ throw new BadRequestError({+ message: `DigiCert code signing certificates are capped at ${MAX_CS_VALIDITY_DAYS} days of validity. Reduce the signer's validity period.`+ });+ }++ const { digicertCa, client } = await loadDigiCertCsContext(caId, { requireCodeSigning: true });+ const { productNameId } = digicertCa.configuration;++ const { verifiedContact } = digicertCa.configuration;+ const payload: TPlaceCodeSigningOrderRequest = {+ certificate: {+ common_name: commonName,+ csr,+ signature_hash: signatureHash,+ server_platform: { id: CS_SERVER_PLATFORM_OTHER }+ },+ organization: {+ id: digicertCa.configuration.organizationId,+ ...(verifiedContact+ ? {+ contacts: [+ {+ contact_type: "verified_contact" as const,+ first_name: verifiedContact.firstName,+ last_name: verifiedContact.lastName,+ email: verifiedContact.email,+ job_title: verifiedContact.jobTitle,+ telephone: verifiedContact.telephone+ }+ ]+ }+ : {})+ },+ order_validity: { days: ttlDays },+ cs_provisioning_method: "email",+ skip_approval: true,+ ...(alternativeOrderId ? { alternative_order_id: alternativeOrderId } : {}),+ ...(comments ? { comments } : {})+ };++ let resp: TPlaceCodeSigningOrderResponse;+ try {+ resp = await client.placeOrder<TPlaceCodeSigningOrderResponse>(productNameId, {+ ...payload,+ ...(renewalOfOrderId ? { renewal_of_order_id: renewalOfOrderId } : {})+ });+ } catch (err) {+ const message = (err as Error)?.message ?? "";+ const isRenewalIneligible =+ renewalOfOrderId !== undefined && CS_RENEWAL_INELIGIBLE_CODES.some((code) => message.includes(code));+ if (!isRenewalIneligible) throw err;+ logger.warn(+ `DigiCert rejected CS renewal linkage (renewal_of_order_id=${renewalOfOrderId}) as not eligible; retrying as a fresh order [caId=${caId}]`+ );+ resp = await client.placeOrder<TPlaceCodeSigningOrderResponse>(productNameId, payload);+ }+ return { orderId: resp.id, certificateId: resp.certificate_id ?? null };+ };++ const reissueCodeSigningCertificate = async ({+ caId,+ previousOrderId,+ csr,+ signatureHash,+ comments+ }: {+ caId: string;+ previousOrderId: number;+ csr: string;+ signatureHash: "sha256" | "sha384" | "sha512";+ comments?: string;+ }): Promise<{ orderId: number; certificateId: number | null }> => {+ const { digicertCa, client } = await loadDigiCertCsContext(caId, { requireCodeSigning: true });++ // The account-wide API key can see orders across orgs/products, so confirm this order belongs to+ // the CA's org and product before reissuing into it (strict: a missing field fails closed).+ 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 reissuePayload: TReissueCodeSigningOrderRequest = {+ certificate: {+ csr,+ signature_hash: signatureHash,+ server_platform: { id: CS_SERVER_PLATFORM_OTHER }+ },+ cs_provisioning_method: "email",+ skip_approval: true,+ ...(comments ? { comments } : {})+ };++ const resp = await client.reissueOrder<TPlaceCodeSigningOrderResponse>(previousOrderId, reissuePayload);+ return { orderId: resp.id ?? previousOrderId, certificateId: resp.certificate_id ?? null };+ };++ // Finds an order previously placed with the given alternative_order_id, so a retry after a crash+ // (order placed at DigiCert but its id not yet persisted) adopts it instead of placing a duplicate.+ const findCodeSigningOrderByReference = async (+ caId: string,+ reference: string+ ): Promise<{ orderId: number; certificateId: number | null } | null> => {+ const { client } = await loadDigiCertCsContext(caId, { requireCodeSigning: true });+ const { orders } = await client.getOrdersByAlternativeId(reference);+ const match = (orders ?? [])[0];+ return match ? { orderId: match.order_id, certificateId: match.certificate_id ?? null } : null;+ };++ const getCodeSigningOrderStatus = async (caId: string, orderId: number): Promise<TCodeSigningOrderInfo> => {+ const { client } = await loadDigiCertCsContext(caId);+ const order = await client.getOrder(orderId);+ return {+ id: orderId,+ status: normalizeCodeSigningStatus(order.status),+ certificateId: order.certificate?.id ?? null,+ rawStatus: order.status+ };+ };++ const downloadCodeSigningCertificate = async ({+ caId,+ orderId,+ digicertCertificateId,+ keyAlgorithm,+ signatureAlgorithm,+ applicationId,+ profileId+ }: {+ caId: string;+ orderId: number;+ digicertCertificateId: number;+ 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);+ const { leaf, chain } = extractLeafAndChain(pemBundle);++ const certObj = new x509.X509Certificate(leaf);+ const issued = extractIssuedCertificateFields(certObj);++ const existingCert = await certificateDAL.findOne({ caId: ca.id, serialNumber: certObj.serialNumber });+ if (existingCert) {+ return { certificateId: existingCert.id, certificatePem: leaf };+ }++ const certificateManagerKmsId = await getProjectKmsCertificateKeyId({+ projectId: ca.projectId,+ projectDAL,+ kmsService+ });+ const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: certificateManagerKmsId });+ const { cipherTextBlob: encryptedCertificate } = await kmsEncryptor({+ plainText: Buffer.from(new Uint8Array(certObj.rawData))+ });+ const { cipherTextBlob: encryptedCertificateChain } = await kmsEncryptor({+ plainText: Buffer.from(chain)+ });++ const createdCertificateId = await certificateDAL.transaction(async (tx) => {+ const cert = await certificateDAL.create(+ {+ caId: ca.id,+ applicationId: applicationId ?? undefined,+ profileId: profileId ?? undefined,+ status: CertStatus.ACTIVE,+ friendlyName: issued.commonName || "",+ commonName: issued.commonName || "",+ altNames: issued.altNames.length > 0 ? issued.altNames.join(",") : "",+ serialNumber: certObj.serialNumber,+ notBefore: certObj.notBefore,+ notAfter: certObj.notAfter,+ keyUsages: issued.keyUsages,+ extendedKeyUsages: issued.extendedKeyUsages,+ keyAlgorithm: keyAlgorithm ?? undefined,+ signatureAlgorithm: signatureAlgorithm ?? undefined,+ projectId: ca.projectId,+ externalMetadata: {+ type: CaType.DIGICERT,+ orderId+ } satisfies TDigiCertExternalMetadata+ },+ tx+ );++ await certificateBodyDAL.create(+ {+ certId: cert.id,+ encryptedCertificate,+ encryptedCertificateChain+ },+ tx+ );++ return cert.id;+ });++ return { certificateId: createdCertificateId, certificatePem: leaf };+ };+return {createCertificateAuthority,updateCertificateAuthority,@@ -728,7 +1110,12 @@ export const DigiCertCertificateAuthorityFns = ({orderCertificate,fetchAndAttachIssuedCertificate,pollOrderForCertificate,- revokeCertificate+ revokeCertificate,+ orderCodeSigningCertificate,+ reissueCodeSigningCertificate,+ findCodeSigningOrderByReference,+ getCodeSigningOrderStatus,+ downloadCodeSigningCertificate};};diff --git a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.ts b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.tsindex 9323cba5b1..ea75b65cc3 100644--- a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.ts+++ b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.ts@@ -91,7 +91,7 @@ const getOrCreateClient = async (kmsService: deps.kmsService})) as TDigiCertConnection["credentials"];- const client = createDigiCertApiClient(credentials.apiKey, getDigiCertApiBaseUrl(credentials.region));+ const client = createDigiCertApiClient(credentials.apiKey, getDigiCertApiBaseUrl(credentials));clientCache?.set(request.caId, client);return client;};diff --git a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-schemas.ts b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-schemas.tsindex 462b9dab42..a4358bb336 100644--- a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-schemas.ts+++ b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-schemas.ts@@ -7,6 +7,11 @@ import {GenericUpdateCertificateAuthorityFieldsSchema} from "../certificate-authority-schemas";+export enum DigiCertCaPurpose {+ Ssl = "ssl",+ CodeSigning = "code_signing"+}+export const DigiCertCertificateAuthorityConfigurationSchema = z.object({appConnectionId: z.string().uuid().trim().describe("DigiCert App Connection ID"),organizationId: z@@ -19,8 +24,22 @@ export const DigiCertCertificateAuthorityConfigurationSchema = z.object({.trim().min(1).describe(- "The DigiCert product name_id used for issuance (e.g. ssl_plus, ssl_ev_plus). Fetch available products from GET /app-connections/digicert/:id/products."- )+ "The DigiCert product name_id used for issuance (e.g. ssl_plus, code_signing, code_signing_ev). Fetch available products from GET /app-connections/digicert/:id/products."+ ),+ purpose: z+ .nativeEnum(DigiCertCaPurpose)+ .optional()+ .describe("Whether this CA issues SSL/TLS or code-signing certificates (defaults to ssl)"),+ verifiedContact: z+ .object({+ firstName: z.string().trim().min(1).max(128),+ lastName: z.string().trim().min(1).max(128),+ email: z.string().trim().email().max(255),+ jobTitle: z.string().trim().min(1).max(64),+ telephone: z.string().trim().min(1).max(32)+ })+ .optional()+ .describe("Contact info for the user who approves first-time CS orders for the organization")});export const DigiCertCertificateAuthoritySchema = BaseCertificateAuthoritySchema.extend({diff --git a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-types.ts b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-types.tsindex 5363e8eec1..ff7d8be2c6 100644--- a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-types.ts+++ b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-types.ts@@ -53,6 +53,8 @@ export type TOrderResponse = {certificate?: {id: number;};+ organization?: { id?: number };+ product?: { name_id?: string };dcv_method?: string;};@@ -73,3 +75,73 @@ export type TOrderStatusChangesResponse = {status: string;}[];};++export type TDigiCertOrderContact = {+ contact_type: "verified_contact";+ first_name: string;+ last_name: string;+ email: string;+ job_title: string;+ telephone: string;+};++export type TPlaceCodeSigningOrderRequest = {+ certificate: {+ common_name: string;+ csr: string;+ signature_hash?: "sha256" | "sha384" | "sha512";+ server_platform?: { id: number };+ };+ organization: {+ id: number;+ contacts?: TDigiCertOrderContact[];+ };+ order_validity: { days: number } | { years: number };+ cs_provisioning_method: "email";+ skip_approval?: boolean;+ renewal_of_order_id?: number;+ // Idempotency token: lets a retried placement be recovered instead of duplicated.+ alternative_order_id?: string;+ comments?: string;+};++export type TReissueCodeSigningOrderRequest = {+ certificate: {+ csr: string;+ signature_hash?: "sha256" | "sha384" | "sha512";+ server_platform?: { id: number };+ };+ cs_provisioning_method: "email";+ skip_approval?: boolean;+ comments?: string;+};++export type TPlaceCodeSigningOrderResponse = {+ id: number;+ certificate_id?: number | null;+};++export type TDigiCertAlternateOrdersResponse = {+ orders?: { order_id: number; certificate_id?: number | null; status?: string }[];+};++export type TCodeSigningOrderStatus =+ | "pending"+ | "needs_approval"+ | "processing"+ | "issued"+ | "rejected"+ | "canceled"+ | "expired"+ | "revoked";++export type TCodeSigningOrderInfo = {+ id: number;+ status: TCodeSigningOrderStatus;+ certificateId: number | null;+ rawStatus: string;+};++export type TOrganizationValidationsResponse = {+ validations?: { type: string; status?: string; validated_until?: string }[];+};diff --git a/backend/src/services/signer/signer-issuance-job-dal.ts b/backend/src/services/signer/signer-issuance-job-dal.tsindex a01dce2ac1..0d2c3849c6 100644--- a/backend/src/services/signer/signer-issuance-job-dal.ts+++ b/backend/src/services/signer/signer-issuance-job-dal.ts@@ -62,5 +62,19 @@ export const signerIssuanceJobDALFactory = (db: TDbClient) => {}};- return { ...orm, findDuePending, cancelOpenForSigner, claimForAttempt };+ const findLatestForSigner = async (+ signerId: string,+ tx?: Knex+ ): Promise<TPkiSignerCertificateIssuanceJobs | undefined> => {+ try {+ return await (tx || db.replicaNode())(TableName.PkiSignerCertificateIssuanceJobs)+ .where({ signerId })+ .orderBy("createdAt", "desc")+ .first();+ } catch (error) {+ throw new DatabaseError({ error, name: "FindLatestSignerIssuanceJob" });+ }+ };++ return { ...orm, findDuePending, cancelOpenForSigner, claimForAttempt, findLatestForSigner };};diff --git a/backend/src/services/signer/signer-issuance-service.ts b/backend/src/services/signer/signer-issuance-service.tsindex d0852d6e77..774ad29510 100644--- a/backend/src/services/signer/signer-issuance-service.ts+++ b/backend/src/services/signer/signer-issuance-service.ts@@ -11,7 +11,12 @@ import { logger } from "@app/lib/logger";import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";import { TCertificateDALFactory } from "../certificate/certificate-dal";import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-dal";-import { CertExtendedKeyUsage, CertKeyAlgorithm, CertKeyUsage } from "../certificate/certificate-types";+import {+ CertExtendedKeyUsage,+ CertKeyAlgorithm,+ CertKeyUsage,+ CertSignatureAlgorithm+} from "../certificate/certificate-types";import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";import { CaStatus, CaType } from "../certificate-authority/certificate-authority-enums";import { keyAlgorithmToAlgCfg } from "../certificate-authority/certificate-authority-fns";@@ -30,7 +35,41 @@ import { TSignerIssuanceJobDALFactory } from "./signer-issuance-job-dal";const POLL_INTERVAL_PATTERN = "*/15 * * * *"; // every 15 minutesconst POLL_BATCH = 25;const RETRY_BACKOFF_MS = 15 * 60_000;-const MAX_ISSUANCE_WINDOW_MS = 24 * 60 * 60 * 1000;++// DigiCert CS orders can sit pending for up to 3 business days while DigiCert validates the org and+// waits for the verified-contact email click, so they get a longer window than synchronous CAs.+const DEFAULT_ISSUANCE_WINDOW_MS = 24 * 60 * 60 * 1000;+const DIGICERT_ISSUANCE_WINDOW_MS = 5 * 24 * 60 * 60 * 1000;++const maxIssuanceWindowMs = (caType: string): number =>+ caType === CaType.DIGICERT ? DIGICERT_ISSUANCE_WINDOW_MS : DEFAULT_ISSUANCE_WINDOW_MS;++const deriveDigicertSignatureParams = (+ keyAlgorithm: string+): { signatureHash: "sha256" | "sha384" | "sha512"; signatureAlgorithm: CertSignatureAlgorithm } => {+ switch (keyAlgorithm) {+ case CertKeyAlgorithm.ECDSA_P256:+ return { signatureHash: "sha256", signatureAlgorithm: CertSignatureAlgorithm.ECDSA_SHA256 };+ case CertKeyAlgorithm.ECDSA_P384:+ return { signatureHash: "sha384", signatureAlgorithm: CertSignatureAlgorithm.ECDSA_SHA384 };+ case CertKeyAlgorithm.ECDSA_P521:+ return { signatureHash: "sha512", signatureAlgorithm: CertSignatureAlgorithm.ECDSA_SHA512 };+ default:+ return { signatureHash: "sha256", signatureAlgorithm: CertSignatureAlgorithm.RSA_SHA256 };+ }+};++const DIGICERT_INSUFFICIENT_SUBSCRIPTION = "insufficient_subscription";++type TDigiCertExternalOrderRef = {+ digicert?: {+ orderId?: number;+ certificateId?: number | null;+ lastStatus?: string;+ lastCheckedAt?: string;+ lifecycle?: { mode: "renew" | "reissue"; previousOrderId: number };+ };+};export type TSignerIssuanceServiceFactory = ReturnType<typeof signerIssuanceServiceFactory>;@@ -42,10 +81,10 @@ type TSignerIssuanceServiceDeps = {certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create" | "updateById">;projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "decryptWithKmsKey" | "generateKmsKey">;- certificateIssuanceQueue: Pick<TCertificateIssuanceQueueFactory, "awsPcaFns" | "azureAdCsFns">;+ certificateIssuanceQueue: Pick<TCertificateIssuanceQueueFactory, "awsPcaFns" | "azureAdCsFns" | "digicertFns">;cronJob: TCronJobFactory;hsmConnectorService: Pick<THsmConnectorServiceFactory, "generateKeyPair" | "sign" | "assertAttachPermission">;- certificateDAL: Pick<TCertificateDALFactory, "updateById">;+ certificateDAL: Pick<TCertificateDALFactory, "updateById" | "findById">;};type TRequestIssuanceInput = {@@ -62,6 +101,8 @@ type TRequestIssuanceInput = {hsmPublicKeySpki?: Buffer;actor?: Pick<THsmConnectorServiceActor, "type" | "id" | "authMethod" | "orgId">;};+ // DigiCert code signing only; absent means a fresh order.+ digicertLifecycle?: { mode: "renew" | "reissue"; previousOrderId: number };};export const signerIssuanceServiceFactory = ({@@ -77,7 +118,7 @@ export const signerIssuanceServiceFactory = ({hsmConnectorService,certificateDAL}: TSignerIssuanceServiceDeps) => {- const { awsPcaFns, azureAdCsFns } = certificateIssuanceQueue;+ const { awsPcaFns, azureAdCsFns, digicertFns } = certificateIssuanceQueue;const buildCsrForSigner = async (commonName: string,@@ -135,6 +176,17 @@ export const signerIssuanceServiceFactory = ({});}+ if (caType === CaType.DIGICERT && !input.hsm) {+ throw new BadRequestError({+ message:+ "DigiCert code signing requires an HSM-backed key. Industry rules require code signing private keys to be generated and stored on certified hardware. Choose an HSM key source for this signer."+ });+ }++ const digicertExternalOrderRef = input.digicertLifecycle+ ? { digicert: { lifecycle: input.digicertLifecycle } }+ : undefined;+if (input.hsm) {if (input.hsm.actor) {await hsmConnectorService.assertAttachPermission(input.hsm.actor, input.hsm.hsmConnectorId, input.projectId);@@ -190,6 +242,7 @@ export const signerIssuanceServiceFactory = ({hsmConnectorId: input.hsm!.hsmConnectorId,hsmKeyLabel: keyLabel,hsmPublicKeySpki: publicKeySpkiDer,+ externalOrderRef: digicertExternalOrderRef,nextPollAt: new Date()},tx@@ -258,11 +311,13 @@ export const signerIssuanceServiceFactory = ({const now = new Date();+ const windowMs = maxIssuanceWindowMs(snapshot.caType);const ageMs = now.getTime() - new Date(snapshot.createdAt).getTime();- if (ageMs > MAX_ISSUANCE_WINDOW_MS) {+ if (ageMs > windowMs) {+ const hours = Math.round(windowMs / (60 * 60 * 1000));await markJobFailedIfStillPending(snapshot,- "Signer issuance was pending for more than 24 hours. The upstream Certificate Authority never finished issuing the certificate; abandoning."+ `Signer issuance was pending for more than ${hours} hours. The upstream Certificate Authority never finished issuing the certificate; abandoning.`);return;}@@ -302,10 +357,13 @@ export const signerIssuanceServiceFactory = ({case CaType.AWS_PCA:await stepSyncWithCsr(job, CaType.AWS_PCA);break;+ case CaType.DIGICERT:+ await stepSyncWithDigiCert(job);+ break;default:await markJobFailed(job,- `CA type '${job.caType}' is not supported for code signing. Choose Internal CA, AWS Private CA, or Azure AD CS.`+ `CA type '${job.caType}' is not supported for code signing. Choose Internal CA, AWS Private CA, Azure AD CS, or DigiCert.`);}} catch (err) {@@ -385,6 +443,9 @@ export const signerIssuanceServiceFactory = ({}const isHsmJob = job.keySource === CertKeySource.Hsm && job.hsmConnectorId && job.hsmKeyLabel;+ // 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);try {await signerDAL.transaction(async (tx) => {if (isHsmJob) {@@ -406,7 +467,8 @@ export const signerIssuanceServiceFactory = ({{certificateId,status: SignerStatus.Active,- certificateFailureReason: null+ certificateFailureReason: null,+ ...(issuedCert?.commonName ? { commonName: issuedCert.commonName } : {})},tx);@@ -491,6 +553,152 @@ export const signerIssuanceServiceFactory = ({await attachIssuedCertToSigner(job, certificateId, projectId);};+ const stepSyncWithDigiCert = async (job: TPkiSignerCertificateIssuanceJobs) => {+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(job.caId);+ if (!ca) {+ await markJobFailed(job, "Certificate authority is no longer available.");+ return;+ }+ const { projectId } = ca;++ const ref = (job.externalOrderRef ?? {}) as TDigiCertExternalOrderRef;+ const existingOrderId = ref.digicert?.orderId;+ const lifecycle = ref.digicert?.lifecycle;++ const persistPlacedOrder = async (orderId: number, certificateId: number | null) => {+ await signerIssuanceJobDAL.updateById(job.id, {+ externalOrderRef: {+ digicert: { orderId, certificateId, lastStatus: "pending", lastCheckedAt: new Date().toISOString() }+ }+ });+ logger.info(+ `signer issuance: DigiCert order placed [jobId=${job.id}] [signerId=${job.signerId}] [orderId=${orderId}]`+ );+ };++ if (!existingOrderId) {+ const csr = (await decryptForProject(projectId, Buffer.from(job.encryptedCsr as Buffer))).toString();+ const comments = `Issued via Infisical signer ${job.signerId}`;+ const { signatureHash } = deriveDigicertSignatureParams(job.keyAlgorithm);++ if (lifecycle?.mode === "reissue") {+ const placed = await digicertFns.reissueCodeSigningCertificate({+ caId: job.caId,+ previousOrderId: lifecycle.previousOrderId,+ csr,+ signatureHash,+ comments+ });+ await persistPlacedOrder(placed.orderId, placed.certificateId);+ return;+ }++ // The alternative_order_id is deterministic per job, so placement is idempotent: if a prior+ // tick placed the order but crashed before persisting it, recover it instead of placing a+ // second (billable) order.+ const placementRef = `infisical-signer-job-${job.id}`;+ const recovered = await digicertFns.findCodeSigningOrderByReference(job.caId, placementRef);+ if (recovered) {+ logger.info(+ `signer issuance: recovered previously-placed DigiCert order [jobId=${job.id}] [orderId=${recovered.orderId}]`+ );+ await persistPlacedOrder(recovered.orderId, recovered.certificateId);+ return;+ }++ let placed: { orderId: number; certificateId: number | null };+ if (lifecycle?.mode === "renew") {+ try {+ placed = await digicertFns.orderCodeSigningCertificate({+ caId: job.caId,+ csr,+ commonName: job.commonName,+ signatureHash,+ ttlDays: job.certificateTtlDays,+ renewalOfOrderId: lifecycle.previousOrderId,+ alternativeOrderId: placementRef,+ comments+ });+ } catch (err) {+ if (!(err as Error)?.message?.includes(DIGICERT_INSUFFICIENT_SUBSCRIPTION)) throw err;+ logger.info(+ `signer issuance: DigiCert renewal had no free subscription slot; reissuing into prior order [jobId=${job.id}] [orderId=${lifecycle.previousOrderId}]`+ );+ placed = await digicertFns.reissueCodeSigningCertificate({+ caId: job.caId,+ previousOrderId: lifecycle.previousOrderId,+ csr,+ signatureHash,+ comments+ });+ }+ } else {+ placed = await digicertFns.orderCodeSigningCertificate({+ caId: job.caId,+ csr,+ commonName: job.commonName,+ signatureHash,+ ttlDays: job.certificateTtlDays,+ alternativeOrderId: placementRef,+ comments+ });+ }+ await persistPlacedOrder(placed.orderId, placed.certificateId);+ return;+ }++ const info = await digicertFns.getCodeSigningOrderStatus(job.caId, existingOrderId);+ await signerIssuanceJobDAL.updateById(job.id, {+ externalOrderRef: {+ digicert: {+ orderId: existingOrderId,+ certificateId: info.certificateId,+ lastStatus: info.status,+ lastCheckedAt: new Date().toISOString()+ }+ }+ });++ if (+ info.status === "rejected" ||+ info.status === "canceled" ||+ info.status === "expired" ||+ info.status === "revoked"+ ) {+ await markJobFailed(+ job,+ `DigiCert order ${info.status} (raw status: ${info.rawStatus}). Order id ${existingOrderId}.`+ );+ return;+ }++ if (info.status !== "issued") {+ logger.info(+ `signer issuance: DigiCert order still pending [jobId=${job.id}] [signerId=${job.signerId}] [orderId=${existingOrderId}] [status=${info.status}]`+ );+ return;+ }++ if (!info.certificateId) {+ logger.warn(+ `signer issuance: DigiCert reports issued but no certificate id yet — will retry [jobId=${job.id}] [orderId=${existingOrderId}]`+ );+ return;+ }++ const { signatureAlgorithm } = deriveDigicertSignatureParams(job.keyAlgorithm);+ const { certificateId } = await digicertFns.downloadCodeSigningCertificate({+ caId: job.caId,+ orderId: existingOrderId,+ digicertCertificateId: info.certificateId,+ keyAlgorithm: job.keyAlgorithm,+ signatureAlgorithm+ });++ await persistCertificatePrivateKey(certificateId, projectId, job);+ await attachIssuedCertToSigner(job, certificateId, projectId);+ };+const persistCertificatePrivateKey = async (certificateId: string,projectId: string,@@ -541,9 +749,23 @@ export const signerIssuanceServiceFactory = ({});};+ // Recovers key config from the last job when retrying a signer that never produced a certificate.+ const getLatestIssuanceKeyConfig = async (signerId: string) => {+ const job = await signerIssuanceJobDAL.findLatestForSigner(signerId);+ if (!job) return null;+ return {+ keySource: job.keySource as CertKeySource,+ keyAlgorithm: job.keyAlgorithm as CertKeyAlgorithm,+ hsmConnectorId: job.hsmConnectorId ?? null,+ hsmKeyLabel: job.hsmKeyLabel ?? null,+ hsmPublicKeySpki: job.hsmPublicKeySpki ?? null+ };+ };+return {requestIssuance,processJob,+ getLatestIssuanceKeyConfig,start};};diff --git a/backend/src/services/signer/signer-service.ts b/backend/src/services/signer/signer-service.tsindex a7c9fcb40f..d58315ee02 100644--- a/backend/src/services/signer/signer-service.ts+++ b/backend/src/services/signer/signer-service.ts@@ -45,9 +45,10 @@ import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal"import { TCertificateDALFactory } from "../certificate/certificate-dal";import { getCertificateCredentials } from "../certificate/certificate-fns";import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-dal";-import { CertExtendedKeyUsage, CertKeyAlgorithm, CertStatus } from "../certificate/certificate-types";+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 { TInternalCertificateAuthorityServiceFactory } from "../certificate-authority/internal/internal-certificate-authority-service";import { TKmsServiceFactory } from "../kms/kms-service";import { TMembershipDALFactory } from "../membership/membership-dal";@@ -84,14 +85,14 @@ import { TSigningOperationDALFactory } from "./signing-operation-dal";const MAX_DATA_BYTES = 128;const DEFAULT_CERTIFICATE_TTL_DAYS = 365;-const CODE_SIGNING_SUPPORTED_EXTERNAL_CA_TYPES = new Set<CaType>([CaType.AWS_PCA, CaType.AZURE_AD_CS]);+const CODE_SIGNING_SUPPORTED_EXTERNAL_CA_TYPES = new Set<CaType>([CaType.AWS_PCA, CaType.AZURE_AD_CS, CaType.DIGICERT]);const assertCaTypeSupportsCodeSigning = (caType: CaType): void => {if (caType === CaType.INTERNAL) return;if (!CODE_SIGNING_SUPPORTED_EXTERNAL_CA_TYPES.has(caType)) {throw new BadRequestError({message:- "Code signing is only supported on Internal CAs, AWS Private CA, and Azure AD CS. Pick a different certificate authority."+ "Code signing is only supported on Internal CAs, AWS Private CA, Azure AD CS, and DigiCert. Pick a different certificate authority."});}};@@ -121,8 +122,9 @@ type TSignerServiceFactoryDep = {certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create">;certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;- signerIssuanceService: Pick<TSignerIssuanceServiceFactory, "requestIssuance">;+ signerIssuanceService: Pick<TSignerIssuanceServiceFactory, "requestIssuance" | "getLatestIssuanceKeyConfig">;internalCertificateAuthorityService: Pick<TInternalCertificateAuthorityServiceFactory, "signCertFromCa">;+ digicertFns: Pick<TDigiCertCertificateAuthorityFns, "revokeCertificate">;projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "encryptWithKmsKey" | "generateKmsKey">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;@@ -215,7 +217,10 @@ export const resolveReissueTarget = ({Boolean(currentCert.hsmConnectorId) &&Boolean(currentCert.keyAlgorithm);const overrideKeySource = dto.certificate?.keySource;- const switchingKeySource = overrideKeySource !== undefined && overrideKeySource !== currentCert?.keySource;+ // An algorithm change needs a fresh key, so treat it like a key source switch.+ const changingKeyAlgorithm = dto.keyAlgorithm !== undefined && dto.keyAlgorithm !== currentCert?.keyAlgorithm;+ const switchingKeySource =+ (overrideKeySource !== undefined && overrideKeySource !== currentCert?.keySource) || changingKeyAlgorithm;const targetIsHsm = overrideKeySource ? overrideKeySource === CertKeySource.Hsm : currentIsHsm;if (targetIsHsm) {@@ -244,6 +249,7 @@ export const signerServiceFactory = ({certificateAuthorityDAL,signerIssuanceService,internalCertificateAuthorityService,+ digicertFns,projectDAL,kmsService,permissionService,@@ -350,6 +356,22 @@ export const signerServiceFactory = ({if (resolvedCaType) assertCaTypeSupportsCodeSigning(resolvedCaType);+ let createDigicertLifecycle: { mode: "reissue"; previousOrderId: number } | undefined;+ const reissueFromExternalOrderId = dto.externalConfiguration?.reissueFromExternalOrderId;+ 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." });+ }+ createDigicertLifecycle = { mode: "reissue", previousOrderId };+ }+const isExternalCa = resolvedCaType !== null && resolvedCaType !== CaType.INTERNAL;if (resolvedCaType === CaType.AZURE_AD_CS && dto.certificate?.keySource === CertKeySource.Hsm) {@@ -669,6 +691,7 @@ export const signerServiceFactory = ({commonName: dto.commonName as string,certificateTtlDays: dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS,keyAlgorithm,+ digicertLifecycle: createDigicertLifecycle,hsm:certificateInput?.keySource === CertKeySource.Hsm && certificateInput.hsmConnectorId? {@@ -863,6 +886,32 @@ export const signerServiceFactory = ({ResourcePermissionSub.Signer);+ // Revoke the DigiCert order so a deleted signer can't leave a live publicly-trusted cert behind.+ // Best-effort and outside the deletion transaction so a DigiCert outage can't block the delete.+ if (existingSigner.caId && existingSigner.certificateId) {+ try {+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(existingSigner.caId);+ if (ca?.externalCa?.type === CaType.DIGICERT) {+ const cert = await certificateDAL.findById(existingSigner.certificateId);+ if (cert?.serialNumber && cert.status !== CertStatus.REVOKED) {+ await digicertFns.revokeCertificate({+ caId: existingSigner.caId,+ serialNumber: cert.serialNumber,+ reason: CrlReason.CESSATION_OF_OPERATION+ });+ logger.info(+ `signer delete: revoked DigiCert order for deleted signer [signerId=${existingSigner.id}] [certificateId=${cert.id}]`+ );+ }+ }+ } catch (err) {+ logger.error(+ err,+ `signer delete: failed to revoke DigiCert order for signer '${existingSigner.name}' [signerId=${existingSigner.id}] [certificateId=${existingSigner.certificateId}] — deletion will proceed; revoke the order manually in CertCentral`+ );+ }+ }+await signerDAL.transaction(async (tx) => {const memberships = await membershipDAL.find({@@ -968,6 +1017,20 @@ export const signerServiceFactory = ({assertCaTypeSupportsCodeSigning(reissueCaType);const reissueIsExternal = reissueCaType !== CaType.INTERNAL;+ let explicitReissueOrderId: number | undefined;+ if (dto.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(dto.reissueFromExternalOrderId);+ if (!Number.isInteger(explicitReissueOrderId) || explicitReissueOrderId <= 0) {+ throw new BadRequestError({ message: "reissueFromExternalOrderId must be a valid DigiCert order id." });+ }+ }+const allowsResubject = signer.status === SignerStatus.Pending || signer.status === SignerStatus.Failed;let nextCommonName = signer.commonName;let nextTtl = signer.certificateTtlDays;@@ -994,10 +1057,25 @@ export const signerServiceFactory = ({}const reissueCurrentCert = signer.certificateId ? await certificateDAL.findById(signer.certificateId) : null;++ // A never-issued signer has no cert to read the key config from; recover it from the last job so+ // an HSM signer keeps its key source instead of falling back to software and being rejected.+ const recoveredKeyConfig = reissueCurrentCert+ ? null+ : await signerIssuanceService.getLatestIssuanceKeyConfig(signer.id);+const target = resolveReissueTarget({dto,signer,- currentCert: reissueCurrentCert+ currentCert:+ reissueCurrentCert ??+ (recoveredKeyConfig+ ? {+ keySource: recoveredKeyConfig.keySource,+ keyAlgorithm: recoveredKeyConfig.keyAlgorithm,+ hsmConnectorId: recoveredKeyConfig.hsmConnectorId+ }+ : null)});if (reissueCaType === CaType.AZURE_AD_CS && target.isHsm) {@@ -1029,8 +1107,12 @@ export const signerServiceFactory = ({? {hsmConnectorId: target.hsmConnectorId,hsmKeyAlgorithm: target.hsmKeyAlgorithm,- hsmKeyLabel: switchingKeySource ? undefined : (reissueCurrentCert?.hsmKeyLabel ?? undefined),- hsmPublicKeySpki: switchingKeySource ? undefined : (reissueCurrentCert?.hsmPublicKeySpki ?? undefined),+ hsmKeyLabel: switchingKeySource+ ? undefined+ : (reissueCurrentCert?.hsmKeyLabel ?? recoveredKeyConfig?.hsmKeyLabel ?? undefined),+ hsmPublicKeySpki: switchingKeySource+ ? undefined+ : (reissueCurrentCert?.hsmPublicKeySpki ?? recoveredKeyConfig?.hsmPublicKeySpki ?? undefined),actor: {type: dto.actor,id: dto.actorId,@@ -1043,6 +1125,10 @@ export const signerServiceFactory = ({status: SignerStatus.Pending,certificateFailureReason: null});+ const reissueDigicertOrderId =+ reissueCaType === CaType.DIGICERT+ ? (explicitReissueOrderId ?? (reissueCurrentCert?.externalMetadata as { orderId?: number } | null)?.orderId)+ : undefined;try {await signerIssuanceService.requestIssuance({signerId: signer.id,@@ -1051,7 +1137,10 @@ export const signerServiceFactory = ({commonName: nextCommonName,certificateTtlDays: nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS,keyAlgorithm: targetKeyAlgorithm,- hsm: reissueHsm+ hsm: reissueHsm,+ digicertLifecycle: reissueDigicertOrderId+ ? { mode: "reissue", previousOrderId: reissueDigicertOrderId }+ : undefined});return await signerDAL.findById(dto.signerId);} catch (queueErr) {@@ -1680,6 +1769,10 @@ export const signerServiceFactory = ({status: SignerStatus.Pending,certificateFailureReason: null});+ const autoRenewDigicertOrderId =+ renewalCaType === CaType.DIGICERT+ ? (autoRenewCert?.externalMetadata as { orderId?: number } | null)?.orderId+ : undefined;try {await signerIssuanceService.requestIssuance({signerId: signer.id,@@ -1688,7 +1781,10 @@ export const signerServiceFactory = ({commonName: signer.commonName,certificateTtlDays: ttlDays,keyAlgorithm: renewKeyAlgorithm,- hsm: autoRenewHsm+ hsm: autoRenewHsm,+ digicertLifecycle: autoRenewDigicertOrderId+ ? { mode: "renew", previousOrderId: autoRenewDigicertOrderId }+ : undefined});} catch (err) {await signerDAL.updateById(signer.id, {diff --git a/backend/src/services/signer/signer-types.ts b/backend/src/services/signer/signer-types.tsindex 54cda2deea..dd7add0621 100644--- a/backend/src/services/signer/signer-types.ts+++ b/backend/src/services/signer/signer-types.ts@@ -22,6 +22,11 @@ export type TSignerCertificateInput = {hsmConnectorId?: string;};+export type TSignerExternalConfigurationInput = {+ // DigiCert code signing only: reissue into this existing order instead of placing a new one.+ reissueFromExternalOrderId?: string;+};+export type TCreateSignerDTO = {name: string;description?: string;@@ -35,6 +40,7 @@ export type TCreateSignerDTO = {members?: TCreateSignerMemberInput[];approvalPolicy?: TCreateSignerApprovalPolicyInput;certificate?: TSignerCertificateInput;+ externalConfiguration?: TSignerExternalConfigurationInput;} & TProjectPermission;export type TUpdateSignerDTO = {@@ -97,6 +103,8 @@ export type TReissueCertificateDTO = {certificateTtlDays?: number;keyAlgorithm?: CertKeyAlgorithm;certificate?: TSignerCertificateInput;+ // DigiCert code signing only: reissue into this existing order instead of placing a new order.+ reissueFromExternalOrderId?: string;} & TActorPermission;export type TExportCertificateDTO = {diff --git a/docs/documentation/platform/pki/ca/digicert-direct.mdx b/docs/documentation/platform/pki/ca/digicert-direct.mdxindex a8af284247..e46e0fc089 100644--- a/docs/documentation/platform/pki/ca/digicert-direct.mdx+++ b/docs/documentation/platform/pki/ca/digicert-direct.mdx@@ -1,17 +1,20 @@---title: "DigiCert (CertCentral Services API)"-description: "Issue OV/EV certificates from DigiCert using the CertCentral Services API with manual DNS validation."+description: "Issue TLS or Code Signing certificates from DigiCert using the CertCentral Services API."---## Concept-Infisical can issue OV and EV TLS certificates directly from [DigiCert CertCentral](https://www.digicert.com/) using the [CertCentral Services API](https://dev.digicert.com/en/certcentral-apis/services-api.html).+Infisical can issue certificates directly from [DigiCert CertCentral](https://www.digicert.com/) using the [CertCentral Services API](https://dev.digicert.com/en/certcentral-apis/services-api.html). A single DigiCert CA in Infisical is configured for one purpose:++- **SSL/TLS** — issues OV and EV TLS server certificates under an SSL product entitlement on your account (for example `ssl_plus`).+- **Code Signing** — issues OV (`code_signing`) and EV (`code_signing_ev`) code-signing certificates against a CSR. The signing key must live on an HSM.## Prerequisites- A [DigiCert App Connection](/integrations/app-connections/digicert) with a validated CertCentral API key.-- A CertCentral **Organization** that has been pre-validated by DigiCert-- Entitlement to either the OV or EV SSL product on your CertCentral account.+- A CertCentral **Organization**. For code signing, DigiCert validates the organization the first time it is used for a code-signing order, which can take up to 3 business days.+- Entitlement to the product you intend to use (`ssl_plus`, `code_signing`, `code_signing_ev`, ...) on your CertCentral account.## Create a DigiCert Certificate Authority@@ -26,14 +29,16 @@ Infisical can issue OV and EV TLS certificates directly from [DigiCert CertCentr- **App Connection** — the DigiCert connection you created- **Organization** — the CertCentral organization that should appear on issued certificates+ - **Purpose** — `SSL / TLS` or `Code Signing`. The product list filters accordingly.- **Product** — the CertCentral entitlement this CA will issue under+ - **Verified Contact** (Code Signing only) — full contact info for the person DigiCert emails to approve first-time code-signing orders for this organization. All five fields required: **First Name**, **Last Name**, **Email**, **Job Title**, **Telephone** (E.164, e.g. `+15551234567`). DigiCert requires `job_title` and `telephone` on every verified contact for CS orders; referencing an existing CertCentral user by id alone is not enough. Once the organization has an active CS validation on file, DigiCert ignores this field.</Step></Steps></Tab><Tab title="API">To create a DigiCert Certificate Authority, make an API request to the [Create DigiCert CA](/api-reference/endpoints/certificate-authorities/digicert/create) API endpoint.- ```bash Create a DigiCert CA+ ```bash Create a DigiCert CA (SSL)curl --request POST \--url https://app.infisical.com/api/v1/pki/ca/digicert \--header 'Content-Type: application/json' \@@ -43,13 +48,58 @@ Infisical can issue OV and EV TLS certificates directly from [DigiCert CertCentr"configuration": {"appConnectionId": "<digicert-app-connection-id>","organizationId": 112236,- "productNameId": "ssl_plus"+ "productNameId": "ssl_plus",+ "purpose": "ssl"+ }+ }'+ ```++ ```bash Create a DigiCert CA (Code Signing)+ curl --request POST \+ --url https://app.infisical.com/api/v1/pki/ca/digicert \+ --header 'Content-Type: application/json' \+ --data '{+ "name": "digicert-cs",+ "status": "active",+ "configuration": {+ "appConnectionId": "<digicert-app-connection-id>",+ "organizationId": 112236,+ "productNameId": "code_signing",+ "purpose": "code_signing",+ "verifiedContact": {+ "firstName": "John",+ "lastName": "Doe",+ "email": "[email protected]",+ "jobTitle": "Security Engineer",+ "telephone": "+15551234567"+ }}}'```</Tab></Tabs>+## Using a DigiCert Code Signing CA++Once a CA is configured with `purpose: "code_signing"`, it appears in the **Code Signing → Create Signer** wizard's CA picker. The Signer is created in **Pending** state while DigiCert processes the order, and flips to **Active** once the certificate issues.++DigiCert's CS workflow includes an out-of-band step for first orders against a new organization: DigiCert emails the organization's verified contact a link they must click to approve the order. This step cannot be skipped by the API. Subsequent orders against the same already-validated organization go from `pending` to `issued` without human action.++<Note>+ Code-signing certificates require an HSM-backed key. When you select a DigiCert code-signing CA, the Signer wizard locks the key source to **HSM** and you must pick an [HSM Connector](/documentation/platform/pki/settings/hsm-connectors). Infisical generates the CSR against the HSM key and sends only the CSR to DigiCert.+</Note>++### Reuse an existing order++Each DigiCert order consumes a subscription slot. Instead of placing a new order, a new Signer can reissue into one of the organization's existing code-signing orders, which reuses that slot. In the Create Signer wizard's **Certificate** step, pick an order under **Reuse an existing order**. The Common Name and Validity are inherited from that order, so those fields are hidden. Leave it empty to place a new order.++Over the API, set `externalConfiguration.reissueFromExternalOrderId` to the order id on [Create Signer](/api-reference/endpoints/code-signing/signers/create), or `reissueFromExternalOrderId` on [Reissue](/api-reference/endpoints/code-signing/signers/reissue).++### 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.+- **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.+## DigiCert Validation WorkflowWhen you request a certificate through a DigiCert CertCentral CA, the request moves through these states:diff --git a/docs/documentation/platform/pki/code-signing/signers.mdx b/docs/documentation/platform/pki/code-signing/signers.mdxindex f30c5295ef..af4ccd4d43 100644--- a/docs/documentation/platform/pki/code-signing/signers.mdx+++ b/docs/documentation/platform/pki/code-signing/signers.mdx@@ -43,7 +43,7 @@ You'll typically have one Signer per real-world signing concern, such as `mobile## Create a Signer-In **Certificate Manager → Code Signing → Signers**, click **Create Signer**. The wizard walks you through four steps in order.+In **Certificate Manager → Code Signing → Signers**, click **Create Signer**. The wizard walks you through five steps in order: Basics, Certificate, Signing Key, Members, and Approval Policy.<Steps><Step title="Basics">@@ -58,18 +58,31 @@ In **Certificate Manager → Code Signing → Signers**, click **Create Signer**</Step><Step title="Certificate">- Infisical issues a fresh code-signing certificate for the Signer from one of your Certificate Authorities.+ Choose which Certificate Authority issues the Signer's certificate and the identity on it.| Field | Description ||-------|-------------|- | **Certificate Authority** | The CA that issues the certificate. Internal CAs issue immediately. External CAs (AWS Private CA, Azure AD CS) issue asynchronously and the Signer enters **Pending** until the cert lands. |- | **Key source** | Where the signing key is generated. **Infisical** (default) lets Infisical generate and manage the key for you. **HSM** generates the key inside your own HSM through an [HSM Connector](/documentation/platform/pki/settings/hsm-connectors). |+ | **Certificate Authority** | The CA that issues the certificate. Internal CAs issue immediately. External CAs (AWS Private CA, Azure AD CS, DigiCert) issue asynchronously and the Signer enters **Pending** until the cert lands. || **Common Name** | The legal name shown on the certificate, for example `Acme Mobile, Inc.`. Fixed once the certificate is issued. To change it you must reissue. |- | **Key algorithm** | The signing key algorithm: `RSA-2048`, `RSA-3072`, `RSA-4096`, `ECDSA P-256`, `ECDSA P-384`, or `ECDSA P-521`. When **Key source = HSM** the choice is restricted to `RSA-2048`, `RSA-4096`, `ECDSA P-256`, or `ECDSA P-384`. |- | **HSM Connector** | The HSM Connector Infisical uses to reach your HSM. Set the Connector up first under **Certificate Manager > Settings > HSM Connectors**. Shown only when **Key source = HSM**. See [HSM Connectors](/documentation/platform/pki/settings/hsm-connectors). || **Validity (days)** | How long each issued certificate is valid for. Default 365. || **Renew before (days)** | Optional, 1 to 30. Auto-renew this many days before expiry. Must be less than Validity. Leave empty to disable auto-renewal. |+ <Note>+ For DigiCert code-signing CAs, this step also offers an optional **Reuse an existing order** field. Selecting one of the organization's existing DigiCert orders reissues into it (reusing the order slot) instead of placing a new one, and inherits the Common Name and Validity from that order. Leave it empty to issue a new certificate.+ </Note>++ Click **Next** to choose the signing key.+ </Step>++ <Step title="Signing Key">+ Decide where the signing key lives and which algorithm to use.++ | Field | Description |+ |-------|-------------|+ | **Key source** | Where the signing key is generated. **Infisical** (default) lets Infisical generate and manage the key for you. **HSM** generates the key inside your own HSM through an [HSM Connector](/documentation/platform/pki/settings/hsm-connectors). Some CAs require an HSM-backed key and lock this to **HSM** (DigiCert code signing is one of them). |+ | **HSM Connector** | The HSM Connector Infisical uses to reach your HSM. Set the Connector up first under **Certificate Manager > Settings > HSM Connectors**. Shown only when **Key source = HSM**. See [HSM Connectors](/documentation/platform/pki/settings/hsm-connectors). |+ | **Key algorithm** | The signing key algorithm: `RSA-2048`, `RSA-3072`, `RSA-4096`, `ECDSA P-256`, `ECDSA P-384`, or `ECDSA P-521`. When **Key source = HSM** the choice is restricted to `RSA-2048`, `RSA-4096`, `ECDSA P-256`, or `ECDSA P-384`. |+Click **Next** to add members.</Step>@@ -97,7 +110,7 @@ In **Certificate Manager → Code Signing → Signers**, click **Create Signer**## HSM-backed Signers-When you pick **Key source = HSM** on the Certificate step, pick the [HSM Connector](/documentation/platform/pki/settings/hsm-connectors) Infisical should use. The Key algorithm choices narrow to the HSM-supported subset. The private key never leaves the HSM and every sign operation routes through the linked Connector. Infisical only holds the public key and the issued certificate.+When you pick **Key source = HSM** on the Signing Key step, pick the [HSM Connector](/documentation/platform/pki/settings/hsm-connectors) Infisical should use. The Key algorithm choices narrow to the HSM-supported subset. The private key never leaves the HSM and every sign operation routes through the linked Connector. Infisical only holds the public key and the issued certificate.You can later switch an existing Signer between Infisical and HSM by reissuing the certificate with a different key source. Hit the [reissue endpoint](/api-reference/endpoints/code-signing/signers/reissue) with a `certificate.keySource` body, plus `hsmConnectorId` when switching to HSM. The signer keeps its name, members, policy, and CA. Only the underlying key and the cert wrapping it change.@@ -115,11 +128,11 @@ See [HSM Connectors](/documentation/platform/pki/settings/hsm-connectors) for th## Edit a Signer-Open the Signer and choose **Options → Edit settings**. The edit sheet walks you through two steps.+Open the Signer and choose **Options → Edit settings**. The edit sheet walks you through three steps: Basics, Certificate, and Signing Key. Saving can trigger a fresh issuance, so some fields are read-only once the Signer is Active.<Steps>- <Step title="Edit basics">- Update the Signer's identifying information.+ <Step title="Basics">+ Update the Signer's identifying information. These never reissue the certificate.- **Signer name**: rename freely. The PKCS#11 token label updates on the next refresh.- **Description**: edit at will.@@ -127,22 +140,23 @@ Open the Signer and choose **Options → Edit settings**. The edit sheet walks yClick **Next** to edit the certificate.</Step>- <Step title="Edit certificate">- Change the certificate parameters. Saving here can trigger a fresh issuance, so what's editable depends on the Signer's current status.-- **Always editable**+ <Step title="Certificate">+ Change 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**: DigiCert code signing only. While the Signer is **Pending** or **Failed**, you can point it at an existing DigiCert order to reuse that order slot instead of placing a new one. Common Name and Validity are inherited from the order.+ - **Common Name** and **Validity (days)**: editable while the Signer is **Pending** or **Failed** so you can fix bad inputs and try issuance again. Locked once the Signer is **Active** so the issued cert and the Signer's stored intent can't drift apart.- **Renew before (days)**: edit any time, 1 to 30, must be less than Validity.- **Locked once the Signer is Active**-- Once a certificate is bound, the **Common Name**, **Validity (days)**, and **Key algorithm** are all locked together so the issued cert and the Signer's stored intent can't drift apart.+ Click **Next** to edit the signing key.+ </Step>- - While the Signer is **Pending** or **Failed** (no certificate bound yet), **Common Name** and **Validity (days)** are editable so you can fix bad inputs and try issuance again. **Key algorithm** is still read-only here.- - Once **Active**, all three fields show as read-only.+ <Step title="Signing Key">+ Change where the key lives or which algorithm it uses. Both reissue the certificate with a new key.- To change any of them on an Active Signer: swap the CA (reissues with the new CN/Validity if you also fix those before going Active again) or, for **Key algorithm**, create a new Signer with the algorithm you want.+ - **Key source**: switch between Infisical and HSM. Switching to HSM requires picking an HSM Connector and a supported algorithm. CAs that require an HSM-backed key (such as DigiCert code signing) lock this to **HSM**.+ - **HSM Connector**: shown when Key source is HSM.+ - **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.@@ -172,13 +186,13 @@ To sign with a Signer, pick the integration that matches your tooling:**Delete** is permanent. The Signer and everything attached to it (members, policy, access records, audit log) is removed. The certificate object remains in the inventory unless you delete that separately.</Accordion><Accordion title="Why is my new Signer stuck in Pending?">- External CAs (AWS Private CA, Azure AD CS) issue asynchronously. Infisical polls the CA in the background and flips the Signer to **Active** once the certificate is delivered. If it stays Pending for more than a few minutes, hover the badge. The failure reason appears there once the polling job gives up.+ External CAs (AWS Private CA, Azure AD CS, DigiCert) issue asynchronously. Infisical polls the CA in the background and flips the Signer to **Active** once the certificate is delivered. AWS and Azure usually take seconds. DigiCert takes minutes to hours for an already-validated organization, and up to 3 business days the first time an organization is used for code signing while DigiCert validates it. If it stays Pending well beyond those windows, hover the badge. The failure reason appears there once the polling job gives up.</Accordion><Accordion title="What happens to signed artifacts when I delete a Signer?">Artifacts already signed remain valid as long as the certificate they were signed with is still valid and the verifier trusts the issuing CA's chain. Deleting the Signer in Infisical only removes Infisical's ability to sign new artifacts with that certificate. It does not invalidate past signatures.</Accordion><Accordion title="Can I migrate an existing Signer between Infisical and an HSM?">- Yes. From the Signer detail page, open **Edit Signer > Certificate** and change **Key source**. When switching to HSM, pick an HSM Connector and a supported algorithm (RSA-2048, RSA-4096, ECDSA P-256, or ECDSA P-384). Saving reissues the certificate with the new key. The signer keeps its name, members, approval policy, and CA. Only the key and the cert wrapping it change.+ Yes. From the Signer detail page, open **Edit Signer > Signing Key** and change **Key source**. When switching to HSM, pick an HSM Connector and a supported algorithm (RSA-2048, RSA-4096, ECDSA P-256, or ECDSA P-384). Saving reissues the certificate with the new key. The signer keeps its name, members, approval policy, and CA. Only the key and the cert wrapping it change.The same operation is available via the [reissue endpoint](/api-reference/endpoints/code-signing/signers/reissue) by passing `certificate.keySource` and (when switching to HSM) `hsmConnectorId`.diff --git a/frontend/src/hooks/api/appConnections/digicert/queries.tsx b/frontend/src/hooks/api/appConnections/digicert/queries.tsxindex dbd4c14411..d9d54b7ffe 100644--- a/frontend/src/hooks/api/appConnections/digicert/queries.tsx+++ b/frontend/src/hooks/api/appConnections/digicert/queries.tsx@@ -10,7 +10,30 @@ const digicertConnectionKeys = {listOrganizations: (connectionId: string) =>[...digicertConnectionKeys.all, "organizations", connectionId] as const,listProducts: (connectionId: string) =>- [...digicertConnectionKeys.all, "products", connectionId] as const+ [...digicertConnectionKeys.all, "products", connectionId] as const,+ codeSigningValidation: (connectionId: string, organizationId: number, productNameId: string) =>+ [+ ...digicertConnectionKeys.all,+ "code-signing-validation",+ connectionId,+ organizationId,+ productNameId+ ] as const,+ codeSigningOrders: (connectionId: string, organizationId: number, productNameId: string) =>+ [+ ...digicertConnectionKeys.all,+ "code-signing-orders",+ connectionId,+ organizationId,+ productNameId+ ] as const+};++export type TDigiCertCodeSigningOrder = {+ orderId: number;+ commonName: string;+ status: string;+ validTill?: string;};export const useDigiCertConnectionListOrganizations = (@@ -60,3 +83,61 @@ export const useDigiCertConnectionListProducts = (...options});};++export const useDigiCertConnectionCodeSigningValidation = (+ connectionId: string,+ organizationId: number,+ productNameId: string,+ options?: Omit<+ UseQueryOptions<+ { isValidated: boolean },+ unknown,+ { isValidated: boolean },+ ReturnType<typeof digicertConnectionKeys.codeSigningValidation>+ >,+ "queryKey" | "queryFn"+ >+) => {+ return useQuery({+ queryKey: digicertConnectionKeys.codeSigningValidation(+ connectionId,+ organizationId,+ productNameId+ ),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ isValidated: boolean }>(+ `/api/v1/app-connections/digicert/${connectionId}/organizations/${organizationId}/code-signing-validation`,+ { params: { productNameId } }+ );+ return data;+ },+ ...options+ });+};++export const useDigiCertConnectionListCodeSigningOrders = (+ connectionId: string,+ organizationId: number,+ productNameId: string,+ options?: Omit<+ UseQueryOptions<+ TDigiCertCodeSigningOrder[],+ unknown,+ TDigiCertCodeSigningOrder[],+ ReturnType<typeof digicertConnectionKeys.codeSigningOrders>+ >,+ "queryKey" | "queryFn"+ >+) => {+ return useQuery({+ queryKey: digicertConnectionKeys.codeSigningOrders(connectionId, organizationId, productNameId),+ queryFn: async () => {+ const { data } = await apiRequest.get<TDigiCertCodeSigningOrder[]>(+ `/api/v1/app-connections/digicert/${connectionId}/organizations/${organizationId}/code-signing-orders`,+ { params: { productNameId } }+ );+ return data;+ },+ ...options+ });+};diff --git a/frontend/src/hooks/api/ca/capabilities.ts b/frontend/src/hooks/api/ca/capabilities.tsnew file mode 100644index 0000000000..ab0461ed2f--- /dev/null+++ b/frontend/src/hooks/api/ca/capabilities.ts@@ -0,0 +1,15 @@+import { CaType } from "./enums";++export type CaIssuanceCapabilities = {+ requiresHsm: boolean;+ supportsExistingOrderReuse: boolean;+};++export const getCaIssuanceCapabilities = (caType?: CaType): CaIssuanceCapabilities => {+ switch (caType) {+ case CaType.DIGICERT:+ return { requiresHsm: true, supportsExistingOrderReuse: true };+ default:+ return { requiresHsm: false, supportsExistingOrderReuse: false };+ }+};diff --git a/frontend/src/hooks/api/ca/index.tsx b/frontend/src/hooks/api/ca/index.tsxindex e2130a8761..51dc824018 100644--- a/frontend/src/hooks/api/ca/index.tsx+++ b/frontend/src/hooks/api/ca/index.tsx@@ -1,3 +1,5 @@+export type { CaIssuanceCapabilities } from "./capabilities";+export { getCaIssuanceCapabilities } from "./capabilities";export {AcmeDnsProvider,CaRenewalStatus,diff --git a/frontend/src/hooks/api/ca/types.ts b/frontend/src/hooks/api/ca/types.tsindex 707c8b26a5..ab25b1b239 100644--- a/frontend/src/hooks/api/ca/types.ts+++ b/frontend/src/hooks/api/ca/types.ts@@ -55,6 +55,19 @@ export type TAwsPcaCertificateAuthority = {};};+export enum DigiCertCaPurpose {+ Ssl = "ssl",+ CodeSigning = "code_signing"+}++export type TDigiCertVerifiedContact = {+ firstName: string;+ lastName: string;+ email: string;+ jobTitle: string;+ telephone: string;+};+export type TDigiCertCertificateAuthority = {id: string;projectId: string;@@ -66,6 +79,8 @@ export type TDigiCertCertificateAuthority = {appConnectionId: string;organizationId: number;productNameId: string;+ purpose?: DigiCertCaPurpose;+ verifiedContact?: TDigiCertVerifiedContact;};};diff --git a/frontend/src/hooks/api/signers/types.ts b/frontend/src/hooks/api/signers/types.tsindex b13481b96c..b375e41d18 100644--- a/frontend/src/hooks/api/signers/types.ts+++ b/frontend/src/hooks/api/signers/types.ts@@ -265,6 +265,9 @@ export type TCreateSignerDTO = {members?: TCreateSignerMemberInput[];approvalPolicy?: TCreateSignerApprovalPolicyInput;certificate?: TSignerCertificateInput;+ externalConfiguration?: {+ reissueFromExternalOrderId?: string;+ };};export type TUpdateSignerDTO = {@@ -288,6 +291,7 @@ export type TReissueSignerCertificateDTO = {keySource: CertKeySource;hsmConnectorId?: string;};+ reissueFromExternalOrderId?: string;};export type TEnableSignerDTO = { signerId: string };diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsxindex f82effa0fe..b4d6e8acf9 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx@@ -34,6 +34,7 @@ import {import {TDigiCertOrganization,TDigiCertProduct,+ useDigiCertConnectionCodeSigningValidation,useDigiCertConnectionListOrganizations,useDigiCertConnectionListProducts} from "@app/hooks/api/appConnections/digicert";@@ -55,6 +56,7 @@ import {ACME_DNS_PROVIDER_APP_CONNECTION_MAP,ACME_DNS_PROVIDER_NAME_MAP} from "@app/hooks/api/ca/constants";+import { DigiCertCaPurpose } from "@app/hooks/api/ca/types";import { UsePopUpState } from "@app/hooks/usePopUp";import { slugSchema } from "@app/lib/schemas";@@ -127,14 +129,54 @@ const awsPcaConfigurationSchema = z.object({region: z.string().min(1, "Region is required")});-const digicertConfigurationSchema = z.object({- digicertConnection: z.object({- id: z.string().min(1, "DigiCert Connection is required"),- name: z.string()- }),- organizationId: z.coerce.number().int().positive("Organization is required"),- productNameId: z.string().trim().min(1, "Product is required")-});+const digicertConfigurationSchema = z+ .object({+ digicertConnection: z.object({+ id: z.string().min(1, "DigiCert Connection is required"),+ name: z.string()+ }),+ organizationId: z.coerce.number().int().positive("Organization is required"),+ productNameId: z.string().trim().min(1, "Product is required"),+ purpose: z.nativeEnum(DigiCertCaPurpose).optional(),+ // UI-only flag (not sent): true when the org isn't code-signing validated yet, so a contact is required.+ csRequiresContact: z.boolean().optional(),+ verifiedContact: z+ .object({+ firstName: z.string().trim().max(128).optional(),+ lastName: z.string().trim().max(128).optional(),+ email: z.string().trim().max(255).optional(),+ jobTitle: z.string().trim().max(64).optional(),+ telephone: z.string().trim().max(32).optional()+ })+ .optional()+ })+ .superRefine((cfg, ctx) => {+ if (cfg.purpose !== DigiCertCaPurpose.CodeSigning || !cfg.csRequiresContact) return;+ const c = cfg.verifiedContact;+ const requiredFields: { key: keyof NonNullable<typeof c>; label: string }[] = [+ { key: "firstName", label: "First Name" },+ { key: "lastName", label: "Last Name" },+ { key: "email", label: "Email" },+ { key: "jobTitle", label: "Job Title" },+ { key: "telephone", label: "Telephone" }+ ];+ requiredFields.forEach(({ key, label }) => {+ if (!c?.[key] || c[key]?.length === 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["verifiedContact", key],+ message: `${label} is required for code signing CAs`+ });+ }+ });+ if (c?.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(c.email)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["verifiedContact", "email"],+ message: "Email must be valid"+ });+ }+ });const awsAcmPublicCaConfigurationSchema = z.object({awsConnection: z.object({@@ -229,7 +271,8 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {handleSubmit,reset,formState: { isSubmitting },- watch+ watch,+ setValue} = useForm<FormData>({resolver: zodResolver(schema)});@@ -285,7 +328,9 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {name: ""},organizationId: 0,- productNameId: ""+ productNameId: "",+ purpose: DigiCertCaPurpose.Ssl,+ verifiedContact: undefined}});} else if (initialType === CaType.AWS_ACM_PUBLIC_CA) {@@ -548,7 +593,9 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {name: selectedConnection?.name || ""},organizationId: ca.configuration.organizationId,- productNameId: ca.configuration.productNameId+ productNameId: ca.configuration.productNameId,+ purpose: ca.configuration.purpose ?? DigiCertCaPurpose.Ssl,+ verifiedContact: ca.configuration.verifiedContact}});} else if (ca.type === CaType.AWS_ACM_PUBLIC_CA && availableConnections?.length) {@@ -633,6 +680,47 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {enabled: caType === CaType.DIGICERT && !!digicertConnectionId});+ const digicertOrganizationId =+ caType === CaType.DIGICERT && configuration && "organizationId" in configuration+ ? (configuration.organizationId ?? 0)+ : 0;+ const digicertProductNameId =+ caType === CaType.DIGICERT && configuration && "productNameId" in configuration+ ? (configuration.productNameId ?? "")+ : "";+ const digicertPurpose =+ caType === CaType.DIGICERT && configuration && "purpose" in configuration+ ? (configuration.purpose ?? DigiCertCaPurpose.Ssl)+ : DigiCertCaPurpose.Ssl;++ const isCsValidationCheckable =+ caType === CaType.DIGICERT &&+ digicertPurpose === DigiCertCaPurpose.CodeSigning &&+ !!digicertConnectionId &&+ !!digicertOrganizationId &&+ !!digicertProductNameId;++ const { data: csValidation, isFetching: isCsValidationFetching } =+ useDigiCertConnectionCodeSigningValidation(+ digicertConnectionId,+ digicertOrganizationId,+ digicertProductNameId,+ { enabled: isCsValidationCheckable }+ );++ const csOrgValidated = isCsValidationCheckable ? csValidation?.isValidated : undefined;+ const csRequiresContact = isCsValidationCheckable && csOrgValidated === false;+ const isCheckingCsValidation =+ isCsValidationCheckable && csOrgValidated === undefined && isCsValidationFetching;++ useEffect(() => {+ if (caType !== CaType.DIGICERT) return;+ setValue("configuration.csRequiresContact", csRequiresContact);+ if (!csRequiresContact) {+ setValue("configuration.verifiedContact", undefined);+ }+ }, [caType, csRequiresContact, setValue]);+const onFormSubmit = async ({type,name,@@ -664,10 +752,17 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {region: formConfiguration.region};} else if (type === CaType.DIGICERT && "digicertConnection" in formConfiguration) {+ const purposeForPayload = formConfiguration.purpose ?? DigiCertCaPurpose.Ssl;configPayload = {appConnectionId: formConfiguration.digicertConnection.id,organizationId: formConfiguration.organizationId,- productNameId: formConfiguration.productNameId+ productNameId: formConfiguration.productNameId,+ purpose: purposeForPayload,+ ...(purposeForPayload === DigiCertCaPurpose.CodeSigning &&+ formConfiguration.csRequiresContact &&+ formConfiguration.verifiedContact+ ? { verifiedContact: formConfiguration.verifiedContact }+ : {})};} else if (type === CaType.AWS_ACM_PUBLIC_CA && "awsConnection" in formConfiguration) {configPayload = {@@ -1161,33 +1256,180 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {</FormControl>)}/>+ <Controller+ control={control}+ name="configuration.purpose"+ render={({ field: { value, onChange }, fieldState: { error } }) => {+ const PURPOSE_OPTIONS = [+ { value: DigiCertCaPurpose.Ssl, label: "SSL / TLS" },+ { value: DigiCertCaPurpose.CodeSigning, label: "Code Signing" }+ ];+ return (+ <FormControl+ label="Purpose"+ errorText={error?.message}+ isError={Boolean(error)}+ isRequired+ tooltipText="What this CA issues. Selecting Code Signing filters the Product list to DigiCert's code-signing products."+ >+ <FilterableSelect+ value={+ PURPOSE_OPTIONS.find(+ (o) => o.value === (value ?? DigiCertCaPurpose.Ssl)+ ) ?? PURPOSE_OPTIONS[0]+ }+ onChange={(option) => {+ const next = (+ option as SingleValue<{ value: DigiCertCaPurpose; label: string }>+ )?.value;+ if (next) {+ onChange(next);+ setValue("configuration.productNameId", "");+ }+ }}+ options={PURPOSE_OPTIONS}+ getOptionLabel={(option) => option.label}+ getOptionValue={(option) => option.value}+ menuPortalTarget={modalContainer.current}+ />+ </FormControl>+ );+ }}+ /><Controllercontrol={control}name="configuration.productNameId"- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- label="Product"- errorText={error?.message}- isError={Boolean(error)}- isRequired- tooltipText="Products available are account-specific entitlements fetched from CertCentral. Each Infisical CA issues under exactly one product."- >- <FilterableSelect- isLoading={isDigiCertProductsPending && !!digicertConnectionId}- isDisabled={!digicertConnectionId}- value={digicertProducts.find((product) => product.nameId === value) ?? null}- onChange={(option) => {- onChange((option as SingleValue<TDigiCertProduct>)?.nameId ?? "");- }}- options={digicertProducts}- placeholder="Select a product..."- getOptionLabel={(option) => `${option.name} (${option.nameId})`}- getOptionValue={(option) => option.nameId}- menuPortalTarget={modalContainer.current}- />- </FormControl>- )}+ render={({ field: { value, onChange }, fieldState: { error } }) => {+ const purpose =+ configuration && "purpose" in configuration+ ? (configuration.purpose ?? DigiCertCaPurpose.Ssl)+ : DigiCertCaPurpose.Ssl;+ const filteredProducts = digicertProducts.filter((p) => {+ if (purpose === DigiCertCaPurpose.CodeSigning)+ return p.type === "code_signing_certificate";+ return p.type === "ssl_certificate" || !p.type;+ });+ return (+ <FormControl+ label="Product"+ errorText={error?.message}+ isError={Boolean(error)}+ isRequired+ tooltipText="Products available are account-specific entitlements fetched from CertCentral. Each Infisical CA issues under exactly one product."+ >+ <FilterableSelect+ isLoading={isDigiCertProductsPending && !!digicertConnectionId}+ isDisabled={!digicertConnectionId}+ value={filteredProducts.find((product) => product.nameId === value) ?? null}+ onChange={(option) => {+ onChange((option as SingleValue<TDigiCertProduct>)?.nameId ?? "");+ }}+ options={filteredProducts}+ placeholder="Select a product..."+ getOptionLabel={(option) => `${option.name} (${option.nameId})`}+ getOptionValue={(option) => option.nameId}+ menuPortalTarget={modalContainer.current}+ />+ </FormControl>+ );+ }}/>+ {/* Shown only when the org is not yet code-signing validated. While the check is in+ flight nothing renders here — the submit button shows a loading state instead. */}+ {csRequiresContact && (+ <div className="mt-3 mb-2 rounded-md border border-mineshaft-600 bg-mineshaft-800 p-4">+ <div className="mb-1 text-sm font-medium text-mineshaft-100">+ Verified Contact+ </div>+ <div className="mb-4 text-xs text-mineshaft-400">+ This organization has not completed DigiCert code-signing validation yet, so a+ verified contact is required. DigiCert emails this person an approval link they+ must click to start organization validation.+ </div>+ <div className="grid grid-cols-2 gap-x-3 gap-y-2">+ <Controller+ control={control}+ name="configuration.verifiedContact.firstName"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="First Name"+ errorText={error?.message}+ isError={Boolean(error)}+ isRequired+ >+ <Input {...field} value={field.value ?? ""} placeholder="John" />+ </FormControl>+ )}+ />+ <Controller+ control={control}+ name="configuration.verifiedContact.lastName"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="Last Name"+ errorText={error?.message}+ isError={Boolean(error)}+ isRequired+ >+ <Input {...field} value={field.value ?? ""} placeholder="Doe" />+ </FormControl>+ )}+ />+ <Controller+ control={control}+ name="configuration.verifiedContact.email"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="Email"+ errorText={error?.message}+ isError={Boolean(error)}+ isRequired+ className="col-span-2"+ >+ <Input+ {...field}+ value={field.value ?? ""}+ placeholder="[email protected]"+ />+ </FormControl>+ )}+ />+ <Controller+ control={control}+ name="configuration.verifiedContact.jobTitle"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="Job Title"+ errorText={error?.message}+ isError={Boolean(error)}+ isRequired+ >+ <Input+ {...field}+ value={field.value ?? ""}+ placeholder="Security Engineer"+ />+ </FormControl>+ )}+ />+ <Controller+ control={control}+ name="configuration.verifiedContact.telephone"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="Telephone"+ errorText={error?.message}+ isError={Boolean(error)}+ isRequired+ tooltipText="Include the country code, e.g. +15551234567."+ >+ <Input {...field} value={field.value ?? ""} placeholder="+15551234567" />+ </FormControl>+ )}+ />+ </div>+ </div>+ )}</>)}{caType === CaType.AWS_ACM_PUBLIC_CA && (@@ -1380,8 +1622,8 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {className="mr-4"size="sm"type="submit"- isLoading={isSubmitting}- isDisabled={isSubmitting}+ isLoading={isSubmitting || isCheckingCsValidation}+ isDisabled={isSubmitting || isCheckingCsValidation}>{popUp?.ca?.data ? "Update" : "Create"}</Button>diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsxindex 10603b85ba..b4fb631ed1 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx@@ -1,8 +1,9 @@+import { useEffect } from "react";import { Controller, useForm } from "react-hook-form";import { Link, useParams } from "@tanstack/react-router";+import { InfoIcon } from "lucide-react";import {- Badge,Field,FieldContent,FieldDescription,@@ -11,60 +12,69 @@ import {FieldLabel,FilterableSelect,Input,- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue+ Tooltip,+ TooltipContent,+ TooltipTrigger} from "@app/components/v3";import { ROUTE_PATHS } from "@app/const/routes";-import { useProjectPermission, useSubscription } from "@app/context";-import {- ProjectPermissionHsmConnectorActions,- ProjectPermissionSub-} from "@app/context/ProjectPermissionContext/types";-import {- CertKeySource,- HSM_SUPPORTED_KEY_ALGORITHMS,- SignerKeyAlgorithm,- signerKeyAlgorithmLabels-} from "@app/hooks/api/signers";+import { useDigiCertConnectionListCodeSigningOrders } from "@app/hooks/api/appConnections/digicert";+import { getCaIssuanceCapabilities } from "@app/hooks/api/ca";import { CertificateForm } from "./schemas";import { CaGroup, CaOption } from "./types";-export type HsmConnectorOption = { id: string; name: string; slotLabel: string };-type CertificateStepProps = {form: ReturnType<typeof useForm<CertificateForm>>;caOptions: CaOption[];isCasLoading: boolean;- hsmConnectorOptions: HsmConnectorOption[];- isHsmConnectorsLoading: boolean;};-export const CertificateStep = ({- form,- caOptions,- isCasLoading,- hsmConnectorOptions,- isHsmConnectorsLoading-}: CertificateStepProps) => {+export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateStepProps) => {const { orgId, projectId } = useParams({ strict: false }) as {orgId?: string;projectId?: string;};- const { subscription } = useSubscription();- const isHsmLicensed = Boolean(subscription?.hsm);- const { permission } = useProjectPermission();- const canAttachHsm = permission.can(- ProjectPermissionHsmConnectorActions.Attach,- ProjectPermissionSub.HsmConnectors- );+ const selectedCaId = form.watch("caId");+ const selectedCa = caOptions.find((o) => o.id === selectedCaId) ?? null;+ const caps = getCaIssuanceCapabilities(selectedCa?.caType);++ const digicertCfg = selectedCa?.digicert;+ const canReuseOrder = caps.supportsExistingOrderReuse && Boolean(digicertCfg);+ const { data: codeSigningOrders = [], isLoading: isOrdersLoading } =+ useDigiCertConnectionListCodeSigningOrders(+ digicertCfg?.appConnectionId ?? "",+ digicertCfg?.organizationId ?? 0,+ digicertCfg?.productNameId ?? "",+ { enabled: canReuseOrder }+ );- const keySource = form.watch("keySource");- const isHsm = keySource === CertKeySource.Hsm;+ const orderOptions = codeSigningOrders.map((o) => ({+ value: String(o.orderId),+ label: `${o.commonName || "Code signing certificate"} (#${o.orderId})`,+ commonName: o.commonName+ }));+ type OrderOption = (typeof orderOptions)[number];++ const reissueOrderId = form.watch("reissueFromExternalOrderId");+ const isReissue = Boolean(reissueOrderId);++ 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);+ }+ }, [canReuseOrder, isOrdersLoading, reissueOrderId, codeSigningOrders, form]);return (<FieldGroup>@@ -99,7 +109,7 @@ export const CertificateStep = ({isError={Boolean(error)}/><FieldDescription>- The CA that will issue the certificate.+ The CA that issues the certificate.{!isCasLoading && caOptions.length === 0 && orgId && projectId && (<>{" "}@@ -108,7 +118,7 @@ export const CertificateStep = ({params={{ orgId, projectId }}className="text-primary underline hover:text-primary/80">- Create one in the Certificate Authorities page.+ Create one first.</Link></>)}@@ -118,128 +128,91 @@ export const CertificateStep = ({</Field>)}/>- <Controller- name="commonName"- control={form.control}- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel>- Common Name <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <Input {...field} placeholder="Acme Mobile, Inc." isError={Boolean(error)} />- <FieldDescription>The legal name shown on the certificate.</FieldDescription>- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}- />- <Controller- name="keySource"- control={form.control}- render={({ field }) => (- <Field>- <FieldLabel>- Key source <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <Select value={field.value} onValueChange={field.onChange}>- <SelectTrigger className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- <SelectItem value={CertKeySource.Infisical}>Infisical</SelectItem>- <SelectItem value={CertKeySource.Hsm} disabled={!isHsmLicensed || !canAttachHsm}>- <div className="flex items-center gap-2">- HSM- {!isHsmLicensed && <Badge variant="info">Enterprise</Badge>}- {isHsmLicensed && !canAttachHsm && (- <Badge variant="warning">Permission required</Badge>- )}- </div>- </SelectItem>- </SelectContent>- </Select>- <FieldDescription>- {field.value === CertKeySource.Hsm- ? "The keypair is generated on a Hardware Security Module and every signature is performed there."- : "Infisical generates and manages the keypair for you."}- </FieldDescription>- </FieldContent>- </Field>- )}- />+ {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>+ </FieldContent>+ </Field>+ )}+ />+ )}- <Controller- name="keyAlgorithm"- control={form.control}- render={({ field, fieldState: { error } }) => {- const options = isHsm- ? Object.values(SignerKeyAlgorithm).filter((v) =>- HSM_SUPPORTED_KEY_ALGORITHMS.includes(v)- )- : Object.values(SignerKeyAlgorithm);- return (+ {!isReissue && (+ <Controller+ name="commonName"+ control={form.control}+ render={({ field, fieldState: { error } }) => (<Field><FieldLabel>- Key algorithm <span className="text-danger">*</span>+ Common Name <span className="text-danger">*</span></FieldLabel><FieldContent>- <Select value={field.value} onValueChange={field.onChange}>- <SelectTrigger className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- {options.map((value) => (- <SelectItem key={value} value={value}>- {signerKeyAlgorithmLabels[value]}- </SelectItem>- ))}- </SelectContent>- </Select>- <FieldDescription>- Algorithm used to generate the signing key. RSA is widely compatible, ECDSA- produces smaller signatures and is faster.- </FieldDescription>+ <Input {...field} placeholder="Acme Mobile, Inc." isError={Boolean(error)} />+ <FieldDescription>The legal name shown on the certificate.</FieldDescription><FieldError errors={[error]} /></FieldContent></Field>- );- }}- />+ )}+ />+ )}- {isHsm && (+ {!isReissue && (<Controller- name="hsmConnectorId"+ name="certificateTtlDays"control={form.control}render={({ field, fieldState: { error } }) => (<Field><FieldLabel>- HSM Connector <span className="text-danger">*</span>+ Validity (days) <span className="text-danger">*</span></FieldLabel><FieldContent>- <FilterableSelect<HsmConnectorOption>- isLoading={isHsmConnectorsLoading}- options={hsmConnectorOptions}- value={hsmConnectorOptions.find((o) => o.id === field.value) ?? null}- onChange={(selected) => {- const opt = selected as HsmConnectorOption | null;- field.onChange(opt?.id ?? null);- }}- getOptionLabel={(opt) => `${opt.name} (slot ${opt.slotLabel})`}- getOptionValue={(opt) => opt.id}- placeholder="Select an HSM Connector..."- noOptionsMessage={() =>- hsmConnectorOptions.length === 0- ? "No HSM Connectors configured. Add one in Cert Manager Settings → HSM Connectors."- : "No match."- }+ <Input+ type="number"+ min={1}+ max={3650}+ value={field.value ?? ""}+ onChange={(e) => field.onChange(Number(e.target.value))}+ placeholder="365"isError={Boolean(error)}/>- <FieldDescription>- The HSM on which Infisical will generate the signing key.- </FieldDescription><FieldError errors={[error]} /></FieldContent></Field>@@ -247,29 +220,6 @@ export const CertificateStep = ({/>)}- <Controller- name="certificateTtlDays"- control={form.control}- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel>- Validity (days) <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <Input- type="number"- min={1}- max={3650}- value={field.value ?? ""}- onChange={(e) => field.onChange(Number(e.target.value))}- placeholder="365"- isError={Boolean(error)}- />- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}- /><Controllername="certificateRenewBeforeDays"control={form.control}@@ -290,7 +240,7 @@ export const CertificateStep = ({isError={Boolean(error)}/><FieldDescription>- Renew the certificate this many days before it expires.+ Renew this many days before the certificate expires.</FieldDescription><FieldError errors={[error]} /></FieldContent>diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsxindex 9ed075d6ac..090331ba63 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx@@ -1,7 +1,7 @@-import { useMemo, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { ShieldIcon } from "lucide-react";+import { PenTool } from "lucide-react";import { createNotification } from "@app/components/notifications";import {@@ -16,8 +16,9 @@ import {StepperStep} from "@app/components/v3";import { useOrganization, useSubscription, useUser } from "@app/context";-import { useListCasByProjectId } from "@app/hooks/api/ca";+import { getCaIssuanceCapabilities, useListCasByProjectId } from "@app/hooks/api/ca";import { CaStatus, CaType } from "@app/hooks/api/ca/enums";+import { DigiCertCaPurpose } from "@app/hooks/api/ca/types";import { useListHsmConnectors } from "@app/hooks/api/hsmConnectors";import { useGetOrganizationGroups } from "@app/hooks/api/organization";import { useListProjectIdentityMemberships } from "@app/hooks/api/projectIdentityMembership";@@ -30,6 +31,7 @@ import {} from "@app/hooks/api/signers";import { useGetOrgUsers } from "@app/hooks/api/users";+import { SignerKeyStep } from "../../../components/SignerKeyStep";import { PkiDocsUrls } from "../../../pki-docs-urls";import { ApprovalPolicyStep } from "./ApprovalPolicyStep";import { BasicsStep } from "./BasicsStep";@@ -78,16 +80,28 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =const list = cas.data ?? [];return list.filter((ca) => ca.status === CaStatus.ACTIVE)- .filter(- (ca) =>- ca.type === CaType.INTERNAL ||- ca.type === CaType.AWS_PCA ||- ca.type === CaType.AZURE_AD_CS- )+ .filter((ca) => {+ if (ca.type === CaType.INTERNAL) return true;+ if (ca.type === CaType.AWS_PCA) return true;+ if (ca.type === CaType.AZURE_AD_CS) return true;+ if (ca.type === CaType.DIGICERT) {+ return ca.configuration?.purpose === DigiCertCaPurpose.CodeSigning;+ }+ return false;+ }).map((ca) => ({id: ca.id,name: ca.name,- groupType: ca.type === CaType.INTERNAL ? "internal" : "external"+ groupType: ca.type === CaType.INTERNAL ? "internal" : "external",+ caType: ca.type,+ digicert:+ ca.type === CaType.DIGICERT+ ? {+ appConnectionId: ca.configuration.appConnectionId,+ organizationId: ca.configuration.organizationId,+ productNameId: ca.configuration.productNameId+ }+ : undefined}));}, [cas.data]);@@ -137,10 +151,21 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =certificateRenewBeforeDays: state.certificateRenewBeforeDays,keyAlgorithm: state.keyAlgorithm,keySource: state.keySource,- hsmConnectorId: state.hsmConnectorId+ hsmConnectorId: state.hsmConnectorId,+ reissueFromExternalOrderId: state.reissueFromExternalOrderId}});+ const selectedCaId = certificateForm.watch("caId");+ const selectedCa = caOptions.find((o) => o.id === selectedCaId) ?? null;+ const caCaps = getCaIssuanceCapabilities(selectedCa?.caType);++ useEffect(() => {+ if (caCaps.requiresHsm && certificateForm.getValues("keySource") !== CertKeySource.Hsm) {+ certificateForm.setValue("keySource", CertKeySource.Hsm, { shouldValidate: false });+ }+ }, [caCaps.requiresHsm, certificateForm]);+const reset = () => {setStep(0);setState(INITIAL_WIZARD_STATE);@@ -152,7 +177,8 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =certificateRenewBeforeDays: null,keyAlgorithm: SignerKeyAlgorithm.RSA_2048,keySource: CertKeySource.Infisical,- hsmConnectorId: null+ hsmConnectorId: null,+ reissueFromExternalOrderId: null});};@@ -204,7 +230,10 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =role: m.role})),approvalPolicy,- certificate+ certificate,+ externalConfiguration: state.reissueFromExternalOrderId+ ? { reissueFromExternalOrderId: state.reissueFromExternalOrderId }+ : undefined});handleClose(false);@@ -220,6 +249,21 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =const isLast = step === STEPS.length - 1;+ const persistCertificateForm = () => {+ const values = certificateForm.getValues();+ setState((prev) => ({+ ...prev,+ caId: values.caId,+ commonName: values.commonName,+ certificateTtlDays: values.certificateTtlDays,+ certificateRenewBeforeDays: values.certificateRenewBeforeDays,+ keyAlgorithm: values.keyAlgorithm,+ keySource: values.keySource,+ hsmConnectorId: values.hsmConnectorId ?? null,+ reissueFromExternalOrderId: values.reissueFromExternalOrderId ?? null+ }));+ };+const goNext = async () => {if (step === 0) {const ok = await basicsForm.trigger();@@ -230,27 +274,30 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =return;}if (step === 1) {- const ok = await certificateForm.trigger();+ const ok = await certificateForm.trigger([+ "caId",+ "commonName",+ "certificateTtlDays",+ "certificateRenewBeforeDays",+ "reissueFromExternalOrderId"+ ]);if (!ok) return;- const values = certificateForm.getValues();- setState((prev) => ({- ...prev,- caId: values.caId,- commonName: values.commonName,- certificateTtlDays: values.certificateTtlDays,- certificateRenewBeforeDays: values.certificateRenewBeforeDays,- keyAlgorithm: values.keyAlgorithm,- keySource: values.keySource,- hsmConnectorId: values.hsmConnectorId ?? null- }));+ persistCertificateForm();setStep(2);return;}if (step === 2) {+ const ok = await certificateForm.trigger(["keySource", "keyAlgorithm", "hsmConnectorId"]);+ if (!ok) return;+ persistCertificateForm();setStep(3);return;}if (step === 3) {+ setStep(4);+ return;+ }+ if (step === 4) {await onCreate();}};@@ -283,7 +330,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =<SheetTitle><div className="flex w-full items-start gap-2"><div className="flex h-10 w-10 items-center justify-center rounded-md bg-project/10 text-project">- <ShieldIcon className="h-5 w-5" />+ <PenTool className="h-5 w-5" /></div><div><div className="flex items-center gap-x-2 text-mineshaft-300">@@ -291,8 +338,8 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =<DocumentationLinkBadge href={PkiDocsUrls.codeSigning.signers.create} /></div><p className="text-sm leading-4 text-mineshaft-400">- A Signer bundles a code-signing certificate, the members allowed to use it, and an- approval policy.+ A code-signing certificate with the members and approval policy that govern its+ use.</p></div></div>@@ -337,11 +384,17 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =form={certificateForm}caOptions={caOptions}isCasLoading={cas.isPending}+ />+ )}+ {step === 2 && (+ <SignerKeyStep+ control={certificateForm.control}+ requiresHsm={caCaps.requiresHsm}hsmConnectorOptions={hsmConnectorOptions}isHsmConnectorsLoading={isHsmConnectorsLoading}/>)}- {step === 2 && (+ {step === 3 && (<MembersStepuserOptions={userOptions.filter((u) => u.value !== user.id)}identityOptions={identityOptions}@@ -354,7 +407,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =creator={{ id: user.id, label: creatorLabel }}/>)}- {step === 3 && (+ {step === 4 && (<ApprovalPolicyStepstate={state}setState={setState}diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.tsindex 3661e9f77d..e76734ebed 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts@@ -37,7 +37,9 @@ export const certificateSchema = z.default(null),keyAlgorithm: z.nativeEnum(SignerKeyAlgorithm).default(SignerKeyAlgorithm.RSA_2048),keySource: z.nativeEnum(CertKeySource).default(CertKeySource.Infisical),- hsmConnectorId: z.string().uuid().optional().nullable()+ 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)}).refine((data) =>diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.tsindex 7698cbca38..b81611c589 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts@@ -1,9 +1,17 @@+import { CaType } from "@app/hooks/api/ca/enums";import { CertKeySource, SignerKeyAlgorithm, SignerMemberRole } from "@app/hooks/api/signers";import { PkiDocsUrls } from "../../../pki-docs-urls";export type CaGroup = "internal" | "external";-export type CaOption = { id: string; name: string; groupType: CaGroup };+export type CaOption = {+ id: string;+ name: string;+ groupType: CaGroup;+ caType: CaType;+ digicert?: { appConnectionId: string; organizationId: number; productNameId: string };+};+export type MemberOption = { value: string; label: string };export type ApproverOption = { value: string; label: string; kind: "user" | "group" };@@ -43,6 +51,7 @@ export type WizardState = {keyAlgorithm: SignerKeyAlgorithm;keySource: CertKeySource;hsmConnectorId: string | null;+ reissueFromExternalOrderId: string | null;pendingMembers: PendingMember[];policySteps: PolicyStep[];maxSignings: number | null;@@ -59,6 +68,7 @@ export const INITIAL_WIZARD_STATE: WizardState = {keyAlgorithm: SignerKeyAlgorithm.RSA_2048,keySource: CertKeySource.Infisical,hsmConnectorId: null,+ reissueFromExternalOrderId: null,pendingMembers: [],policySteps: [],maxSignings: null,@@ -80,20 +90,30 @@ export const STEPS: WizardStep[] = [name: "Basics",shortDescription: "Name and description",title: "Basics",- subtitle: "A short name and what this signer is for.",+ subtitle: "Name this signer and note what it's for.",rightLabel: "BASICS",rightDescription:- "Set the signer's name and a short description so your team knows what it signs (for example, mobile-app-prod for production iOS and Android bundles).",+ "A clear name and description help your team identify what this signer is used for.",docsUrl: PkiDocsUrls.codeSigning.signers.basics},{name: "Certificate",- shortDescription: "How it signs",+ shortDescription: "CA and identity",title: "Certificate",- subtitle: "Pick the Certificate Authority and the name on the certificate.",+ subtitle: "Select the issuing CA and the certificate's name and validity.",rightLabel: "CERTIFICATE",rightDescription:- "Tells Infisical which CA issues the signing certificate, the name shown on it, and how long it stays valid. The Common Name is fixed once issued. Pick the key source: Infisical or HSM (the keypair stays inside your own HSM).",+ "Select the CA that issues the certificate and the name shown on it. The Common Name cannot be changed after issuance.",+ docsUrl: PkiDocsUrls.codeSigning.signers.certificate+ },+ {+ name: "Signing Key",+ shortDescription: "Key storage and algorithm",+ title: "Signing Key",+ subtitle: "Select the key source and algorithm.",+ rightLabel: "SIGNING KEY",+ rightDescription:+ "Choose the key source and algorithm. Some CAs require an HSM-backed key and lock this selection.",docsUrl: PkiDocsUrls.codeSigning.signers.certificate},{diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsxindex bb1cc68da7..06f087cbd3 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx@@ -1,7 +1,8 @@+import { useEffect } from "react";import { Controller, useForm } from "react-hook-form";+import { InfoIcon } from "lucide-react";import {- Badge,Field,FieldContent,FieldDescription,@@ -10,40 +11,23 @@ import {FieldLabel,FilterableSelect,Input,- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue+ Tooltip,+ TooltipContent,+ TooltipTrigger} from "@app/components/v3";-import { useProjectPermission, useSubscription } from "@app/context";-import {- ProjectPermissionHsmConnectorActions,- ProjectPermissionSub-} from "@app/context/ProjectPermissionContext/types";-import {- CertKeySource,- HSM_SUPPORTED_KEY_ALGORITHMS,- SignerKeyAlgorithm,- signerKeyAlgorithmLabels-} from "@app/hooks/api/signers";+import { useDigiCertConnectionListCodeSigningOrders } from "@app/hooks/api/appConnections/digicert";+import { getCaIssuanceCapabilities } from "@app/hooks/api/ca";import { CertificateForm } from "./schemas";import { CaGroup, CaOption } from "./types";-export type HsmConnectorOption = { id: string; name: string; slotLabel: string };-type CertificateStepProps = {form: ReturnType<typeof useForm<CertificateForm>>;caOptions: CaOption[];isCasLoading: boolean;commonName: string;certificateTtlDays: number | null;- hsmConnectorOptions: HsmConnectorOption[];- isHsmConnectorsLoading: boolean;- caSwap: boolean;canEditSubject: boolean;- keySourceChanged: boolean;};export const CertificateStep = ({@@ -52,22 +36,48 @@ export const CertificateStep = ({isCasLoading,commonName,certificateTtlDays,- hsmConnectorOptions,- isHsmConnectorsLoading,- caSwap,- canEditSubject,- keySourceChanged+ canEditSubject}: CertificateStepProps) => {- const { subscription } = useSubscription();- const isHsmLicensed = Boolean(subscription?.hsm);- const { permission } = useProjectPermission();- const canAttachHsm = permission.can(- ProjectPermissionHsmConnectorActions.Attach,- ProjectPermissionSub.HsmConnectors- );+ const selectedCaId = form.watch("caId");+ const selectedCa = caOptions.find((o) => o.id === selectedCaId) ?? null;+ const caps = getCaIssuanceCapabilities(selectedCa?.caType);++ const digicertCfg = selectedCa?.digicert;+ const canReuseOrder = canEditSubject && caps.supportsExistingOrderReuse && Boolean(digicertCfg);+ const { data: codeSigningOrders = [], isLoading: isOrdersLoading } =+ useDigiCertConnectionListCodeSigningOrders(+ digicertCfg?.appConnectionId ?? "",+ digicertCfg?.organizationId ?? 0,+ digicertCfg?.productNameId ?? "",+ { enabled: canReuseOrder }+ );++ const orderOptions = codeSigningOrders.map((o) => ({+ value: String(o.orderId),+ label: `${o.commonName || "Code signing certificate"} (#${o.orderId})`,+ commonName: o.commonName+ }));+ type OrderOption = (typeof orderOptions)[number];++ const reissueOrderId = form.watch("reissueFromExternalOrderId");+ const isReissue = Boolean(reissueOrderId);++ useEffect(() => {+ if (!canReuseOrder && reissueOrderId) {+ form.setValue("reissueFromExternalOrderId", null);+ }+ }, [canReuseOrder, reissueOrderId, form]);- const keySource = form.watch("keySource");- const isHsm = keySource === CertKeySource.Hsm;+ useEffect(() => {+ if (+ canReuseOrder &&+ !isOrdersLoading &&+ reissueOrderId &&+ !codeSigningOrders.some((order) => String(order.orderId) === reissueOrderId)+ ) {+ form.setValue("reissueFromExternalOrderId", null);+ }+ }, [canReuseOrder, isOrdersLoading, reissueOrderId, codeSigningOrders, form]);return (<FieldGroup>@@ -110,193 +120,128 @@ export const CertificateStep = ({)}/>- {canEditSubject ? (- <Controller- name="commonName"- control={form.control}- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel>- Common Name <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <Input- {...field}- value={field.value ?? ""}- placeholder="Acme Mobile, Inc."- isError={Boolean(error)}- />- <FieldDescription>- The legal name shown on the certificate. Editable while no certificate has been- issued. Locked once the signer becomes Active.- </FieldDescription>- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}- />- ) : (- <Field>- <FieldLabel>Common Name</FieldLabel>- <FieldContent>- <Input value={commonName} readOnly disabled />- <FieldDescription>The legal name shown on the certificate.</FieldDescription>- </FieldContent>- </Field>- )}-- {canEditSubject ? (+ {canReuseOrder && (<Controller- name="certificateTtlDays"+ name="reissueFromExternalOrderId"control={form.control}- render={({ field, fieldState: { error } }) => (+ render={({ field }) => (<Field><FieldLabel>- Validity (days) <span className="text-danger">*</span>+ <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>- <Input- type="number"- min={1}- max={3650}- value={field.value ?? ""}- onChange={(e) => field.onChange(Number(e.target.value))}- placeholder="365"- isError={Boolean(error)}+ <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>- How long each issued certificate stays valid. Locked once the signer becomes- Active.- </FieldDescription>- <FieldError errors={[error]} />+ <FieldDescription>Leave empty to issue a new certificate.</FieldDescription></FieldContent></Field>)}/>- ) : (- <Field>- <FieldLabel>Validity (days)</FieldLabel>- <FieldContent>- <Input- value={certificateTtlDays != null ? String(certificateTtlDays) : "—"}- readOnly- disabled- />- <FieldDescription>How long each issued certificate stays valid.</FieldDescription>- </FieldContent>- </Field>)}- <Controller- name="keySource"- control={form.control}- render={({ field }) => (+ {!isReissue &&+ (canEditSubject ? (+ <Controller+ name="commonName"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Common Name <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Input+ {...field}+ value={field.value ?? ""}+ placeholder="Acme Mobile, Inc."+ isError={Boolean(error)}+ />+ <FieldDescription>+ The legal name on the certificate. Locked once the signer is active.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ ) : (<Field>- <FieldLabel>Key source</FieldLabel>+ <FieldLabel>Common Name</FieldLabel><FieldContent>- <Select value={field.value} onValueChange={field.onChange}>- <SelectTrigger className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- <SelectItem value={CertKeySource.Infisical}>Infisical</SelectItem>- <SelectItem value={CertKeySource.Hsm} disabled={!isHsmLicensed || !canAttachHsm}>- <div className="flex items-center gap-2">- HSM- {!isHsmLicensed && <Badge variant="info">Enterprise</Badge>}- {isHsmLicensed && !canAttachHsm && (- <Badge variant="warning">Permission required</Badge>- )}- </div>- </SelectItem>- </SelectContent>- </Select>- <FieldDescription>- Switching key source reissues the certificate with a new key.- </FieldDescription>+ <Input value={commonName} readOnly disabled />+ <FieldDescription>The legal name shown on the certificate.</FieldDescription></FieldContent></Field>- )}- />+ ))}- <Controller- name="keyAlgorithm"- control={form.control}- render={({ field, fieldState: { error } }) => {- const options = isHsm- ? Object.values(SignerKeyAlgorithm).filter((v) =>- HSM_SUPPORTED_KEY_ALGORITHMS.includes(v)- )- : Object.values(SignerKeyAlgorithm);- return (- <Field>- <FieldLabel>Key algorithm</FieldLabel>- <FieldContent>- <Select- value={field.value}- onValueChange={field.onChange}- disabled={!keySourceChanged}- >- <SelectTrigger className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- {options.map((value) => (- <SelectItem key={value} value={value}>- {signerKeyAlgorithmLabels[value]}- </SelectItem>- ))}- </SelectContent>- </Select>- <FieldDescription>- {keySourceChanged- ? "Pick the algorithm for the new key."- : "Algorithm of the signer's current key. Switch key source to generate a new one."}- </FieldDescription>- <FieldError errors={[error]} />- </FieldContent>- </Field>- );- }}- />-- {isHsm && (- <Controller- name="hsmConnectorId"- control={form.control}- render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel>- HSM Connector <span className="text-danger">*</span>- </FieldLabel>- <FieldContent>- <FilterableSelect<HsmConnectorOption>- isLoading={isHsmConnectorsLoading}- options={hsmConnectorOptions}- value={hsmConnectorOptions.find((o) => o.id === field.value) ?? null}- onChange={(selected) => {- const opt = selected as HsmConnectorOption | null;- field.onChange(opt?.id ?? null);- }}- getOptionLabel={(opt) => `${opt.name} (slot ${opt.slotLabel})`}- getOptionValue={(opt) => opt.id}- placeholder="Select an HSM Connector..."- noOptionsMessage={() =>- hsmConnectorOptions.length === 0- ? "No HSM Connectors configured. Add one in Cert Manager Settings → HSM Connectors."- : "No match."- }- isError={Boolean(error)}- />- <FieldDescription>- The HSM on which Infisical will generate the signing key.- </FieldDescription>- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}- />- )}+ {!isReissue &&+ (canEditSubject ? (+ <Controller+ name="certificateTtlDays"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Validity (days) <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Input+ type="number"+ min={1}+ max={3650}+ value={field.value ?? ""}+ onChange={(e) => field.onChange(Number(e.target.value))}+ placeholder="365"+ isError={Boolean(error)}+ />+ <FieldDescription>+ How long each certificate stays valid. Locked once the signer is active.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ ) : (+ <Field>+ <FieldLabel>Validity (days)</FieldLabel>+ <FieldContent>+ <Input+ value={certificateTtlDays != null ? String(certificateTtlDays) : "—"}+ readOnly+ disabled+ />+ <FieldDescription>How long each issued certificate stays valid.</FieldDescription>+ </FieldContent>+ </Field>+ ))}<Controllername="certificateRenewBeforeDays"@@ -318,19 +263,13 @@ export const CertificateStep = ({isError={Boolean(error)}/><FieldDescription>- Renew the certificate this many days before it expires.+ Renew this many days before the certificate expires.</FieldDescription><FieldError errors={[error]} /></FieldContent></Field>)}/>-- {(caSwap || keySourceChanged) && (- <div className="rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning">- Saving will issue a new certificate right away.- </div>- )}</FieldGroup>);};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsxindex 0571312d7f..0668e6338b 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx@@ -1,7 +1,7 @@-import { useMemo, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { ShieldIcon } from "lucide-react";+import { PenTool } from "lucide-react";import { createNotification } from "@app/components/notifications";import {@@ -16,8 +16,9 @@ import {StepperStep} from "@app/components/v3";import { useSubscription } from "@app/context";-import { useListCasByProjectId } from "@app/hooks/api/ca";+import { getCaIssuanceCapabilities, useListCasByProjectId } from "@app/hooks/api/ca";import { CaStatus, CaType } from "@app/hooks/api/ca/enums";+import { DigiCertCaPurpose } from "@app/hooks/api/ca/types";import { useListHsmConnectors } from "@app/hooks/api/hsmConnectors";import {CertKeySource,@@ -28,6 +29,7 @@ import {useUpdateSigner} from "@app/hooks/api/signers";+import { SignerKeyStep } from "../../../components/SignerKeyStep";import { PkiDocsUrls } from "../../../pki-docs-urls";import { BasicsStep } from "./BasicsStep";import { CertificateStep } from "./CertificateStep";@@ -52,8 +54,13 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {enabled: Boolean(subscription?.hsm)});- const currentKeySource =- (signer.certificateKeySource as CertKeySource | undefined) ?? CertKeySource.Infisical;+ const signerCaType = useMemo(+ () => (cas.data ?? []).find((c) => c.id === signer.caId)?.type,+ [cas.data, signer.caId]+ );+ const currentKeySource = getCaIssuanceCapabilities(signerCaType).requiresHsm+ ? CertKeySource.Hsm+ : ((signer.certificateKeySource as CertKeySource | undefined) ?? CertKeySource.Infisical);const currentHsmConnectorId = signer.certificateHsmConnectorId ?? null;const currentKeyAlgorithm =(signer.keyAlgorithm as SignerKeyAlgorithm | undefined) ?? SignerKeyAlgorithm.RSA_2048;@@ -62,16 +69,28 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {const list = cas.data ?? [];return list.filter((ca) => ca.status === CaStatus.ACTIVE)- .filter(- (ca) =>- ca.type === CaType.INTERNAL ||- ca.type === CaType.AWS_PCA ||- ca.type === CaType.AZURE_AD_CS- )+ .filter((ca) => {+ if (ca.type === CaType.INTERNAL) return true;+ if (ca.type === CaType.AWS_PCA) return true;+ if (ca.type === CaType.AZURE_AD_CS) return true;+ if (ca.type === CaType.DIGICERT) {+ return ca.configuration?.purpose === DigiCertCaPurpose.CodeSigning;+ }+ return false;+ }).map((ca) => ({id: ca.id,name: ca.name,- groupType: ca.type === CaType.INTERNAL ? "internal" : "external"+ groupType: ca.type === CaType.INTERNAL ? "internal" : "external",+ caType: ca.type,+ digicert:+ ca.type === CaType.DIGICERT+ ? {+ appConnectionId: ca.configuration.appConnectionId,+ organizationId: ca.configuration.organizationId,+ productNameId: ca.configuration.productNameId+ }+ : undefined}));}, [cas.data]);@@ -92,7 +111,8 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {certificateTtlDays: signer.certificateTtlDays ?? 365,keySource: currentKeySource,keyAlgorithm: currentKeyAlgorithm,- hsmConnectorId: currentHsmConnectorId+ hsmConnectorId: currentHsmConnectorId,+ reissueFromExternalOrderId: null}});@@ -111,6 +131,17 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {const watchedTtl = certificateForm.watch("certificateTtlDays");const watchedKeySource = certificateForm.watch("keySource");const watchedHsmConnectorId = certificateForm.watch("hsmConnectorId");+ const watchedKeyAlgorithm = certificateForm.watch("keyAlgorithm");+ const watchedReissueOrderId = certificateForm.watch("reissueFromExternalOrderId");++ const selectedCa = caOptions.find((o) => o.id === watchedCaId) ?? null;+ const { requiresHsm } = getCaIssuanceCapabilities(selectedCa?.caType);++ useEffect(() => {+ if (requiresHsm && certificateForm.getValues("keySource") !== CertKeySource.Hsm) {+ certificateForm.setValue("keySource", CertKeySource.Hsm, { shouldValidate: false });+ }+ }, [requiresHsm, certificateForm]);const caSwap = Boolean(watchedCaId) && watchedCaId !== signer.caId;const subjectChanged =@@ -121,7 +152,10 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {watchedKeySource !== currentKeySource ||(watchedKeySource === CertKeySource.Hsm &&(watchedHsmConnectorId ?? null) !== currentHsmConnectorId);- const shouldReissue = caSwap || subjectChanged || keySourceChanged;+ const keyAlgorithmChanged = watchedKeyAlgorithm !== currentKeyAlgorithm;+ const isReissueFromOrder = Boolean(watchedReissueOrderId);+ const shouldReissue =+ caSwap || subjectChanged || keySourceChanged || keyAlgorithmChanged || isReissueFromOrder;const handleOpenChange = (open: boolean) => {if (!open) {@@ -134,7 +168,8 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {certificateTtlDays: signer.certificateTtlDays ?? 365,keySource: currentKeySource,keyAlgorithm: currentKeyAlgorithm,- hsmConnectorId: currentHsmConnectorId+ hsmConnectorId: currentHsmConnectorId,+ reissueFromExternalOrderId: null});}onOpenChange(open);@@ -156,19 +191,24 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {await reissueCertificate.mutateAsync({signerId: signer.id,caId: cert.caId,- commonName: canEditSubject && subjectChanged ? cert.commonName : undefined,+ commonName:+ !isReissueFromOrder && canEditSubject && subjectChanged ? cert.commonName : undefined,certificateTtlDays:- canEditSubject && subjectChanged ? cert.certificateTtlDays : undefined,- keyAlgorithm: keySourceChanged ? cert.keyAlgorithm : undefined,- certificate: keySourceChanged- ? {- keySource: cert.keySource,- hsmConnectorId:- cert.keySource === CertKeySource.Hsm- ? (cert.hsmConnectorId ?? undefined)- : undefined- }- : undefined+ !isReissueFromOrder && canEditSubject && subjectChanged+ ? cert.certificateTtlDays+ : undefined,+ keyAlgorithm: keySourceChanged || keyAlgorithmChanged ? cert.keyAlgorithm : undefined,+ certificate:+ keySourceChanged || keyAlgorithmChanged+ ? {+ keySource: cert.keySource,+ hsmConnectorId:+ cert.keySource === CertKeySource.Hsm+ ? (cert.hsmConnectorId ?? undefined)+ : undefined+ }+ : undefined,+ reissueFromExternalOrderId: cert.reissueFromExternalOrderId ?? undefined});}@@ -200,7 +240,18 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {return;}if (step === 1) {- const ok = await certificateForm.trigger();+ const ok = await certificateForm.trigger([+ "caId",+ "commonName",+ "certificateTtlDays",+ "certificateRenewBeforeDays"+ ]);+ if (!ok) return;+ setStep(2);+ return;+ }+ if (step === 2) {+ const ok = await certificateForm.trigger(["keySource", "keyAlgorithm", "hsmConnectorId"]);if (!ok) return;await onSave();}@@ -222,7 +273,7 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {<SheetTitle><div className="flex w-full items-start gap-2"><div className="flex h-10 w-10 items-center justify-center rounded-md bg-warning/10 text-warning">- <ShieldIcon className="h-5 w-5" />+ <PenTool className="h-5 w-5" /></div><div><div className="flex items-center gap-x-2 text-mineshaft-300">@@ -277,11 +328,15 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {isCasLoading={cas.isPending}commonName={signer.commonName ?? signer.certificateCommonName ?? "—"}certificateTtlDays={signer.certificateTtlDays ?? null}+ canEditSubject={canEditSubject}+ />+ )}+ {step === 2 && (+ <SignerKeyStep+ control={certificateForm.control}+ requiresHsm={requiresHsm}hsmConnectorOptions={hsmConnectorOptions}isHsmConnectorsLoading={isHsmConnectorsLoading}- caSwap={caSwap}- canEditSubject={canEditSubject}- keySourceChanged={keySourceChanged}/>)}</div>diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.tsindex 85ca229867..4690cc3230 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts@@ -37,7 +37,9 @@ export const certificateSchema = zcertificateTtlDays: 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()+ 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)}).refine((data) =>diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/types.ts b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/types.tsindex cf8f9dd9ab..1179b09201 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/types.ts+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/types.ts@@ -1,7 +1,15 @@+import { CaType } from "@app/hooks/api/ca/enums";+import { PkiDocsUrls } from "../../../pki-docs-urls";export type CaGroup = "internal" | "external";-export type CaOption = { id: string; name: string; groupType: CaGroup };+export type CaOption = {+ id: string;+ name: string;+ groupType: CaGroup;+ caType: CaType;+ digicert?: { appConnectionId: string; organizationId: number; productNameId: string };+};export type StepConfig = {name: string;@@ -26,12 +34,22 @@ export const STEPS: StepConfig[] = [},{name: "Certificate",- shortDescription: "Validity and CA",+ shortDescription: "CA and identity",title: "Certificate",subtitle: "The certificate behind this signer.",rightLabel: "CERTIFICATE",rightDescription:- "Adjust how early to auto-renew, and which CA issues the certificate. Swapping the CA reissues the certificate right away.",+ "Choose which CA issues the certificate and review its name and validity. Swapping the CA reissues the certificate right away.",+ docsUrl: PkiDocsUrls.codeSigning.signers.editCertificate+ },+ {+ name: "Signing Key",+ shortDescription: "Key storage and algorithm",+ title: "Signing Key",+ subtitle: "Where the signing key lives and which algorithm to use.",+ rightLabel: "SIGNING KEY",+ rightDescription:+ "Changing the key source or algorithm reissues the certificate with a new key. Some CAs require an HSM-backed key.",docsUrl: PkiDocsUrls.codeSigning.signers.editCertificate}];diff --git a/frontend/src/pages/cert-manager/components/SignerKeyStep.tsx b/frontend/src/pages/cert-manager/components/SignerKeyStep.tsxnew file mode 100644index 0000000000..80c035b1dd--- /dev/null+++ b/frontend/src/pages/cert-manager/components/SignerKeyStep.tsx@@ -0,0 +1,191 @@+import { ReactNode } from "react";+import { Control, Controller, useWatch } from "react-hook-form";+import { AlertTriangleIcon } from "lucide-react";++import {+ Badge,+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldGroup,+ FieldLabel,+ FilterableSelect,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { useProjectPermission, useSubscription } from "@app/context";+import {+ ProjectPermissionHsmConnectorActions,+ ProjectPermissionSub+} from "@app/context/ProjectPermissionContext/types";+import {+ CertKeySource,+ HSM_SUPPORTED_KEY_ALGORITHMS,+ SignerKeyAlgorithm,+ signerKeyAlgorithmLabels+} from "@app/hooks/api/signers";++export type HsmConnectorOption = { id: string; name: string; slotLabel: string };++type SignerKeyStepProps = {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ control: Control<any>;+ requiresHsm: boolean;+ hsmConnectorOptions: HsmConnectorOption[];+ isHsmConnectorsLoading: boolean;+};++export const SignerKeyStep = ({+ control,+ requiresHsm,+ hsmConnectorOptions,+ isHsmConnectorsLoading+}: SignerKeyStepProps) => {+ const { subscription } = useSubscription();+ const isHsmLicensed = Boolean(subscription?.hsm);+ const { permission } = useProjectPermission();+ const canAttachHsm = permission.can(+ ProjectPermissionHsmConnectorActions.Attach,+ ProjectPermissionSub.HsmConnectors+ );++ const keySource = useWatch({ control, name: "keySource" });+ const isHsm = keySource === CertKeySource.Hsm;++ let keySourceHint: ReactNode = "Infisical manages the keypair.";+ if (requiresHsm) {+ keySourceHint = (+ <span className="inline-flex items-center gap-1.5">+ <Tooltip>+ <TooltipTrigger asChild>+ <AlertTriangleIcon className="h-3.5 w-3.5 shrink-0 text-warning" />+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ This CA only issues certificates with an HSM-backed key.+ </TooltipContent>+ </Tooltip>+ HSM required by this CA.+ </span>+ );+ } else if (isHsm) {+ keySourceHint = "Uses an HSM-backed key.";+ }++ return (+ <FieldGroup>+ <Controller+ name="keySource"+ control={control}+ render={({ field }) => (+ <Field>+ <FieldLabel>+ Key source <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Select value={field.value} onValueChange={field.onChange} disabled={requiresHsm}>+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ <SelectItem value={CertKeySource.Infisical} disabled={requiresHsm}>+ Infisical+ </SelectItem>+ <SelectItem value={CertKeySource.Hsm} disabled={!isHsmLicensed || !canAttachHsm}>+ <div className="flex items-center gap-2">+ HSM+ {!isHsmLicensed && <Badge variant="info">Enterprise</Badge>}+ {isHsmLicensed && !canAttachHsm && (+ <Badge variant="warning">Permission required</Badge>+ )}+ </div>+ </SelectItem>+ </SelectContent>+ </Select>+ <FieldDescription>{keySourceHint}</FieldDescription>+ </FieldContent>+ </Field>+ )}+ />++ {isHsm && (+ <Controller+ name="hsmConnectorId"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ HSM Connector <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <FilterableSelect<HsmConnectorOption>+ isLoading={isHsmConnectorsLoading}+ options={hsmConnectorOptions}+ value={hsmConnectorOptions.find((o) => o.id === field.value) ?? null}+ onChange={(selected) => {+ const opt = selected as HsmConnectorOption | null;+ field.onChange(opt?.id ?? null);+ }}+ getOptionLabel={(opt) => `${opt.name} (slot ${opt.slotLabel})`}+ getOptionValue={(opt) => opt.id}+ placeholder="Select an HSM Connector..."+ noOptionsMessage={() =>+ hsmConnectorOptions.length === 0+ ? "No HSM Connectors configured. Add one in Settings → HSM Connectors."+ : "No match."+ }+ isError={Boolean(error)}+ />+ <FieldDescription>Which HSM connector to use.</FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ )}++ <Controller+ name="keyAlgorithm"+ control={control}+ render={({ field, fieldState: { error } }) => {+ const options = isHsm+ ? Object.values(SignerKeyAlgorithm).filter((v) =>+ HSM_SUPPORTED_KEY_ALGORITHMS.includes(v)+ )+ : Object.values(SignerKeyAlgorithm);+ return (+ <Field>+ <FieldLabel>+ Key algorithm <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Select value={field.value} onValueChange={field.onChange}>+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ {options.map((value) => (+ <SelectItem key={value} value={value}>+ {signerKeyAlgorithmLabels[value]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldDescription>+ RSA is widely compatible; ECDSA is smaller and faster.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ );+ }}+ />+ </FieldGroup>+ );+};