Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Address PR comments
Carlos Monastyrski776044e61fca
diff --git a/backend/src/db/migrations/20260630173512_add-certificates-digicert-order-index.ts b/backend/src/db/migrations/20260630173512_add-certificates-digicert-order-index.tsnew file mode 100644index 0000000000..5b8cb86126--- /dev/null+++ b/backend/src/db/migrations/20260630173512_add-certificates-digicert-order-index.ts@@ -0,0 +1,40 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++const INDEX_NAME = "certificates_digicert_order_idx";+const MIGRATION_TIMEOUT = 60 * 60 * 1000;+const MIGRATION_LOCK_TIMEOUT = 30 * 1000;++export async function up(knex: Knex): Promise<void> {+ const stmtResult = await knex.raw("SHOW statement_timeout");+ const originalStatementTimeout = stmtResult.rows[0].statement_timeout;+ const lockResult = await knex.raw("SHOW lock_timeout");+ const originalLockTimeout = lockResult.rows[0].lock_timeout;++ try {+ await knex.raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);+ await knex.raw(`SET lock_timeout = ${MIGRATION_LOCK_TIMEOUT}`);++ if (+ (await knex.schema.hasTable(TableName.Certificate)) &&+ (await knex.schema.hasColumn(TableName.Certificate, "externalMetadata"))+ ) {+ await knex.raw(`+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${INDEX_NAME}"+ ON ${TableName.Certificate} ("caId", ("externalMetadata"->>'orderId'))+ WHERE "externalMetadata"->>'type' = 'digicert'+ `);+ }+ } finally {+ await knex.raw(`SET statement_timeout = '${originalStatementTimeout}'`);+ await knex.raw(`SET lock_timeout = '${originalLockTimeout}'`);+ }+}++export async function down(knex: Knex): Promise<void> {+ await knex.raw(`DROP INDEX CONCURRENTLY IF EXISTS "${INDEX_NAME}"`);+}++const config = { transaction: false };+export { config };diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 47abfb7e6d..e08fade3f6 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -55,6 +55,7 @@ import {} from "@app/services/secret-sync/secret-sync-types";import { TDuplicateSecretAttributes } from "@app/services/secret-v2-bridge/secret-v2-bridge-types";import { CertKeySource } from "@app/services/signer/signer-enums";+import { TSignerExternalConfigurationInput } from "@app/services/signer/signer-types";import { TWebhookPayloads } from "@app/services/webhook/webhook-types";import { WorkflowIntegration } from "@app/services/workflow-integration/workflow-integration-types";@@ -4918,7 +4919,7 @@ interface CreatePkiSignerEvent {approvalPolicyId?: string | null;keySource?: CertKeySource;hsmConnectorId?: string | null;- reissueFromExternalOrderId?: string | null;+ externalConfiguration?: TSignerExternalConfigurationInput;};}@@ -5007,7 +5008,7 @@ interface ReissuePkiSignerCertificateEvent {keySource?: string;hsmConnectorId?: string;hsmKeyAlgorithm?: string;- reissueFromExternalOrderId?: string;+ externalConfiguration?: TSignerExternalConfigurationInput;};}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 7975c7161d..71a2aa491c 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@@ -81,12 +81,12 @@ export const registerDigiCertConnectionRouter = async (server: FastifyZodProvideserver.route({method: "GET",- url: `/:connectionId/organizations/:organizationId/code-signing-validation`,+ url: `/:connectionId/organizations/:organizationId/validation`,config: {rateLimit: readLimit},schema: {- operationId: "getDigiCertOrgCodeSigningValidation",+ operationId: "getDigiCertOrgValidation",params: z.object({connectionId: z.string().uuid(),organizationId: z.coerce.number().int().positive()@@ -104,7 +104,7 @@ export const registerDigiCertConnectionRouter = async (server: FastifyZodProvidehandler: async (req) => {const { connectionId, organizationId } = req.params;const { productNameId } = req.query;- return server.services.appConnection.digicert.getCodeSigningValidation(+ return server.services.appConnection.digicert.getOrgValidation(connectionId,organizationId,productNameId,@@ -115,12 +115,12 @@ export const registerDigiCertConnectionRouter = async (server: FastifyZodProvideserver.route({method: "GET",- url: `/:connectionId/organizations/:organizationId/code-signing-orders`,+ url: `/:connectionId/organizations/:organizationId/orders`,config: {rateLimit: readLimit},schema: {- operationId: "listDigiCertCodeSigningOrders",+ operationId: "listDigiCertOrders",params: z.object({connectionId: z.string().uuid(),organizationId: z.coerce.number().int().positive()@@ -133,6 +133,7 @@ export const registerDigiCertConnectionRouter = async (server: FastifyZodProvide.object({orderId: z.number(),commonName: z.string(),+ organizationName: z.string(),status: z.string(),validTill: z.string().optional()})@@ -143,7 +144,7 @@ export const registerDigiCertConnectionRouter = async (server: FastifyZodProvidehandler: async (req) => {const { connectionId, organizationId } = req.params;const { productNameId } = req.query;- return server.services.appConnection.digicert.listCodeSigningOrders(+ return server.services.appConnection.digicert.listOrders(connectionId,organizationId,productNameId,diff --git a/backend/src/server/routes/v1/signer-routers/certificate-router.ts b/backend/src/server/routes/v1/signer-routers/certificate-router.tsindex 4d13d0496d..bcbc3ca26a 100644--- a/backend/src/server/routes/v1/signer-routers/certificate-router.ts+++ b/backend/src/server/routes/v1/signer-routers/certificate-router.ts@@ -8,7 +8,12 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";import { CertKeySource } from "@app/services/signer/signer-enums";-import { HSM_SUPPORTED_KEY_ALGORITHMS, SignerIdParamsSchema, SignerKeyAlgorithm } from "./schemas";+import {+ HSM_SUPPORTED_KEY_ALGORITHMS,+ SignerExternalConfigurationSchema,+ SignerIdParamsSchema,+ SignerKeyAlgorithm+} from "./schemas";export const registerSignerCertificateRouter = async (server: FastifyZodProvider) => {server.route({@@ -33,14 +38,7 @@ export const registerSignerCertificateRouter = async (server: FastifyZodProviderhsmConnectorId: 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."- )+ externalConfiguration: SignerExternalConfigurationSchema.optional()}).superRefine((data, ctx) => {if (data.certificate?.keySource !== CertKeySource.Hsm) return;@@ -85,7 +83,7 @@ export const registerSignerCertificateRouter = async (server: FastifyZodProviderkeyAlgorithm: req.body.keyAlgorithm,keySource: req.body.certificate?.keySource,hsmConnectorId: req.body.certificate?.hsmConnectorId,- reissueFromExternalOrderId: req.body.reissueFromExternalOrderId+ externalConfiguration: req.body.externalConfiguration}}});diff --git a/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts b/backend/src/server/routes/v1/signer-routers/lifecycle-router.tsindex dedda03be2..3ed41e9400 100644--- a/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts+++ b/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts@@ -14,10 +14,24 @@ import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";import {ApprovalPolicyBodySchema,HSM_SUPPORTED_KEY_ALGORITHMS,+ SignerExternalConfigurationSchema,SignerIdParamsSchema,SignerKeyAlgorithm} from "./schemas";+const SignerWithCertificateResponseSchema = PkiSignersSchema.extend({+ certificateCommonName: z.string().nullable().optional(),+ certificateSerialNumber: z.string().nullable().optional(),+ certificateNotAfter: z.date().nullable().optional(),+ certificateNotBefore: z.date().nullable().optional(),+ certificateKeyAlgorithm: z.string().nullable().optional(),+ certificateKeySource: z.string().nullable().optional(),+ certificateHsmConnectorId: z.string().nullable().optional(),+ certificateStatus: z.string().nullable().optional(),+ certificateCaId: z.string().nullable().optional(),+ approvalPolicyName: z.string().nullable().optional()+});+export const registerSignerLifecycleRouter = async (server: FastifyZodProvider) => {server.route({method: "POST",@@ -45,18 +59,7 @@ 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(),+ externalConfiguration: SignerExternalConfigurationSchema.optional(),approvalPolicyId: z.string().uuid().optional(),members: z.array(@@ -113,7 +116,7 @@ export const registerSignerLifecycleRouter = async (server: FastifyZodProvider)approvalPolicyId: signer.approvalPolicyId,keySource: req.body.certificate?.keySource,hsmConnectorId: req.body.certificate?.hsmConnectorId,- reissueFromExternalOrderId: req.body.externalConfiguration?.reissueFromExternalOrderId+ externalConfiguration: req.body.externalConfiguration}}});@@ -200,18 +203,7 @@ export const registerSignerLifecycleRouter = async (server: FastifyZodProvider)description: "Get a code signing signer by ID",params: SignerIdParamsSchema,response: {- 200: PkiSignersSchema.extend({- certificateCommonName: z.string().nullable().optional(),- certificateSerialNumber: z.string().nullable().optional(),- certificateNotAfter: z.date().nullable().optional(),- certificateNotBefore: z.date().nullable().optional(),- certificateKeyAlgorithm: z.string().nullable().optional(),- certificateKeySource: z.string().nullable().optional(),- certificateHsmConnectorId: z.string().nullable().optional(),- certificateStatus: z.string().nullable().optional(),- certificateCaId: z.string().nullable().optional(),- approvalPolicyName: z.string().nullable().optional()- })+ 200: SignerWithCertificateResponseSchema}},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),@@ -280,6 +272,34 @@ export const registerSignerLifecycleRouter = async (server: FastifyZodProvider)}});+ server.route({+ method: "POST",+ url: "/:signerId/issuance/check",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "checkSignerIssuance",+ tags: [ApiDocsTags.PkiSigners],+ description:+ "Poll the upstream CA for a pending signer's certificate immediately instead of waiting for the next scheduled check.",+ params: SignerIdParamsSchema,+ response: {+ 200: SignerWithCertificateResponseSchema+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const signer = await server.services.pkiSigner.checkIssuanceNow({+ signerId: req.params.signerId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });+ return signer;+ }+ });+server.route({method: "PATCH",url: "/:signerId",diff --git a/backend/src/server/routes/v1/signer-routers/schemas.ts b/backend/src/server/routes/v1/signer-routers/schemas.tsindex cb26a3deb8..e7686a4b2d 100644--- a/backend/src/server/routes/v1/signer-routers/schemas.ts+++ b/backend/src/server/routes/v1/signer-routers/schemas.ts@@ -1,9 +1,24 @@import { z } from "zod";import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";+import { CaType } from "@app/services/certificate-authority/certificate-authority-enums";export const SignerIdParamsSchema = z.object({ signerId: z.string().uuid() });+export const SignerExternalConfigurationSchema = z.discriminatedUnion("caType", [+ z.object({+ caType: z.literal(CaType.DIGICERT),+ reissueFromExternalOrderId: z+ .string()+ .trim()+ .min(1)+ .optional()+ .describe(+ "Reissue into this existing DigiCert order instead of placing a new order (reuses the subscription slot)."+ )+ })+]);+export const SignerKeyAlgorithm = {values: [CertKeyAlgorithm.RSA_2048,diff --git a/backend/src/services/app-connection/digicert/digicert-connection-fns.ts b/backend/src/services/app-connection/digicert/digicert-connection-fns.tsindex d0543b8d09..07f4e8e61a 100644--- a/backend/src/services/app-connection/digicert/digicert-connection-fns.ts+++ b/backend/src/services/app-connection/digicert/digicert-connection-fns.ts@@ -102,11 +102,13 @@ const DIGICERT_CS_VALIDATION_TYPE_BY_PRODUCT: Record<string, string> = {code_signing_ev: "ev_cs"};+export const DIGICERT_CS_PRODUCT_NAME_IDS = new Set(Object.keys(DIGICERT_CS_VALIDATION_TYPE_BY_PRODUCT));+type TDigiCertOrgValidationResponse = {validations?: { type?: string; status?: string }[];};-export const isDigiCertOrgCodeSigningValidated = (+export const isDigiCertOrgValidatedForProduct = (validations: { type?: string; status?: string }[] | undefined,productNameId: string): boolean => {@@ -116,7 +118,7 @@ export const isDigiCertOrgCodeSigningValidated = ();};-export const getDigiCertOrgCodeSigningValidation = async (+export const getDigiCertOrgValidation = async (appConnection: TDigiCertConnection,organizationId: number,productNameId: string@@ -135,7 +137,7 @@ export const getDigiCertOrgCodeSigningValidation = async (});- return { isValidated: isDigiCertOrgCodeSigningValidated(data.validations, productNameId) };+ return { isValidated: isDigiCertOrgValidatedForProduct(data.validations, productNameId) };} catch (error: unknown) {if (error instanceof AxiosError) {throw new BadRequestError({@@ -155,18 +157,20 @@ type TDigiCertOrdersResponse = {}[];};-export type TDigiCertCodeSigningOrder = {+export type TDigiCertOrder = {orderId: number;commonName: string;+ organizationName: string;status: string;validTill?: string;};-export const listDigiCertCodeSigningOrders = async (+export const listDigiCertOrders = async (appConnection: TDigiCertConnection,organizationId: number,- productNameId: string-): Promise<TDigiCertCodeSigningOrder[]> => {+ productNameId: string,+ status = "issued"+): Promise<TDigiCertOrder[]> => {const { apiKey } = appConnection.credentials;const baseUrl = getDigiCertApiBaseUrl(appConnection.credentials);@@ -179,22 +183,22 @@ export const listDigiCertCodeSigningOrders = async (params: {"filters[product_name_id]": productNameId,"filters[organization_id]": organizationId,- "filters[status]": "issued",+ "filters[status]": status,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 || "",+ commonName: order.certificate?.common_name ?? "",+ organizationName: order.organization?.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)}`+ message: `Failed to list DigiCert orders: ${extractDigiCertErrorMessage(error)}`});}throw error;diff --git a/backend/src/services/app-connection/digicert/digicert-connection-service.ts b/backend/src/services/app-connection/digicert/digicert-connection-service.tsindex 94784eba4a..9e71055ceb 100644--- a/backend/src/services/app-connection/digicert/digicert-connection-service.ts+++ b/backend/src/services/app-connection/digicert/digicert-connection-service.ts@@ -3,8 +3,8 @@ import { OrgServiceActor } from "@app/lib/types";import { AppConnection } from "../app-connection-enums";import {- getDigiCertOrgCodeSigningValidation,- listDigiCertCodeSigningOrders,+ getDigiCertOrgValidation,+ listDigiCertOrders,listDigiCertOrganizations,listDigiCertProducts} from "./digicert-connection-fns";@@ -37,7 +37,7 @@ export const digicertConnectionService = (getAppConnection: TGetAppConnectionFun}};- const getCodeSigningValidation = async (+ const getOrgValidation = async (connectionId: string,organizationId: number,productNameId: string,@@ -45,14 +45,14 @@ export const digicertConnectionService = (getAppConnection: TGetAppConnectionFun) => {const appConnection = await getAppConnection(AppConnection.DigiCert, connectionId, actor);try {- return await getDigiCertOrgCodeSigningValidation(appConnection, organizationId, productNameId);+ return await getDigiCertOrgValidation(appConnection, organizationId, productNameId);} catch (error) {- logger.error(error, `Failed to check DigiCert code signing validation [connectionId=${connectionId}]`);+ logger.error(error, `Failed to check DigiCert organization validation [connectionId=${connectionId}]`);return { isValidated: false };}};- const listCodeSigningOrders = async (+ const listOrders = async (connectionId: string,organizationId: number,productNameId: string,@@ -60,9 +60,9 @@ export const digicertConnectionService = (getAppConnection: TGetAppConnectionFun) => {const appConnection = await getAppConnection(AppConnection.DigiCert, connectionId, actor);try {- return await listDigiCertCodeSigningOrders(appConnection, organizationId, productNameId);+ return await listDigiCertOrders(appConnection, organizationId, productNameId);} catch (error) {- logger.error(error, `Failed to list DigiCert code signing orders [connectionId=${connectionId}]`);+ logger.error(error, `Failed to list DigiCert orders [connectionId=${connectionId}]`);return [];}};@@ -70,7 +70,7 @@ export const digicertConnectionService = (getAppConnection: TGetAppConnectionFunreturn {listOrganizations,listProducts,- getCodeSigningValidation,- listCodeSigningOrders+ getOrgValidation,+ listOrders};};diff --git a/backend/src/services/certificate-authority/digicert/digicert-api-client.ts b/backend/src/services/certificate-authority/digicert/digicert-api-client.tsindex 0901feb928..0fadebc8e7 100644--- a/backend/src/services/certificate-authority/digicert/digicert-api-client.ts+++ b/backend/src/services/certificate-authority/digicert/digicert-api-client.ts@@ -99,11 +99,18 @@ export const createDigiCertApiClient = (apiKey: string, baseURL: string) => {const getOrdersByAlternativeId = async (alternativeOrderId: string) =>wrap(async () => {- const { data } = await request.get<TDigiCertAlternateOrdersResponse>(- `${baseURL}/order/alternate/${encodeURIComponent(alternativeOrderId)}`,- { headers }- );- return data;+ try {+ const { data } = await request.get<TDigiCertAlternateOrdersResponse>(+ `${baseURL}/order/alternate/${encodeURIComponent(alternativeOrderId)}`,+ { headers }+ );+ return data;+ } catch (error) {+ if (error instanceof AxiosError && error.response?.status === 404) {+ return { orders: [] };+ }+ throw error;+ }}, `alternate order lookup for ${alternativeOrderId}`);const revokeOrder = async (orderId: number, comments: string) =>diff --git a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-enums.ts b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-enums.tsindex e2b094f268..92ccaf68ca 100644--- a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-enums.ts+++ b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-enums.ts@@ -19,3 +19,14 @@ export enum DigiCertPollOutcome {Pending = "pending",Failed = "failed"}++export enum CodeSigningOrderStatus {+ Pending = "pending",+ NeedsApproval = "needs_approval",+ Processing = "processing",+ Issued = "issued",+ Rejected = "rejected",+ Canceled = "canceled",+ Expired = "expired",+ Revoked = "revoked"+}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 8ddb4868b0..7a40471dd4 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@@ -10,13 +10,8 @@ import { logger } from "@app/lib/logger";import { OrgServiceActor } from "@app/lib/types";import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";import { 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,- isDigiCertOrgCodeSigningValidated-} from "@app/services/app-connection/digicert/digicert-connection-fns";-import { TDigiCertConnection } from "@app/services/app-connection/digicert/digicert-connection-types";+import { DIGICERT_CS_PRODUCT_NAME_IDS } from "@app/services/app-connection/digicert/digicert-connection-fns";import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";@@ -41,17 +36,19 @@ import {} from "./digicert-certificate-authority-enums";import { DigiCertCaPurpose } from "./digicert-certificate-authority-schemas";import {- TCodeSigningOrderInfo,- TCodeSigningOrderStatus,+ castDbEntryToDigiCertCertificateAuthority,+ extractLeafAndChain,+ getDigiCertClientCredentials+} from "./digicert-certificate-authority-shared";+import {TCreateDigiCertCertificateAuthorityDTO,- TDigiCertCertificateAuthority,TDigiCertCertificateRequestMetadata,- TPlaceCodeSigningOrderRequest,- TPlaceCodeSigningOrderResponse,TPlaceOrderResponse,- TReissueCodeSigningOrderRequest,TUpdateDigiCertCertificateAuthorityDTO} from "./digicert-certificate-authority-types";+import { digiCertCodeSigningFns } from "./digicert-code-signing-fns";++export { castDbEntryToDigiCertCertificateAuthority, getDigiCertClientCredentials };type TDigiCertCertificateAuthorityFnsDeps = {appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;@@ -71,102 +68,21 @@ type TDigiCertCertificateAuthorityFnsDeps = {projectDAL: Pick<TProjectDALFactory, "findById" | "findOne" | "updateById" | "transaction">;};-export const castDbEntryToDigiCertCertificateAuthority = (- ca: Awaited<ReturnType<TCertificateAuthorityDALFactory["findByIdWithAssociatedCa"]>>-): TDigiCertCertificateAuthority & { credentials: Buffer | null | undefined } => {- if (!ca.externalCa?.id) {- throw new BadRequestError({ message: "Malformed DigiCert certificate authority" });- }-- if (!ca.externalCa.appConnectionId) {- throw new BadRequestError({- message: "DigiCert app connection ID is missing from certificate authority configuration"- });- }-- 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) {- throw new BadRequestError({- message: "DigiCert certificate authority configuration is missing organization ID or product"- });- }-- const purpose = config.purpose ?? DigiCertCaPurpose.Ssl;-- return {- id: ca.id,- type: CaType.DIGICERT,- enableDirectIssuance: ca.enableDirectIssuance,- name: ca.name,- projectId: ca.projectId,- credentials: ca.externalCa.credentials,- configuration: {- appConnectionId: ca.externalCa.appConnectionId,- organizationId: config.organizationId,- productNameId: config.productNameId,- purpose,- verifiedContact: config.verifiedContact- },- status: ca.status as CaStatus- };-};--export const getDigiCertClientCredentials = async (- appConnectionId: string,- appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">,- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">-): Promise<{ apiKey: string; baseUrl: string }> => {- const appConnection = await appConnectionDAL.findById(appConnectionId);- if (!appConnection) {- throw new NotFoundError({ message: `DigiCert app connection with ID '${appConnectionId}' not found` });- }- if (appConnection.app !== AppConnection.DigiCert) {- throw new BadRequestError({ message: `App connection with ID '${appConnectionId}' is not a DigiCert connection` });- }-- const credentials = (await decryptAppConnectionCredentials({- orgId: appConnection.orgId,- projectId: appConnection.projectId,- encryptedCredentials: appConnection.encryptedCredentials,- kmsService- })) as TDigiCertConnection["credentials"];-- return {- apiKey: credentials.apiKey,- baseUrl: getDigiCertApiBaseUrl(credentials)- };-};--const DIGICERT_CS_PRODUCT_NAME_IDS = new Set(["code_signing", "code_signing_ev"]);--const assertPurposeMatchesProduct = (purpose: DigiCertCaPurpose, productNameId: string): void => {+const assertPurposeMatchesProduct = (purpose: DigiCertCaPurpose | undefined, productNameId: string): void => {+ const effectivePurpose = purpose ?? DigiCertCaPurpose.Ssl;const isCsProduct = DIGICERT_CS_PRODUCT_NAME_IDS.has(productNameId);- if (purpose === DigiCertCaPurpose.CodeSigning && !isCsProduct) {+ if (effectivePurpose === 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) {+ if (effectivePurpose === 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])$");const parseTtlToDays = (ttl: string): number => {const match = ttl.match(TTL_RE2);@@ -190,40 +106,6 @@ const parseTtlToDays = (ttl: string): number => {}};-const extractLeafAndChain = (pemBundle: string): { leaf: string; chain: string } => {- const matches = pemBundle.match(PEM_CERTIFICATE_RE2);- if (!matches || matches.length === 0) {- throw new BadRequestError({ message: "DigiCert returned an empty certificate bundle" });- }-- if (matches.length < 2) {- throw new BadRequestError({- message: `DigiCert returned an incomplete certificate bundle (${matches.length} entry, expected leaf + chain)`- });- }-- let leafIndex = -1;- matches.forEach((pem, index) => {- if (leafIndex !== -1) return;- try {- const cert = new x509.X509Certificate(pem);- const basicConstraints = cert.getExtension(x509.BasicConstraintsExtension);- if (!basicConstraints?.ca) leafIndex = index;- } catch {- // skip unparseable entries- }- });-- if (leafIndex === -1) leafIndex = 0;-- const leaf = matches[leafIndex].trim();- const chain = matches- .filter((_, index) => index !== leafIndex)- .map((cert) => cert.trim())- .join("\n");- return { leaf, chain };-};-export const DigiCertCertificateAuthorityFns = ({appConnectionDAL,appConnectionService,@@ -235,42 +117,14 @@ 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 codeSigningFns = digiCertCodeSigningFns({+ appConnectionDAL,+ certificateAuthorityDAL,+ certificateDAL,+ certificateBodyDAL,+ kmsService,+ projectDAL+ });const createCertificateAuthority = async ({name,@@ -303,10 +157,15 @@ export const DigiCertCertificateAuthorityFns = ({actor);- assertPurposeMatchesProduct(purpose ?? DigiCertCaPurpose.Ssl, productNameId);+ assertPurposeMatchesProduct(purpose, productNameId);- if ((purpose ?? DigiCertCaPurpose.Ssl) === DigiCertCaPurpose.CodeSigning) {- await assertCsOrgValidatedOrContactProvided({ appConnectionId, organizationId, productNameId, verifiedContact });+ if (purpose === DigiCertCaPurpose.CodeSigning) {+ await codeSigningFns.assertCsOrgValidatedOrContactProvided({+ appConnectionId,+ organizationId,+ productNameId,+ verifiedContact+ });}const caEntity = await certificateAuthorityDAL.transaction(async (tx) => {@@ -392,11 +251,10 @@ export const DigiCertCertificateAuthorityFns = ({actor);- const resolvedPurpose = purpose ?? DigiCertCaPurpose.Ssl;- assertPurposeMatchesProduct(resolvedPurpose, productNameId);+ assertPurposeMatchesProduct(purpose, productNameId);- if (resolvedPurpose === DigiCertCaPurpose.CodeSigning) {- await assertCsOrgValidatedOrContactProvided({+ if (purpose === DigiCertCaPurpose.CodeSigning) {+ await codeSigningFns.assertCsOrgValidatedOrContactProvided({appConnectionId,organizationId,productNameId,@@ -821,289 +679,6 @@ 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,@@ -1112,11 +687,12 @@ export const DigiCertCertificateAuthorityFns = ({fetchAndAttachIssuedCertificate,pollOrderForCertificate,revokeCertificate,- orderCodeSigningCertificate,- reissueCodeSigningCertificate,- findCodeSigningOrderByReference,- getCodeSigningOrderStatus,- downloadCodeSigningCertificate+ orderCodeSigningCertificate: codeSigningFns.orderCodeSigningCertificate,+ reissueCodeSigningCertificate: codeSigningFns.reissueCodeSigningCertificate,+ findCodeSigningOrderByReference: codeSigningFns.findCodeSigningOrderByReference,+ assertCodeSigningOrderReusable: codeSigningFns.assertCodeSigningOrderReusable,+ getCodeSigningOrderStatus: codeSigningFns.getCodeSigningOrderStatus,+ downloadCodeSigningCertificate: codeSigningFns.downloadCodeSigningCertificate};};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 a4358bb336..8bfdf8ec69 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@@ -39,7 +39,7 @@ export const DigiCertCertificateAuthorityConfigurationSchema = z.object({telephone: z.string().trim().min(1).max(32)}).optional()- .describe("Contact info for the user who approves first-time CS orders for the organization")+ .describe("Contact info for the user who approves first-time code signing orders for the organization")});export const DigiCertCertificateAuthoritySchema = BaseCertificateAuthoritySchema.extend({diff --git a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-shared.ts b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-shared.tsnew file mode 100644index 0000000000..a7296f7c98--- /dev/null+++ b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-shared.ts@@ -0,0 +1,129 @@+import * as x509 from "@peculiar/x509";+import RE2 from "re2";++import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";+import { getDigiCertApiBaseUrl } from "@app/services/app-connection/digicert/digicert-connection-fns";+import { TDigiCertConnection } from "@app/services/app-connection/digicert/digicert-connection-types";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";++import { TCertificateAuthorityDALFactory } from "../certificate-authority-dal";+import { CaStatus, CaType } from "../certificate-authority-enums";+import { DigiCertCaPurpose } from "./digicert-certificate-authority-schemas";+import { TDigiCertCertificateAuthority } from "./digicert-certificate-authority-types";++const PEM_CERTIFICATE_RE2 = new RE2("-----BEGIN CERTIFICATE-----[\\s\\S]*?-----END CERTIFICATE-----", "g");++export const castDbEntryToDigiCertCertificateAuthority = (+ ca: Awaited<ReturnType<TCertificateAuthorityDALFactory["findByIdWithAssociatedCa"]>>+): TDigiCertCertificateAuthority & { credentials: Buffer | null | undefined } => {+ if (!ca.externalCa?.id) {+ throw new BadRequestError({ message: "Malformed DigiCert certificate authority" });+ }++ if (!ca.externalCa.appConnectionId) {+ throw new BadRequestError({+ message: "DigiCert app connection ID is missing from certificate authority configuration"+ });+ }++ 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) {+ throw new BadRequestError({+ message: "DigiCert certificate authority configuration is missing organization ID or product"+ });+ }++ const purpose = config.purpose ?? DigiCertCaPurpose.Ssl;++ return {+ id: ca.id,+ type: CaType.DIGICERT,+ enableDirectIssuance: ca.enableDirectIssuance,+ name: ca.name,+ projectId: ca.projectId,+ credentials: ca.externalCa.credentials,+ configuration: {+ appConnectionId: ca.externalCa.appConnectionId,+ organizationId: config.organizationId,+ productNameId: config.productNameId,+ purpose,+ verifiedContact: config.verifiedContact+ },+ status: ca.status as CaStatus+ };+};++export const getDigiCertClientCredentials = async (+ appConnectionId: string,+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">,+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">+): Promise<{ apiKey: string; baseUrl: string }> => {+ const appConnection = await appConnectionDAL.findById(appConnectionId);+ if (!appConnection) {+ throw new NotFoundError({ message: `DigiCert app connection with ID '${appConnectionId}' not found` });+ }+ if (appConnection.app !== AppConnection.DigiCert) {+ throw new BadRequestError({ message: `App connection with ID '${appConnectionId}' is not a DigiCert connection` });+ }++ const credentials = (await decryptAppConnectionCredentials({+ orgId: appConnection.orgId,+ projectId: appConnection.projectId,+ encryptedCredentials: appConnection.encryptedCredentials,+ kmsService+ })) as TDigiCertConnection["credentials"];++ return {+ apiKey: credentials.apiKey,+ baseUrl: getDigiCertApiBaseUrl(credentials)+ };+};++export const extractLeafAndChain = (pemBundle: string): { leaf: string; chain: string } => {+ const matches = pemBundle.match(PEM_CERTIFICATE_RE2);+ if (!matches || matches.length === 0) {+ throw new BadRequestError({ message: "DigiCert returned an empty certificate bundle" });+ }++ if (matches.length < 2) {+ throw new BadRequestError({+ message: `DigiCert returned an incomplete certificate bundle (${matches.length} entry, expected leaf + chain)`+ });+ }++ let leafIndex = -1;+ matches.forEach((pem, index) => {+ if (leafIndex !== -1) return;+ try {+ const cert = new x509.X509Certificate(pem);+ const basicConstraints = cert.getExtension(x509.BasicConstraintsExtension);+ if (!basicConstraints?.ca) leafIndex = index;+ } catch {+ // skip unparseable entries+ }+ });++ if (leafIndex === -1) leafIndex = 0;++ const leaf = matches[leafIndex].trim();+ const chain = matches+ .filter((_, index) => index !== leafIndex)+ .map((cert) => cert.trim())+ .join("\n");+ return { leaf, chain };+};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 ff7d8be2c6..6f452f4c81 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@@ -1,5 +1,6 @@import { z } from "zod";+import { CodeSigningOrderStatus } from "./digicert-certificate-authority-enums";import {CreateDigiCertCertificateAuthoritySchema,DigiCertCertificateAuthoritySchema,@@ -125,19 +126,9 @@ 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;+ status: CodeSigningOrderStatus;certificateId: number | null;rawStatus: string;};diff --git a/backend/src/services/certificate-authority/digicert/digicert-code-signing-fns.ts b/backend/src/services/certificate-authority/digicert/digicert-code-signing-fns.tsnew file mode 100644index 0000000000..a372e888fe--- /dev/null+++ b/backend/src/services/certificate-authority/digicert/digicert-code-signing-fns.ts@@ -0,0 +1,396 @@+import * as x509 from "@peculiar/x509";++import { BadRequestError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";+import {+ DIGICERT_CS_PRODUCT_NAME_IDS,+ isDigiCertOrgValidatedForProduct+} from "@app/services/app-connection/digicert/digicert-connection-fns";+import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";+import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";+import { CertStatus } from "@app/services/certificate/certificate-types";+import { TDigiCertExternalMetadata } from "@app/services/certificate-common/external-metadata-schemas";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { TProjectDALFactory } from "@app/services/project/project-dal";+import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";++import { TCertificateAuthorityDALFactory } from "../certificate-authority-dal";+import { CaStatus, CaType } from "../certificate-authority-enums";+import { extractIssuedCertificateFields } from "../certificate-authority-fns";+import { createDigiCertApiClient } from "./digicert-api-client";+import { CodeSigningOrderStatus } from "./digicert-certificate-authority-enums";+import { DigiCertCaPurpose } from "./digicert-certificate-authority-schemas";+import {+ castDbEntryToDigiCertCertificateAuthority,+ extractLeafAndChain,+ getDigiCertClientCredentials+} from "./digicert-certificate-authority-shared";+import {+ TCodeSigningOrderInfo,+ TPlaceCodeSigningOrderRequest,+ TPlaceCodeSigningOrderResponse,+ TReissueCodeSigningOrderRequest+} from "./digicert-certificate-authority-types";++// 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"];++type TDigiCertCodeSigningFnsDeps = {+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;+ certificateDAL: Pick<TCertificateDALFactory, "create" | "transaction" | "updateById" | "findOne">;+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;+ kmsService: Pick<+ TKmsServiceFactory,+ "encryptWithKmsKey" | "generateKmsKey" | "createCipherPairWithDataKey" | "decryptWithKmsKey"+ >;+ projectDAL: Pick<TProjectDALFactory, "findById" | "findOne" | "updateById" | "transaction">;+};++export const digiCertCodeSigningFns = ({+ appConnectionDAL,+ certificateAuthorityDAL,+ certificateDAL,+ certificateBodyDAL,+ kmsService,+ projectDAL+}: TDigiCertCodeSigningFnsDeps) => {+ 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 = isDigiCertOrgValidatedForProduct(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 normalizeCodeSigningStatus = (raw: string): CodeSigningOrderStatus => {+ const s = (raw || "").toLowerCase();+ switch (s) {+ case CodeSigningOrderStatus.Issued:+ case CodeSigningOrderStatus.Rejected:+ case CodeSigningOrderStatus.Canceled:+ case CodeSigningOrderStatus.Expired:+ case CodeSigningOrderStatus.Revoked:+ case CodeSigningOrderStatus.NeedsApproval:+ case CodeSigningOrderStatus.Processing:+ case CodeSigningOrderStatus.Pending:+ return s as CodeSigningOrderStatus;+ case "waiting_pickup":+ case "reissue_pending":+ return CodeSigningOrderStatus.Pending;+ default:+ logger.warn(`DigiCert returned unrecognized CS order status [status=${raw}] — treating as pending`);+ return CodeSigningOrderStatus.Pending;+ }+ };++ 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 });++ 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 };+ };++ 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 assertCodeSigningOrderReusable = async (caId: string, orderId: number): Promise<void> => {+ const { digicertCa, client } = await loadDigiCertCsContext(caId, { requireCodeSigning: true });+ const order = await client.getOrder(orderId);+ const sameOrg = order.organization?.id === digicertCa.configuration.organizationId;+ const sameProduct = order.product?.name_id === digicertCa.configuration.productNameId;+ if (!sameOrg || !sameProduct) {+ throw new BadRequestError({+ message:+ "That DigiCert order belongs to a different organization or product than this certificate authority and cannot be reused."+ });+ }+ };++ 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 {+ assertCsOrgValidatedOrContactProvided,+ orderCodeSigningCertificate,+ reissueCodeSigningCertificate,+ findCodeSigningOrderByReference,+ assertCodeSigningOrderReusable,+ getCodeSigningOrderStatus,+ downloadCodeSigningCertificate+ };+};diff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.tsindex 24c7ac0f1c..43ea771861 100644--- a/backend/src/services/certificate/certificate-dal.ts+++ b/backend/src/services/certificate/certificate-dal.ts@@ -65,21 +65,6 @@ export const certificateDALFactory = (db: TDbClient) => {}};- const findDigiCertCertByOrderId = async (caId: string, orderId: number) => {- try {- const cert = await db- .replicaNode()(TableName.Certificate)- .where({ caId })- .whereRaw(`"externalMetadata"->>'type' = ?`, ["digicert"])- .whereRaw(`("externalMetadata"->>'orderId') = ?`, [String(orderId)])- .first();-- return cert;- } catch (error) {- throw new DatabaseError({ error, name: "Find DigiCert cert by order ID" });- }- };-const findActiveDigiCertCertsByOrderIds = async (caId: string, orderIds: number[]) => {if (orderIds.length === 0) return [];try {@@ -1174,7 +1159,6 @@ export const certificateDALFactory = (db: TDbClient) => {findLatestActiveCertForSubscriber,findAllActiveCertsForSubscriber,findActiveDigiCertCertsByOrderIds,- findDigiCertCertByOrderId,findExpiredSyncedCertificates,findByThumbprintInOrg,findActiveCertificatesByIds,diff --git a/backend/src/services/signer/signer-issuance-service.ts b/backend/src/services/signer/signer-issuance-service.tsindex 7ed8c0527e..6f09c03590 100644--- a/backend/src/services/signer/signer-issuance-service.ts+++ b/backend/src/services/signer/signer-issuance-service.ts@@ -21,6 +21,7 @@ import { TCertificateAuthorityDALFactory } from "../certificate-authority/certifimport { CaStatus, CaType } from "../certificate-authority/certificate-authority-enums";import { keyAlgorithmToAlgCfg } from "../certificate-authority/certificate-authority-fns";import { TCertificateIssuanceQueueFactory } from "../certificate-authority/certificate-issuance-queue";+import { CodeSigningOrderStatus } from "../certificate-authority/digicert/digicert-certificate-authority-enums";import { THsmConnectorServiceFactory } from "../hsm-connector/hsm-connector-service";import { THsmConnectorServiceActor } from "../hsm-connector/hsm-connector-types";import { TKmsServiceFactory } from "../kms/kms-service";@@ -583,7 +584,12 @@ export const signerIssuanceServiceFactory = ({const persistPlacedOrder = async (orderId: number, certificateId: number | null) => {await signerIssuanceJobDAL.updateById(job.id, {externalOrderRef: {- digicert: { orderId, certificateId, lastStatus: "pending", lastCheckedAt: new Date().toISOString() }+ digicert: {+ orderId,+ certificateId,+ lastStatus: CodeSigningOrderStatus.Pending,+ lastCheckedAt: new Date().toISOString()+ }}});logger.info(@@ -675,10 +681,10 @@ export const signerIssuanceServiceFactory = ({});if (- info.status === "rejected" ||- info.status === "canceled" ||- info.status === "expired" ||- info.status === "revoked"+ info.status === CodeSigningOrderStatus.Rejected ||+ info.status === CodeSigningOrderStatus.Canceled ||+ info.status === CodeSigningOrderStatus.Expired ||+ info.status === CodeSigningOrderStatus.Revoked) {await markJobFailed(job,@@ -687,7 +693,7 @@ export const signerIssuanceServiceFactory = ({return;}- if (info.status !== "issued") {+ if (info.status !== CodeSigningOrderStatus.Issued) {logger.info(`signer issuance: DigiCert order still pending [jobId=${job.id}] [signerId=${job.signerId}] [orderId=${existingOrderId}] [status=${info.status}]`);@@ -777,9 +783,16 @@ export const signerIssuanceServiceFactory = ({};};+ const runPendingJobNow = async (signerId: string): Promise<void> => {+ const job = await signerIssuanceJobDAL.transaction((tx) => signerIssuanceJobDAL.findLatestForSigner(signerId, tx));+ if (!job || job.status !== SignerIssuanceJobStatus.Pending) return;+ await processJob(job.id);+ };+return {requestIssuance,processJob,+ runPendingJobNow,getLatestIssuanceKeyConfig,start};diff --git a/backend/src/services/signer/signer-service.ts b/backend/src/services/signer/signer-service.tsindex 9f8882d90a..bb086e3346 100644--- a/backend/src/services/signer/signer-service.ts+++ b/backend/src/services/signer/signer-service.ts@@ -118,13 +118,16 @@ type TSignerServiceFactoryDep = {THsmConnectorServiceFactory,"sign" | "generateKeyPair" | "getPublicKey" | "assertAttachPermission">;- certificateDAL: Pick<TCertificateDALFactory, "findById" | "updateById" | "findDigiCertCertByOrderId">;+ certificateDAL: Pick<TCertificateDALFactory, "findById" | "updateById">;certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create">;certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;- signerIssuanceService: Pick<TSignerIssuanceServiceFactory, "requestIssuance" | "getLatestIssuanceKeyConfig">;+ signerIssuanceService: Pick<+ TSignerIssuanceServiceFactory,+ "requestIssuance" | "getLatestIssuanceKeyConfig" | "runPendingJobNow"+ >;internalCertificateAuthorityService: Pick<TInternalCertificateAuthorityServiceFactory, "signCertFromCa">;- digicertFns: Pick<TDigiCertCertificateAuthorityFns, "revokeCertificate">;+ digicertFns: Pick<TDigiCertCertificateAuthorityFns, "revokeCertificate" | "assertCodeSigningOrderReusable">;projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "encryptWithKmsKey" | "generateKmsKey">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;@@ -262,6 +265,24 @@ export const signerServiceFactory = ({membershipRoleDAL,hsmConnectorService}: TSignerServiceFactoryDep) => {+ const hsmCertIssuanceDeps = {+ certificateAuthorityDAL,+ internalCertificateAuthorityService,+ certificateBodyDAL,+ certificateDAL,+ hsmConnectorService,+ projectDAL,+ kmsService+ };+ const softwareCertIssuanceDeps = {+ certificateAuthorityDAL,+ internalCertificateAuthorityService,+ certificateBodyDAL,+ certificateSecretDAL,+ projectDAL,+ kmsService+ };+const $loadSignerResourcePermission = async (signerId: string,projectId: string,@@ -280,6 +301,44 @@ export const signerServiceFactory = ({actorOrgId});+ const $issueInternalCaCertificate = async (input: {+ caId: string;+ projectId: string;+ commonName: string;+ certificateTtlDays?: number;+ keyAlgorithm: CertKeyAlgorithm;+ certificate?: TCreateSignerDTO["certificate"];+ actor: Parameters<typeof hsmConnectorService.assertAttachPermission>[0];+ }): Promise<string> => {+ const { caId, projectId, commonName, certificateTtlDays, keyAlgorithm, certificate, actor } = input;+ const ttlDays = certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS;++ if (certificate?.keySource === CertKeySource.Hsm) {+ if (!certificate.hsmConnectorId) {+ throw new BadRequestError({ message: "hsmConnectorId is required when certificate.keySource = 'hsm'." });+ }+ await hsmConnectorService.assertAttachPermission(actor, certificate.hsmConnectorId, projectId);+ const { certificateId } = await issueHsmBackedSignerCertificate(hsmCertIssuanceDeps, {+ caId,+ projectId,+ commonName,+ certificateTtlDays: ttlDays,+ hsmConnectorId: certificate.hsmConnectorId,+ hsmKeyAlgorithm: mapCertKeyAlgorithmToHsmKeyAlgorithm(keyAlgorithm)+ });+ return certificateId;+ }++ const { certificateId } = await issueSignerCertificate(softwareCertIssuanceDeps, {+ caId,+ projectId,+ commonName,+ certificateTtlDays: ttlDays,+ keyAlgorithm+ });+ return certificateId;+ };+const create = async (dto: TCreateSignerDTO) => {const { permission } = await permissionService.getProjectPermission({actor: dto.actor,@@ -357,7 +416,9 @@ export const signerServiceFactory = ({if (resolvedCaType) assertCaTypeSupportsCodeSigning(resolvedCaType);let createDigicertLifecycle: { mode: "reissue"; previousOrderId: number } | undefined;- const reissueFromExternalOrderId = dto.externalConfiguration?.reissueFromExternalOrderId;+ const createExternalConfig = dto.externalConfiguration;+ const reissueFromExternalOrderId =+ createExternalConfig?.caType === CaType.DIGICERT ? createExternalConfig.reissueFromExternalOrderId : undefined;if (reissueFromExternalOrderId) {if (resolvedCaType !== CaType.DIGICERT) {throw new BadRequestError({@@ -369,12 +430,7 @@ export const signerServiceFactory = ({if (!Number.isInteger(previousOrderId) || previousOrderId <= 0) {throw new BadRequestError({ message: "reissueFromExternalOrderId must be a valid DigiCert order id." });}- const managedOrder = await certificateDAL.findDigiCertCertByOrderId(resolvedCaId as string, previousOrderId);- if (!managedOrder) {- throw new BadRequestError({- message: "That DigiCert order is not managed by this certificate authority and cannot be reused."- });- }+ await digicertFns.assertCodeSigningOrderReusable(resolvedCaId as string, previousOrderId);createDigicertLifecycle = { mode: "reissue", previousOrderId };}@@ -391,63 +447,15 @@ export const signerServiceFactory = ({let issuedCertificateId: string | null = null;if (usingCa && resolvedCaId && !isExternalCa) {- const certificateInput = dto.certificate;- if (certificateInput?.keySource === CertKeySource.Hsm) {- if (!certificateInput.hsmConnectorId) {- throw new BadRequestError({- message: "hsmConnectorId is required when certificate.keySource = 'hsm'."- });- }- await hsmConnectorService.assertAttachPermission(- {- type: dto.actor,- id: dto.actorId,- authMethod: dto.actorAuthMethod,- orgId: dto.actorOrgId- },- certificateInput.hsmConnectorId,- dto.projectId- );- const { certificateId } = await issueHsmBackedSignerCertificate(- {- certificateAuthorityDAL,- internalCertificateAuthorityService,- certificateBodyDAL,- certificateDAL,- hsmConnectorService,- projectDAL,- kmsService- },- {- caId: resolvedCaId,- projectId: dto.projectId,- commonName: dto.commonName as string,- certificateTtlDays: dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS,- hsmConnectorId: certificateInput.hsmConnectorId,- hsmKeyAlgorithm: mapCertKeyAlgorithmToHsmKeyAlgorithm(keyAlgorithm)- }- );- issuedCertificateId = certificateId;- } else {- const { certificateId } = await issueSignerCertificate(- {- certificateAuthorityDAL,- internalCertificateAuthorityService,- certificateBodyDAL,- certificateSecretDAL,- projectDAL,- kmsService- },- {- caId: resolvedCaId,- projectId: dto.projectId,- commonName: dto.commonName as string,- certificateTtlDays: dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS,- keyAlgorithm- }- );- issuedCertificateId = certificateId;- }+ issuedCertificateId = await $issueInternalCaCertificate({+ caId: resolvedCaId,+ projectId: dto.projectId,+ commonName: dto.commonName as string,+ certificateTtlDays: dto.certificateTtlDays,+ keyAlgorithm,+ certificate: dto.certificate,+ actor: { type: dto.actor, id: dto.actorId, authMethod: dto.actorAuthMethod, orgId: dto.actorOrgId }+ });}const finalCertificateId = usingExistingCert ? (dto.certificateId as string) : issuedCertificateId;@@ -800,9 +808,42 @@ export const signerServiceFactory = ({ForbiddenError.from(permission).throwUnlessCan(ResourcePermissionSignerActions.Read, ResourcePermissionSub.Signer);+ if (!signer.certificateId) {+ const keyConfig = await signerIssuanceService.getLatestIssuanceKeyConfig(signer.id);+ if (keyConfig) {+ signer.certificateKeySource = signer.certificateKeySource ?? keyConfig.keySource;+ signer.certificateHsmConnectorId = signer.certificateHsmConnectorId ?? keyConfig.hsmConnectorId;+ signer.certificateKeyAlgorithm = signer.certificateKeyAlgorithm ?? keyConfig.keyAlgorithm;+ }+ }+return { ...signer, status: computeEffectiveStatus(signer) };};+ const checkIssuanceNow = async (dto: TGetSignerDTO) => {+ const signer = await signerDAL.findById(dto.signerId);+ if (!signer) {+ throw new NotFoundError({ message: `Signer with ID '${dto.signerId}' not found` });+ }++ const { permission } = await $loadSignerResourcePermission(+ signer.id,+ signer.projectId,+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId+ );++ ForbiddenError.from(permission).throwUnlessCan(+ ResourcePermissionSignerActions.ReissueCertificate,+ ResourcePermissionSub.Signer+ );++ await signerIssuanceService.runPendingJobNow(signer.id);+ return getById(dto);+ };+const getMyPermissions = async (dto: TGetSignerDTO) => {const signer = await signerDAL.findById(dto.signerId);if (!signer) {@@ -994,6 +1035,123 @@ export const signerServiceFactory = ({return signerDAL.updateById(dto.signerId, { status: SignerStatus.Disabled });};+ type TReissueExecutionContext = {+ dto: TReissueCertificateDTO;+ signer: NonNullable<Awaited<ReturnType<typeof signerDAL.findById>>>;+ reissueCaType: CaType;+ target: ReturnType<typeof resolveReissueTarget>;+ currentCert: Awaited<ReturnType<typeof certificateDAL.findById>> | null;+ recoveredKeyConfig: Awaited<ReturnType<typeof signerIssuanceService.getLatestIssuanceKeyConfig>>;+ commonName: string;+ certificateTtlDays: number;+ explicitReissueOrderId?: number;+ };++ const $reissueExternalSigner = async (ctx: TReissueExecutionContext) => {+ const { dto, signer, reissueCaType, target, currentCert, recoveredKeyConfig, commonName, certificateTtlDays } = ctx;+ const reissueHsm = target.isHsm+ ? {+ hsmConnectorId: target.hsmConnectorId,+ hsmKeyAlgorithm: target.hsmKeyAlgorithm,+ hsmKeyLabel: target.switchingKeySource+ ? undefined+ : (currentCert?.hsmKeyLabel ?? recoveredKeyConfig?.hsmKeyLabel ?? undefined),+ hsmPublicKeySpki: target.switchingKeySource+ ? undefined+ : (currentCert?.hsmPublicKeySpki ?? recoveredKeyConfig?.hsmPublicKeySpki ?? undefined),+ actor: { type: dto.actor, id: dto.actorId, authMethod: dto.actorAuthMethod, orgId: dto.actorOrgId }+ }+ : undefined;++ await signerDAL.updateById(dto.signerId, { status: SignerStatus.Pending, certificateFailureReason: null });++ const reissueDigicertOrderId =+ reissueCaType === CaType.DIGICERT+ ? (ctx.explicitReissueOrderId ?? (currentCert?.externalMetadata as { orderId?: number } | null)?.orderId)+ : undefined;+ try {+ await signerIssuanceService.requestIssuance({+ signerId: signer.id,+ projectId: signer.projectId,+ caId: dto.caId,+ commonName,+ certificateTtlDays,+ keyAlgorithm: target.keyAlgorithm,+ hsm: reissueHsm,+ digicertLifecycle: reissueDigicertOrderId+ ? { mode: "reissue", previousOrderId: reissueDigicertOrderId }+ : undefined+ });+ return await signerDAL.findById(dto.signerId);+ } catch (queueErr) {+ await signerDAL.updateById(dto.signerId, {+ status: SignerStatus.Failed,+ certificateFailureReason: formatSignerIssuanceErrorReason(+ queueErr,+ "Could not schedule re-issuance from the external Certificate Authority"+ )+ });+ throw queueErr;+ }+ };++ const $reissueInternalSigner = async (ctx: TReissueExecutionContext) => {+ const { dto, signer, target, currentCert, commonName, certificateTtlDays } = ctx;+ try {+ let certificateId: string;+ if (target.isHsm) {+ if (target.switchingKeySource || !currentCert?.hsmKeyLabel) {+ const result = await issueHsmBackedSignerCertificate(hsmCertIssuanceDeps, {+ caId: dto.caId,+ projectId: signer.projectId,+ commonName,+ certificateTtlDays,+ hsmConnectorId: target.hsmConnectorId,+ hsmKeyAlgorithm: target.hsmKeyAlgorithm+ });+ certificateId = result.certificateId;+ } else {+ const result = await renewHsmBackedSignerCertificate(hsmCertIssuanceDeps, {+ caId: dto.caId,+ projectId: signer.projectId,+ commonName,+ certificateTtlDays,+ hsmConnectorId: target.hsmConnectorId,+ hsmKeyLabel: currentCert.hsmKeyLabel,+ expectedPublicKeySpkiDer: currentCert.hsmPublicKeySpki ?? undefined,+ hsmKeyAlgorithm: target.hsmKeyAlgorithm+ });+ certificateId = result.certificateId;+ }+ } else {+ const result = await issueSignerCertificate(softwareCertIssuanceDeps, {+ caId: dto.caId,+ projectId: signer.projectId,+ commonName,+ certificateTtlDays,+ keyAlgorithm: target.keyAlgorithm+ });+ certificateId = result.certificateId;+ }++ return await signerDAL.updateById(dto.signerId, {+ certificateId,+ status: SignerStatus.Active,+ certificateFailureReason: null+ });+ } catch (issueErr) {+ logger.error(+ issueErr,+ `signer reissue: certificate issuance failed for signer '${signer.name}' [signerId=${signer.id}]`+ );+ await signerDAL.updateById(dto.signerId, {+ status: SignerStatus.Failed,+ certificateFailureReason: formatSignerIssuanceErrorReason(issueErr, "Internal CA certificate issuance failed")+ });+ throw issueErr;+ }+ };+const reissueCertificate = async (dto: TReissueCertificateDTO) => {const signer = await signerDAL.findById(dto.signerId);if (!signer) throw new NotFoundError({ message: `Signer with ID '${dto.signerId}' not found` });@@ -1023,36 +1181,29 @@ export const signerServiceFactory = ({assertCaTypeSupportsCodeSigning(reissueCaType);const reissueIsExternal = reissueCaType !== CaType.INTERNAL;+ const reissueExternalConfig = dto.externalConfiguration;+ const reissueFromExternalOrderId =+ reissueExternalConfig?.caType === CaType.DIGICERT ? reissueExternalConfig.reissueFromExternalOrderId : undefined;let explicitReissueOrderId: number | undefined;- if (dto.reissueFromExternalOrderId) {+ if (reissueFromExternalOrderId) {if (reissueCaType !== CaType.DIGICERT) {throw new BadRequestError({message:"Reissuing from an existing order is only supported for DigiCert code signing certificate authorities."});}- explicitReissueOrderId = Number(dto.reissueFromExternalOrderId);+ explicitReissueOrderId = Number(reissueFromExternalOrderId);if (!Number.isInteger(explicitReissueOrderId) || explicitReissueOrderId <= 0) {throw new BadRequestError({ message: "reissueFromExternalOrderId must be a valid DigiCert order id." });}- const managedOrder = await certificateDAL.findDigiCertCertByOrderId(ca.id, explicitReissueOrderId);- if (!managedOrder) {- throw new BadRequestError({- message: "That DigiCert order is not managed by this certificate authority and cannot be reused."- });- }+ await digicertFns.assertCodeSigningOrderReusable(ca.id, explicitReissueOrderId);}- const allowsResubject = signer.status === SignerStatus.Pending || signer.status === SignerStatus.Failed;let nextCommonName = signer.commonName;- let nextTtl = signer.certificateTtlDays;- if (allowsResubject) {+ let effectiveTtl = signer.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS;+ if (!explicitReissueOrderId) {if (dto.commonName !== undefined) nextCommonName = dto.commonName;- if (dto.certificateTtlDays !== undefined) nextTtl = dto.certificateTtlDays;- } else if (dto.commonName !== undefined || dto.certificateTtlDays !== undefined) {- throw new BadRequestError({- message: "Common Name and validity are fixed for an active signer. Create a new signer to change them."- });+ if (dto.certificateTtlDays !== undefined) effectiveTtl = dto.certificateTtlDays;}if (!nextCommonName) {@@ -1061,7 +1212,6 @@ export const signerServiceFactory = ({});}- const effectiveTtl = nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS;if (signer.certificateRenewBeforeDays != null && signer.certificateRenewBeforeDays >= effectiveTtl) {throw new BadRequestError({message: `Certificate validity (${effectiveTtl}d) must be greater than the configured renew before (${signer.certificateRenewBeforeDays}d). Update the renew-before window before reissuing with a shorter validity.`@@ -1105,153 +1255,30 @@ export const signerServiceFactory = ({);}- const { isHsm: targetIsHsm, switchingKeySource, keyAlgorithm: targetKeyAlgorithm } = target;-await signerDAL.updateById(dto.signerId, {caId: dto.caId,commonName: nextCommonName,certificateTtlDays: effectiveTtl,- keyAlgorithm: targetKeyAlgorithm+ keyAlgorithm: target.keyAlgorithm});+ const reissueCtx: TReissueExecutionContext = {+ dto,+ signer,+ reissueCaType,+ target,+ currentCert: reissueCurrentCert,+ recoveredKeyConfig,+ commonName: nextCommonName,+ certificateTtlDays: effectiveTtl,+ explicitReissueOrderId+ };+if (reissueIsExternal) {- const reissueHsm = targetIsHsm- ? {- hsmConnectorId: target.hsmConnectorId,- hsmKeyAlgorithm: target.hsmKeyAlgorithm,- hsmKeyLabel: switchingKeySource- ? undefined- : (reissueCurrentCert?.hsmKeyLabel ?? recoveredKeyConfig?.hsmKeyLabel ?? undefined),- hsmPublicKeySpki: switchingKeySource- ? undefined- : (reissueCurrentCert?.hsmPublicKeySpki ?? recoveredKeyConfig?.hsmPublicKeySpki ?? undefined),- actor: {- type: dto.actor,- id: dto.actorId,- authMethod: dto.actorAuthMethod,- orgId: dto.actorOrgId- }- }- : undefined;- await signerDAL.updateById(dto.signerId, {- 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,- projectId: signer.projectId,- caId: dto.caId,- commonName: nextCommonName,- certificateTtlDays: nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS,- keyAlgorithm: targetKeyAlgorithm,- hsm: reissueHsm,- digicertLifecycle: reissueDigicertOrderId- ? { mode: "reissue", previousOrderId: reissueDigicertOrderId }- : undefined- });- return await signerDAL.findById(dto.signerId);- } catch (queueErr) {- await signerDAL.updateById(dto.signerId, {- status: SignerStatus.Failed,- certificateFailureReason: formatSignerIssuanceErrorReason(- queueErr,- "Could not schedule re-issuance from the external Certificate Authority"- )- });- throw queueErr;- }+ return $reissueExternalSigner(reissueCtx);}- try {- let certificateId: string;- if (targetIsHsm) {- if (switchingKeySource || !reissueCurrentCert?.hsmKeyLabel) {- const result = await issueHsmBackedSignerCertificate(- {- certificateAuthorityDAL,- internalCertificateAuthorityService,- certificateBodyDAL,- certificateDAL,- hsmConnectorService,- projectDAL,- kmsService- },- {- caId: dto.caId,- projectId: signer.projectId,- commonName: nextCommonName,- certificateTtlDays: nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS,- hsmConnectorId: target.hsmConnectorId,- hsmKeyAlgorithm: target.hsmKeyAlgorithm- }- );- certificateId = result.certificateId;- } else {- const result = await renewHsmBackedSignerCertificate(- {- certificateAuthorityDAL,- internalCertificateAuthorityService,- certificateBodyDAL,- certificateDAL,- hsmConnectorService,- projectDAL,- kmsService- },- {- caId: dto.caId,- projectId: signer.projectId,- commonName: nextCommonName,- certificateTtlDays: nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS,- hsmConnectorId: target.hsmConnectorId,- hsmKeyLabel: reissueCurrentCert.hsmKeyLabel,- expectedPublicKeySpkiDer: reissueCurrentCert.hsmPublicKeySpki ?? undefined,- hsmKeyAlgorithm: target.hsmKeyAlgorithm- }- );- certificateId = result.certificateId;- }- } else {- const result = await issueSignerCertificate(- {- certificateAuthorityDAL,- internalCertificateAuthorityService,- certificateBodyDAL,- certificateSecretDAL,- projectDAL,- kmsService- },- {- caId: dto.caId,- projectId: signer.projectId,- commonName: nextCommonName,- certificateTtlDays: nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS,- keyAlgorithm: targetKeyAlgorithm- }- );- certificateId = result.certificateId;- }-- return await signerDAL.updateById(dto.signerId, {- certificateId,- status: SignerStatus.Active,- certificateFailureReason: null- });- } catch (issueErr) {- logger.error(- issueErr,- `signer reissue: certificate issuance failed for signer '${signer.name}' [signerId=${signer.id}]`- );- await signerDAL.updateById(dto.signerId, {- status: SignerStatus.Failed,- certificateFailureReason: formatSignerIssuanceErrorReason(issueErr, "Internal CA certificate issuance failed")- });- throw issueErr;- }+ return $reissueInternalSigner(reissueCtx);};const exportCertificate = async (dto: TExportCertificateDTO) => {@@ -1816,46 +1843,25 @@ export const signerServiceFactory = ({const renewIsHsm = existingCert?.keySource === CertKeySource.Hsm;let certificateId: string;if (renewIsHsm && existingCert?.hsmConnectorId && existingCert.hsmKeyLabel && existingCert.keyAlgorithm) {- const result = await renewHsmBackedSignerCertificate(- {- certificateAuthorityDAL,- internalCertificateAuthorityService,- certificateBodyDAL,- certificateDAL,- hsmConnectorService,- projectDAL,- kmsService- },- {- caId: signer.caId,- projectId: signer.projectId,- commonName: signer.commonName,- certificateTtlDays: ttlDays,- hsmConnectorId: existingCert.hsmConnectorId,- hsmKeyLabel: existingCert.hsmKeyLabel,- expectedPublicKeySpkiDer: existingCert.hsmPublicKeySpki ?? undefined,- hsmKeyAlgorithm: mapCertKeyAlgorithmToHsmKeyAlgorithm(existingCert.keyAlgorithm)- }- );+ const result = await renewHsmBackedSignerCertificate(hsmCertIssuanceDeps, {+ caId: signer.caId,+ projectId: signer.projectId,+ commonName: signer.commonName,+ certificateTtlDays: ttlDays,+ hsmConnectorId: existingCert.hsmConnectorId,+ hsmKeyLabel: existingCert.hsmKeyLabel,+ expectedPublicKeySpkiDer: existingCert.hsmPublicKeySpki ?? undefined,+ hsmKeyAlgorithm: mapCertKeyAlgorithmToHsmKeyAlgorithm(existingCert.keyAlgorithm)+ });certificateId = result.certificateId;} else {- const result = await issueSignerCertificate(- {- certificateAuthorityDAL,- internalCertificateAuthorityService,- certificateBodyDAL,- certificateSecretDAL,- projectDAL,- kmsService- },- {- caId: signer.caId,- projectId: signer.projectId,- commonName: signer.commonName,- certificateTtlDays: ttlDays,- keyAlgorithm: renewKeyAlgorithm- }- );+ const result = await issueSignerCertificate(softwareCertIssuanceDeps, {+ caId: signer.caId,+ projectId: signer.projectId,+ commonName: signer.commonName,+ certificateTtlDays: ttlDays,+ keyAlgorithm: renewKeyAlgorithm+ });certificateId = result.certificateId;}await signerDAL.updateById(signer.id, {@@ -1885,6 +1891,7 @@ export const signerServiceFactory = ({create,list,getById,+ checkIssuanceNow,getMyPermissions,getProjectIdForSigner,update,diff --git a/backend/src/services/signer/signer-types.ts b/backend/src/services/signer/signer-types.tsindex dd7add0621..3cad7ee658 100644--- a/backend/src/services/signer/signer-types.ts+++ b/backend/src/services/signer/signer-types.ts@@ -2,6 +2,7 @@ import { SigningAlgorithm } from "@app/lib/crypto/sign/types";import { TProjectPermission } from "@app/lib/types";import { CertKeyAlgorithm } from "../certificate/certificate-types";+import { CaType } from "../certificate-authority/certificate-authority-enums";import { CertKeySource, SignerStatus, SigningOperationStatus } from "./signer-enums";type TActorPermission = Omit<TProjectPermission, "projectId">;@@ -23,7 +24,7 @@ export type TSignerCertificateInput = {};export type TSignerExternalConfigurationInput = {- // DigiCert code signing only: reissue into this existing order instead of placing a new one.+ caType: CaType.DIGICERT;reissueFromExternalOrderId?: string;};@@ -103,8 +104,7 @@ 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;+ externalConfiguration?: TSignerExternalConfigurationInput;} & TActorPermission;export type TExportCertificateDTO = {diff --git a/docs/docs.json b/docs/docs.jsonindex 943c8a5543..50b24c4dbb 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -851,8 +851,14 @@"documentation/platform/pki/code-signing/overview","documentation/platform/pki/code-signing/signers","documentation/platform/pki/code-signing/approvals",- "documentation/platform/pki/code-signing/pkcs11-module",- "documentation/platform/pki/code-signing/windows-ksp"+ {+ "group": "Guides",+ "pages": [+ "documentation/platform/pki/code-signing/digicert-code-signing",+ "documentation/platform/pki/code-signing/pkcs11-module",+ "documentation/platform/pki/code-signing/windows-ksp"+ ]+ }]},{diff --git a/docs/documentation/platform/pki/ca/digicert-direct.mdx b/docs/documentation/platform/pki/ca/digicert-direct.mdxindex e46e0fc089..b64ee320f5 100644--- a/docs/documentation/platform/pki/ca/digicert-direct.mdx+++ b/docs/documentation/platform/pki/ca/digicert-direct.mdx@@ -16,6 +16,10 @@ Infisical can issue certificates directly from [DigiCert CertCentral](https://ww- 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.+<Note>+ Configuring a DigiCert CA requires a CertCentral account with administrator-level access (or a role with permission to manage organizations, products, and API keys). The API key used for the App Connection inherits the permissions of the CertCentral user that created it.+</Note>+## Create a DigiCert Certificate Authority<Tabs>@@ -81,24 +85,11 @@ Infisical can issue certificates directly from [DigiCert CertCentral](https://ww## 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+A CA configured for code signing is used from the **Code Signing** product, not the TLS issuance flow. For creating signers, reusing orders, HSM requirements, reissue, renewal, and deletion behavior, see the dedicated guide:-- **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.+<Card title="Code Signing with DigiCert" icon="signature" href="/documentation/platform/pki/code-signing/digicert-code-signing">+ Issue code-signing certificates from this CA with an HSM-backed key.+</Card>## DigiCert Validation Workflowdiff --git a/docs/documentation/platform/pki/code-signing/digicert-code-signing.mdx b/docs/documentation/platform/pki/code-signing/digicert-code-signing.mdxnew file mode 100644index 0000000000..bab76144be--- /dev/null+++ b/docs/documentation/platform/pki/code-signing/digicert-code-signing.mdx@@ -0,0 +1,59 @@+---+title: "Code Signing with DigiCert"+description: "Issue code-signing certificates from DigiCert CertCentral with an HSM-backed key."+---++## Concept++A DigiCert Certificate Authority configured for code signing issues OV (`code_signing`) and EV (`code_signing_ev`) certificates from your CertCentral account against a CSR. The signing key must live on an HSM, so Infisical generates the CSR against an HSM key and sends only the CSR to DigiCert.++This guide covers using such a CA from the **Code Signing** product. To set up the CA itself, see [DigiCert (CertCentral Services API)](/documentation/platform/pki/ca/digicert-direct).++## Prerequisites++- A DigiCert Certificate Authority created with **Purpose** set to `Code Signing`. See [DigiCert (CertCentral Services API)](/documentation/platform/pki/ca/digicert-direct).+- An [HSM Connector](/documentation/platform/pki/settings/hsm-connectors) the signing key can be generated on.++## Create a Signer++Once a CA is configured for 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 code-signing workflow includes an out-of-band step for the first order 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).+</Note>++A **Pending** signer is checked on a schedule. To poll DigiCert immediately instead of waiting for the next check, use **Check issuance now** from the signer's actions menu.++### Reuse an existing order++Each DigiCert order consumes a subscription slot on your CertCentral account. If a code-signing order already exists in this CA's organization, a Signer can issue into that order instead of spending another slot. This includes orders placed directly in DigiCert, not just ones Infisical created.++Reuse is scoped to the CA's configured organization and product, so only orders from that organization and product can be selected. The Common Name and Validity come from the chosen order rather than from the Signer.++<Tabs>+ <Tab title="Infisical UI">+ In the Create Signer wizard's **Certificate** step, open **Reuse an existing order** and pick one of the listed issued orders. The Common Name and Validity fields are hidden because they are inherited from the order. Leave the field empty to place a new order.+ </Tab>+ <Tab title="API">+ Set `externalConfiguration.reissueFromExternalOrderId` to the order id on [Create Signer](/api-reference/endpoints/code-signing/signers/create) or [Reissue](/api-reference/endpoints/code-signing/signers/reissue).+ </Tab>+</Tabs>++<Warning>+ Reissuing into an existing order replaces that order's certificate. DigiCert revokes the previous certificate within 72 hours, after which it can no longer be used to sign.+</Warning>++## Editing a Signer++Editing a signer's Common Name, validity, key source, key algorithm, or CA triggers a fresh issuance. The signer returns to **Pending** until the new certificate issues, and DigiCert revokes the previous certificate within 72 hours.++## 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.++## Deleting a Signer++Deleting a DigiCert code-signing signer revokes its DigiCert order, so the certificate can no longer be used to sign anywhere. Depending on your CertCentral account's revocation policy, DigiCert may queue the revocation for administrator approval.diff --git a/docs/documentation/platform/pki/code-signing/signers.mdx b/docs/documentation/platform/pki/code-signing/signers.mdxindex af4ccd4d43..f3b3276d80 100644--- a/docs/documentation/platform/pki/code-signing/signers.mdx+++ b/docs/documentation/platform/pki/code-signing/signers.mdx@@ -63,12 +63,12 @@ In **Certificate Manager → Code Signing → Signers**, click **Create Signer**| Field | Description ||-------|-------------|| **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. |+ | **Common Name** | The legal name shown on the certificate, for example `Acme Mobile, Inc.`. You can change it later; doing so reissues the certificate. || **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.+ Some CAs add extra fields on this step. Check your CA's documentation for any CA-specific options.</Note>Click **Next** to choose the signing key.@@ -128,7 +128,7 @@ 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 three steps: Basics, Certificate, and Signing Key. Saving can trigger a fresh issuance, so some fields are read-only once the Signer is Active.+Open the Signer and choose **Options → Edit settings**. The edit sheet walks you through three steps: Basics, Certificate, and Signing Key. Changing the CA, identity, validity, or key triggers a fresh issuance, and the signer switches to the newly issued certificate.<Steps><Step title="Basics">@@ -144,8 +144,8 @@ Open the Signer and choose **Options → Edit settings**. The edit sheet walks yChange which CA issues the certificate and its identity.- **Certificate Authority**: swap to another CA. Saving with a different CA reissues the certificate immediately from the new CA.- - **Reuse an existing order**: 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.+ - **Reuse an existing order**: offered by some CAs (DigiCert code signing). Point the Signer at an existing order to reuse that order slot instead of placing a new one. Common Name and Validity are inherited from the order.+ - **Common Name** and **Validity (days)**: edit them to change the identity on the certificate. Saving reissues the certificate with the new values, and the signer switches to the new certificate.- **Renew before (days)**: edit any time, 1 to 30, must be less than Validity.Click **Next** to edit the signing key.diff --git a/frontend/src/hooks/api/appConnections/digicert/queries.tsx b/frontend/src/hooks/api/appConnections/digicert/queries.tsxindex d9d54b7ffe..4cb490d84b 100644--- a/frontend/src/hooks/api/appConnections/digicert/queries.tsx+++ b/frontend/src/hooks/api/appConnections/digicert/queries.tsx@@ -11,27 +11,22 @@ const digicertConnectionKeys = {[...digicertConnectionKeys.all, "organizations", connectionId] as const,listProducts: (connectionId: string) =>[...digicertConnectionKeys.all, "products", connectionId] as const,- codeSigningValidation: (connectionId: string, organizationId: number, productNameId: string) =>+ orgValidation: (connectionId: string, organizationId: number, productNameId: string) =>[...digicertConnectionKeys.all,- "code-signing-validation",+ "org-validation",connectionId,organizationId,productNameId] as const,- codeSigningOrders: (connectionId: string, organizationId: number, productNameId: string) =>- [- ...digicertConnectionKeys.all,- "code-signing-orders",- connectionId,- organizationId,- productNameId- ] as const+ orders: (connectionId: string, organizationId: number, productNameId: string) =>+ [...digicertConnectionKeys.all, "orders", connectionId, organizationId, productNameId] as const};-export type TDigiCertCodeSigningOrder = {+export type TDigiCertOrder = {orderId: number;commonName: string;+ organizationName: string;status: string;validTill?: string;};@@ -84,7 +79,7 @@ export const useDigiCertConnectionListProducts = (});};-export const useDigiCertConnectionCodeSigningValidation = (+export const useDigiCertConnectionOrgValidation = (connectionId: string,organizationId: number,productNameId: string,@@ -93,20 +88,16 @@ export const useDigiCertConnectionCodeSigningValidation = ({ isValidated: boolean },unknown,{ isValidated: boolean },- ReturnType<typeof digicertConnectionKeys.codeSigningValidation>+ ReturnType<typeof digicertConnectionKeys.orgValidation>>,"queryKey" | "queryFn">) => {return useQuery({- queryKey: digicertConnectionKeys.codeSigningValidation(- connectionId,- organizationId,- productNameId- ),+ queryKey: digicertConnectionKeys.orgValidation(connectionId, organizationId, productNameId),queryFn: async () => {const { data } = await apiRequest.get<{ isValidated: boolean }>(- `/api/v1/app-connections/digicert/${connectionId}/organizations/${organizationId}/code-signing-validation`,+ `/api/v1/app-connections/digicert/${connectionId}/organizations/${organizationId}/validation`,{ params: { productNameId } });return data;@@ -115,25 +106,25 @@ export const useDigiCertConnectionCodeSigningValidation = (});};-export const useDigiCertConnectionListCodeSigningOrders = (+export const useDigiCertConnectionListOrders = (connectionId: string,organizationId: number,productNameId: string,options?: Omit<UseQueryOptions<- TDigiCertCodeSigningOrder[],+ TDigiCertOrder[],unknown,- TDigiCertCodeSigningOrder[],- ReturnType<typeof digicertConnectionKeys.codeSigningOrders>+ TDigiCertOrder[],+ ReturnType<typeof digicertConnectionKeys.orders>>,"queryKey" | "queryFn">) => {return useQuery({- queryKey: digicertConnectionKeys.codeSigningOrders(connectionId, organizationId, productNameId),+ queryKey: digicertConnectionKeys.orders(connectionId, organizationId, productNameId),queryFn: async () => {- const { data } = await apiRequest.get<TDigiCertCodeSigningOrder[]>(- `/api/v1/app-connections/digicert/${connectionId}/organizations/${organizationId}/code-signing-orders`,+ const { data } = await apiRequest.get<TDigiCertOrder[]>(+ `/api/v1/app-connections/digicert/${connectionId}/organizations/${organizationId}/orders`,{ params: { productNameId } });return data;diff --git a/frontend/src/hooks/api/signers/index.tsx b/frontend/src/hooks/api/signers/index.tsxindex c742619461..b77b3bbc1a 100644--- a/frontend/src/hooks/api/signers/index.tsx+++ b/frontend/src/hooks/api/signers/index.tsx@@ -3,6 +3,7 @@ export {useAddSignerGroupMember,useAddSignerIdentityMember,useAddSignerUserMembers,+ useCheckSignerIssuance,useCreateSigner,useDeleteSigner,useDisableSigner,diff --git a/frontend/src/hooks/api/signers/mutations.tsx b/frontend/src/hooks/api/signers/mutations.tsxindex 7a34bcd35c..e9fd4bebdb 100644--- a/frontend/src/hooks/api/signers/mutations.tsx+++ b/frontend/src/hooks/api/signers/mutations.tsx@@ -6,6 +6,7 @@ import { approvalRequestQuery } from "@app/hooks/api/approvalRequests/queries";import { signerKeys } from "./queries";import {+ SignerStatus,TAddSignerGroupMemberDTO,TAddSignerIdentityMemberDTO,TAddSignerUserMembersDTO,@@ -137,6 +138,31 @@ export const useReissueSignerCertificate = () => {});};+export const useCheckSignerIssuance = () => {+ const queryClient = useQueryClient();++ return useMutation<TSigner, object, string>({+ mutationFn: async (signerId) => {+ const { data } = await apiRequest.post<TSigner>(+ `/api/v1/cert-manager/signers/${signerId}/issuance/check`+ );+ return data;+ },+ onSuccess: (signer) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.byId(signer.id) });+ queryClient.invalidateQueries({ queryKey: signerKeys.list(signer.projectId) });+ queryClient.invalidateQueries({ queryKey: signerKeys.certificate(signer.id) });+ createNotification({+ text:+ signer.status === SignerStatus.Pending+ ? "Issuance still pending. Checked just now."+ : "Issuance status updated",+ type: signer.status === SignerStatus.Pending ? "info" : "success"+ });+ }+ });+};+export const useAddSignerUserMembers = () => {const queryClient = useQueryClient();diff --git a/frontend/src/hooks/api/signers/types.ts b/frontend/src/hooks/api/signers/types.tsindex b375e41d18..3a5b2c7dd3 100644--- a/frontend/src/hooks/api/signers/types.ts+++ b/frontend/src/hooks/api/signers/types.ts@@ -1,7 +1,14 @@+import { CaType } from "@app/hooks/api/ca/enums";+export type TGetUserSignerPermissionDTO = {signerId: string;};+export type TSignerExternalConfiguration = {+ caType: CaType.DIGICERT;+ reissueFromExternalOrderId?: string;+};+export enum SignerStatus {Pending = "pending",Active = "active",@@ -265,9 +272,7 @@ export type TCreateSignerDTO = {members?: TCreateSignerMemberInput[];approvalPolicy?: TCreateSignerApprovalPolicyInput;certificate?: TSignerCertificateInput;- externalConfiguration?: {- reissueFromExternalOrderId?: string;- };+ externalConfiguration?: TSignerExternalConfiguration;};export type TUpdateSignerDTO = {@@ -291,7 +296,7 @@ export type TReissueSignerCertificateDTO = {keySource: CertKeySource;hsmConnectorId?: string;};- reissueFromExternalOrderId?: string;+ externalConfiguration?: TSignerExternalConfiguration;};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 b4d6e8acf9..83fcd09c54 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx@@ -34,9 +34,9 @@ import {import {TDigiCertOrganization,TDigiCertProduct,- useDigiCertConnectionCodeSigningValidation,useDigiCertConnectionListOrganizations,- useDigiCertConnectionListProducts+ useDigiCertConnectionListProducts,+ useDigiCertConnectionOrgValidation} from "@app/hooks/api/appConnections/digicert";import {TDNSMadeEasyZone,@@ -701,7 +701,7 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {!!digicertProductNameId;const { data: csValidation, isFetching: isCsValidationFetching } =- useDigiCertConnectionCodeSigningValidation(+ useDigiCertConnectionOrgValidation(digicertConnectionId,digicertOrganizationId,digicertProductNameId,diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsxindex b4fb631ed1..c8bf25f706 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx@@ -17,7 +17,7 @@ import {TooltipTrigger} from "@app/components/v3";import { ROUTE_PATHS } from "@app/const/routes";-import { useDigiCertConnectionListCodeSigningOrders } from "@app/hooks/api/appConnections/digicert";+import { useDigiCertConnectionListOrders } from "@app/hooks/api/appConnections/digicert";import { getCaIssuanceCapabilities } from "@app/hooks/api/ca";import { CertificateForm } from "./schemas";@@ -42,7 +42,7 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateStconst digicertCfg = selectedCa?.digicert;const canReuseOrder = caps.supportsExistingOrderReuse && Boolean(digicertCfg);const { data: codeSigningOrders = [], isLoading: isOrdersLoading } =- useDigiCertConnectionListCodeSigningOrders(+ useDigiCertConnectionListOrders(digicertCfg?.appConnectionId ?? "",digicertCfg?.organizationId ?? 0,digicertCfg?.productNameId ?? "",@@ -51,7 +51,7 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateStconst orderOptions = codeSigningOrders.map((o) => ({value: String(o.orderId),- label: `${o.commonName || "Code signing certificate"} (#${o.orderId})`,+ label: `${o.commonName || o.organizationName || "Code signing certificate"} (#${o.orderId})`,commonName: o.commonName}));type OrderOption = (typeof orderOptions)[number];@@ -169,6 +169,12 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateStnoOptionsMessage={() => "No existing orders found."}/><FieldDescription>Leave empty to issue a new certificate.</FieldDescription>+ {field.value && (+ <FieldDescription className="text-warning">+ Reissuing replaces the certificate in this order. DigiCert revokes the previous+ one within 72 hours, after which it can no longer be used to sign.+ </FieldDescription>+ )}</FieldContent></Field>)}diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsxindex b4f1ac0130..ddab8a72e8 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx@@ -232,7 +232,10 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =approvalPolicy,certificate,externalConfiguration: state.reissueFromExternalOrderId- ? { reissueFromExternalOrderId: state.reissueFromExternalOrderId }+ ? {+ caType: CaType.DIGICERT,+ reissueFromExternalOrderId: state.reissueFromExternalOrderId+ }: undefined});diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.tsindex b81611c589..0a71bc1627 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts@@ -103,7 +103,7 @@ export const STEPS: WizardStep[] = [subtitle: "Select the issuing CA and the certificate's name and validity.",rightLabel: "CERTIFICATE",rightDescription:- "Select the CA that issues the certificate and the name shown on it. The Common Name cannot be changed after issuance.",+ "Select the CA that issues the certificate and the name shown on it. You can change the name or validity later; doing so reissues the certificate.",docsUrl: PkiDocsUrls.codeSigning.signers.certificate},{diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/SignerDetailPage.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/SignerDetailPage.tsxindex a05d9fa115..c95766e749 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/SignerDetailPage.tsx+++ b/frontend/src/pages/cert-manager/SignerDetailPage/SignerDetailPage.tsx@@ -12,6 +12,7 @@ import {MoreVerticalIcon,PencilIcon,PenTool,+ RefreshCwIcon,RotateCwIcon,Trash2Icon} from "lucide-react";@@ -55,11 +56,14 @@ import {SignerPermissionSub,useSignerPermission} from "@app/context/SignerPermissionContext";+import { useListCasByProjectId } from "@app/hooks/api/ca";+import { CaType } from "@app/hooks/api/ca/enums";import { ProjectType } from "@app/hooks/api/projects/types";import {getSignerStatusBadgeVariant,SignerStatus,signerStatusLabels,+ useCheckSignerIssuance,useDeleteSigner,useDisableSigner,useEnableSigner,@@ -97,6 +101,9 @@ export const SignerDetailPage = () => {const [isExportOpen, setIsExportOpen] = useState(false);const { data: signer, isLoading } = useGetSigner(signerId);+ const cas = useListCasByProjectId();+ const isDigicertSigner =+ (cas.data ?? []).find((ca) => ca.id === signer?.caId)?.type === CaType.DIGICERT;const { permission } = useSignerPermission();const can = (action: SignerPermissionActions) =>permission.can(action, SignerPermissionSub.Signer);@@ -104,6 +111,7 @@ export const SignerDetailPage = () => {const disableSigner = useDisableSigner();const deleteSigner = useDeleteSigner();const reissueSigner = useReissueSignerCertificate();+ const checkSignerIssuance = useCheckSignerIssuance();if (isLoading) return <PageLoader />;if (!signer)@@ -218,6 +226,18 @@ export const SignerDetailPage = () => {Enable signer</DropdownMenuItem>) : null}+ {signer.status === SignerStatus.Pending && (+ <DropdownMenuItem+ onClick={() => checkSignerIssuance.mutate(signer.id)}+ isDisabled={+ checkSignerIssuance.isPending ||+ !can(SignerPermissionActions.ReissueCertificate)+ }+ >+ <RefreshCwIcon />+ Check issuance now+ </DropdownMenuItem>+ )}{signer.status === SignerStatus.Failed && signer.caId && (<DropdownMenuItemonClick={() =>@@ -319,6 +339,12 @@ export const SignerDetailPage = () => {<AlertDialogDescription>This permanently removes the signer, its policy, members, requests, and signinghistory. The certificate is preserved for audit but signing will stop immediately.+ {isDigicertSigner && (+ <span className="mt-2 block font-medium text-warning">+ This also revokes the certificate's DigiCert order, so the certificate can no+ longer be used to sign anywhere.+ </span>+ )}</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsxindex 06f087cbd3..98cc325e53 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx@@ -15,7 +15,7 @@ import {TooltipContent,TooltipTrigger} from "@app/components/v3";-import { useDigiCertConnectionListCodeSigningOrders } from "@app/hooks/api/appConnections/digicert";+import { useDigiCertConnectionListOrders } from "@app/hooks/api/appConnections/digicert";import { getCaIssuanceCapabilities } from "@app/hooks/api/ca";import { CertificateForm } from "./schemas";@@ -25,27 +25,17 @@ type CertificateStepProps = {form: ReturnType<typeof useForm<CertificateForm>>;caOptions: CaOption[];isCasLoading: boolean;- commonName: string;- certificateTtlDays: number | null;- canEditSubject: boolean;};-export const CertificateStep = ({- form,- caOptions,- isCasLoading,- commonName,- certificateTtlDays,- canEditSubject-}: CertificateStepProps) => {+export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateStepProps) => {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 canReuseOrder = caps.supportsExistingOrderReuse && Boolean(digicertCfg);const { data: codeSigningOrders = [], isLoading: isOrdersLoading } =- useDigiCertConnectionListCodeSigningOrders(+ useDigiCertConnectionListOrders(digicertCfg?.appConnectionId ?? "",digicertCfg?.organizationId ?? 0,digicertCfg?.productNameId ?? "",@@ -54,7 +44,7 @@ export const CertificateStep = ({const orderOptions = codeSigningOrders.map((o) => ({value: String(o.orderId),- label: `${o.commonName || "Code signing certificate"} (#${o.orderId})`,+ label: `${o.commonName || o.organizationName || "Code signing certificate"} (#${o.orderId})`,commonName: o.commonName}));type OrderOption = (typeof orderOptions)[number];@@ -160,88 +150,72 @@ export const CertificateStep = ({noOptionsMessage={() => "No existing orders found."}/><FieldDescription>Leave empty to issue a new certificate.</FieldDescription>+ {field.value && (+ <FieldDescription className="text-warning">+ Reissuing replaces the certificate in this order. DigiCert revokes the previous+ one within 72 hours, after which it can no longer be used to sign.+ </FieldDescription>+ )}</FieldContent></Field>)}/>)}- {!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>Common Name</FieldLabel>- <FieldContent>- <Input value={commonName} readOnly disabled />- <FieldDescription>The legal name shown on the certificate.</FieldDescription>- </FieldContent>- </Field>- ))}+ {!isReissue && (+ <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. Changing it reissues the certificate.+ </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>- ))}+ {!isReissue && (+ <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. Changing it reissues the certificate.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ )}<Controllername="certificateRenewBeforeDays"diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsxindex 5b7ffe6c52..c3ad32b821 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx@@ -23,7 +23,6 @@ import { useListHsmConnectors } from "@app/hooks/api/hsmConnectors";import {CertKeySource,SignerKeyAlgorithm,- SignerStatus,TSigner,useReissueSignerCertificate,useUpdateSigner@@ -99,9 +98,6 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {values: { name: signer.name, description: signer.description ?? "" }});- const canEditSubject =- signer.status === SignerStatus.Pending || signer.status === SignerStatus.Failed;-const certificateForm = useForm<CertificateForm>({resolver: zodResolver(certificateSchema),values: {@@ -145,9 +141,8 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {const caSwap = Boolean(watchedCaId) && watchedCaId !== signer.caId;const subjectChanged =- canEditSubject &&- ((watchedCommonName ?? "") !== (signer.commonName ?? "") ||- (watchedTtl ?? 0) !== (signer.certificateTtlDays ?? 0));+ (watchedCommonName ?? "") !== (signer.commonName ?? "") ||+ (watchedTtl ?? 0) !== (signer.certificateTtlDays ?? 0);const keySourceChanged =watchedKeySource !== currentKeySource ||(watchedKeySource === CertKeySource.Hsm &&@@ -191,12 +186,9 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {await reissueCertificate.mutateAsync({signerId: signer.id,caId: cert.caId,- commonName:- !isReissueFromOrder && canEditSubject && subjectChanged ? cert.commonName : undefined,+ commonName: !isReissueFromOrder && subjectChanged ? cert.commonName : undefined,certificateTtlDays:- !isReissueFromOrder && canEditSubject && subjectChanged- ? cert.certificateTtlDays- : undefined,+ !isReissueFromOrder && subjectChanged ? cert.certificateTtlDays : undefined,keyAlgorithm: keySourceChanged || keyAlgorithmChanged ? cert.keyAlgorithm : undefined,certificate:keySourceChanged || keyAlgorithmChanged@@ -208,7 +200,12 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {: undefined}: undefined,- reissueFromExternalOrderId: cert.reissueFromExternalOrderId ?? undefined+ externalConfiguration: cert.reissueFromExternalOrderId+ ? {+ caType: CaType.DIGICERT,+ reissueFromExternalOrderId: cert.reissueFromExternalOrderId+ }+ : undefined});}@@ -326,9 +323,6 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {form={certificateForm}caOptions={caOptions}isCasLoading={cas.isPending}- commonName={signer.commonName ?? signer.certificateCommonName ?? "—"}- certificateTtlDays={signer.certificateTtlDays ?? null}- canEditSubject={canEditSubject}/>)}{step === 2 && (@@ -359,8 +353,10 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {</div><div className="flex shrink-0 items-center justify-between gap-3 border-t border-border px-6 py-4">- <span className="text-xs text-muted">- {shouldReissue ? "Saving will reissue the certificate immediately." : ""}+ <span className="text-xs text-warning">+ {shouldReissue+ ? "Saving reissues the certificate immediately. The signer switches to the new certificate."+ : ""}</span><div className="flex items-center gap-3"><span className="text-xs text-muted">