Skip to content

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

Address PR comments

Carlos Monastyrski92bfb6d1fa97
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index d2c9a72179..471db4dd88 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2329,7 +2329,8 @@ export const CERTIFICATES = {
"Certificate fields to change on renewal. Anything omitted is copied from the certificate being renewed. Profile defaults are not applied.",
removeRootsFromChain: "Whether to remove the root certificate from the returned certificate chain.",
externalConfiguration: "Options for certificates issued by an external certificate authority.",
- reissue: "Reissue the certificate on the same DigiCert order instead of placing a new order."
+ reissue:
+ "Whether to reissue the certificate on its current order with the issuing CA instead of placing a new order. Defaults to `false`. Only for CAs that support reissuing (currently DigiCert), and `ttl` can't be set. If the reissue removes or changes a name, the CA revokes the current certificate (DigiCert within 72 hours), so you also need permission to revoke it."
},
RENEWAL_PREVIEW: {
id: "The ID of the certificate to preview a renewal for.",
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index de43e9bb26..04fa4d7bad 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -4022,7 +4022,8 @@ export const registerRoutes = async (
identityDAL,
certificateProfileDAL,
certificateAuthorityDAL,
- auditLogService
+ auditLogService,
+ digicertFns: digicertCaFns
});
const certificateIssuanceQueue = certificateIssuanceQueueFactory({
@@ -4369,6 +4370,8 @@ export const registerRoutes = async (
cronJob,
certificateAuthorityDAL,
certificateDAL,
+ certificateBodyDAL,
+ projectDAL,
appConnectionDAL,
kmsService,
auditLogService,
diff --git a/backend/src/services/certificate-authority/certificate-issuance-queue.test.ts b/backend/src/services/certificate-authority/certificate-issuance-queue.test.ts
new file mode 100644
index 0000000000..0b11ae5af1
--- /dev/null
+++ b/backend/src/services/certificate-authority/certificate-issuance-queue.test.ts
@@ -0,0 +1,147 @@
+import { CertificateRequestStatus } from "../certificate-request/certificate-request-types";
+import { CaType } from "./certificate-authority-enums";
+import { certificateIssuanceQueueFactory, TIssueCertificateFromProfileJobData } from "./certificate-issuance-queue";
+
+const digicertFns = {
+ orderCertificate: vi.fn(),
+ reissueCertificate: vi.fn(),
+ cancelReissue: vi.fn(),
+ fetchAndAttachIssuedCertificate: vi.fn()
+};
+
+vi.mock("@app/lib/logger", () => ({ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() } }));
+vi.mock("./digicert/digicert-certificate-authority-fns", () => ({
+ DigiCertCertificateAuthorityFns: () => digicertFns
+}));
+
+const CA_ID = "ca-1";
+const ORDER_ID = 7001;
+const ORIGINAL_CERTIFICATE_ID = "00000000-0000-4000-8000-000000000001";
+const CERTIFICATE_REQUEST_ID = "00000000-0000-4000-8000-000000000002";
+
+const stubDeps = () => {
+ const stubs = new Map<string, unknown>();
+ return new Proxy({} as Record<string, unknown>, {
+ get: (_target, property: string) => {
+ if (!stubs.has(property)) stubs.set(property, vi.fn());
+ return stubs.get(property);
+ }
+ });
+};
+
+const buildQueue = () => {
+ let runJob: ((job: { data: TIssueCertificateFromProfileJobData }) => Promise<void>) | undefined;
+ const queueService = {
+ start: vi.fn((_queue: string, handler: typeof runJob) => {
+ runJob = handler;
+ }),
+ queue: vi.fn()
+ };
+ const certificateAuthorityDAL = {
+ findByIdWithAssociatedCa: vi.fn().mockResolvedValue({
+ id: CA_ID,
+ projectId: "project-1",
+ externalCa: { id: "external-ca-1", type: CaType.DIGICERT }
+ })
+ };
+ const certificateDAL = {
+ findById: vi.fn().mockResolvedValue({
+ id: ORIGINAL_CERTIFICATE_ID,
+ externalMetadata: { type: CaType.DIGICERT, orderId: ORDER_ID, certificateId: 50001 }
+ })
+ };
+ const certificateRequestDAL = {
+ findById: vi.fn().mockResolvedValue({ id: CERTIFICATE_REQUEST_ID, status: CertificateRequestStatus.PENDING }),
+ setPendingMessage: vi.fn(),
+ transitionToPendingValidation: vi.fn().mockResolvedValue(true)
+ };
+
+ certificateIssuanceQueueFactory({
+ ...stubDeps(),
+ queueService,
+ certificateAuthorityDAL,
+ certificateDAL,
+ certificateRequestDAL
+ } as unknown as Parameters<typeof certificateIssuanceQueueFactory>[0]);
+
+ const run = (data: Partial<TIssueCertificateFromProfileJobData>) =>
+ runJob!({
+ data: {
+ certificateId: "renewal-1",
+ caId: CA_ID,
+ caType: CaType.DIGICERT,
+ commonName: "example.com",
+ altNames: [{ type: "dns_name", value: "example.com" }],
+ ttl: "90d",
+ signatureAlgorithm: "RSA-SHA256",
+ keyAlgorithm: "RSA_2048",
+ isRenewal: true,
+ originalCertificateId: ORIGINAL_CERTIFICATE_ID,
+ certificateRequestId: CERTIFICATE_REQUEST_ID,
+ ...data
+ }
+ });
+ return Object.assign(run, { certificateRequestDAL });
+};
+
+const digicertResult = {
+ metadata: {
+ digicert: {
+ orderId: ORDER_ID,
+ productNameId: "ssl_basic",
+ organizationId: 777,
+ orderPlacedAt: new Date().toISOString()
+ }
+ },
+ privateKey: "",
+ orderId: ORDER_ID
+};
+
+describe("certificate issuance queue, DigiCert renewals", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ digicertFns.orderCertificate.mockResolvedValue(digicertResult);
+ digicertFns.reissueCertificate.mockResolvedValue(digicertResult);
+ });
+
+ test("reissues on the original certificate's DigiCert order when reissue is requested", async () => {
+ const runJob = buildQueue();
+
+ await runJob({ externalConfiguration: { reissue: true } });
+
+ expect(digicertFns.reissueCertificate).toHaveBeenCalledWith(
+ expect.objectContaining({ caId: CA_ID, orderId: ORDER_ID, originalCertificateId: ORIGINAL_CERTIFICATE_ID })
+ );
+ expect(digicertFns.orderCertificate).not.toHaveBeenCalled();
+ });
+
+ test("places a new order linked to the original order for a plain renewal", async () => {
+ const runJob = buildQueue();
+
+ await runJob({});
+
+ expect(digicertFns.orderCertificate).toHaveBeenCalledWith(
+ expect.objectContaining({ caId: CA_ID, renewalOfOrderId: ORDER_ID })
+ );
+ expect(digicertFns.reissueCertificate).not.toHaveBeenCalled();
+ });
+
+ test("hands a reissue to the poller before DigiCert is called", async () => {
+ const runJob = buildQueue();
+ const reissueMetadata = { ...digicertResult.metadata.digicert, previousCertificateId: 50001 };
+ digicertFns.reissueCertificate.mockImplementation(
+ async ({ onBeforeSubmit }: { onBeforeSubmit: (prepared: object) => Promise<void> }) => {
+ await onBeforeSubmit({ metadata: { digicert: reissueMetadata }, privateKey: "" });
+ expect(runJob.certificateRequestDAL.transitionToPendingValidation).toHaveBeenCalledWith(
+ CERTIFICATE_REQUEST_ID,
+ expect.objectContaining({ metadata: expect.stringContaining('"previousCertificateId":50001') as string })
+ );
+ return digicertResult;
+ }
+ );
+
+ await runJob({ externalConfiguration: { reissue: true }, csr: "csr" });
+
+ expect(runJob.certificateRequestDAL.transitionToPendingValidation).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/backend/src/services/certificate-authority/certificate-issuance-queue.ts b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
index 0108b93ba9..7d22bf11a2 100644
--- a/backend/src/services/certificate-authority/certificate-issuance-queue.ts
+++ b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
@@ -79,6 +79,7 @@ import { CaType } from "./certificate-authority-enums";
import { keyAlgorithmToAlgCfg } from "./certificate-authority-fns";
import { assertCaSupportsCustomExtensions } from "./certificate-authority-maps";
import { DigiCertCertificateAuthorityFns } from "./digicert/digicert-certificate-authority-fns";
+import { TDigiCertCertificateRequestMetadata } from "./digicert/digicert-certificate-authority-types";
import { TExternalCertificateAuthorityDALFactory } from "./external-certificate-authority-dal";
import { GoDaddyCertificateAuthorityFns } from "./godaddy/godaddy-certificate-authority-fns";
import { VenafiTppCertificateAuthorityFns } from "./venafi-tpp/venafi-tpp-certificate-authority-fns";
@@ -896,13 +897,44 @@ export const certificateIssuanceQueueFactory = ({
...(csr && { csr })
};
- const digicertResult =
+ const encryptPrivateKey = async (privateKey: string) => {
+ const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
+ projectId: ca.projectId,
+ projectDAL,
+ kmsService
+ });
+ const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: certificateManagerKmsId });
+ const { cipherTextBlob } = await kmsEncryptor({ plainText: Buffer.from(privateKey) });
+ return cipherTextBlob;
+ };
+ const withRenewalMetadata = (metadata: TDigiCertCertificateRequestMetadata) => ({
+ ...metadata,
+ digicert: {
+ ...metadata.digicert,
+ ...(isRenewal && originalCertificateId ? { isRenewal: true, originalCertificateId } : {})
+ }
+ });
+
+ const isReissue = Boolean(
externalConfiguration?.reissue && renewalOfOrderId !== undefined && originalCertificateId
+ );
+ let encryptedPrivateKey: Buffer | undefined;
+
+ const digicertResult =
+ isReissue && renewalOfOrderId !== undefined && originalCertificateId
? await digicertFns.reissueCertificate({
...digicertRequest,
orderId: renewalOfOrderId,
ttl,
- originalCertificateId
+ originalCertificateId,
+ onBeforeSubmit: async ({ metadata, privateKey }) => {
+ encryptedPrivateKey = privateKey ? await encryptPrivateKey(privateKey) : undefined;
+ const transitioned = await certificateRequestDAL.transitionToPendingValidation(certificateRequestId, {
+ metadata: JSON.stringify(withRenewalMetadata(metadata)),
+ ...(encryptedPrivateKey && { encryptedPrivateKey })
+ });
+ if (!transitioned) throw new CertificateRequestCancelledError();
+ }
})
: await digicertFns.orderCertificate({
...digicertRequest,
@@ -910,47 +942,34 @@ export const certificateIssuanceQueueFactory = ({
...(renewalOfOrderId !== undefined && { renewalOfOrderId })
});
- const untrackedReissueMessage = `DigiCert reissue on order ${digicertResult.orderId} is still open but will not be tracked; cancel it in DigiCert CertCentral before reissuing again [certificateRequestId=${certificateRequestId}]`;
-
if (await isCancelled()) {
logger.info(
`Cancelled after DigiCert order — order placed at CA but will not be tracked locally [certificateRequestId=${certificateRequestId}]`
);
- if (externalConfiguration?.reissue) logger.error(untrackedReissueMessage);
+ if (isReissue) await digicertFns.cancelReissue({ caId, orderId: digicertResult.orderId });
return;
}
- let encryptedPrivateKey: Buffer | undefined;
- if (digicertResult.privateKey) {
- const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
- projectId: ca.projectId,
- projectDAL,
- kmsService
- });
- const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: certificateManagerKmsId });
- const { cipherTextBlob } = await kmsEncryptor({ plainText: Buffer.from(digicertResult.privateKey) });
- encryptedPrivateKey = cipherTextBlob;
- }
-
- const metadataWithRenewal = {
- ...digicertResult.metadata,
- digicert: {
- ...digicertResult.metadata.digicert,
- ...(isRenewal && originalCertificateId ? { isRenewal: true, originalCertificateId } : {})
+ if (isReissue) {
+ if (digicertResult.immediateCertificateId) {
+ await certificateRequestDAL.updateById(certificateRequestId, {
+ metadata: JSON.stringify(withRenewalMetadata(digicertResult.metadata))
+ });
}
- };
+ } else {
+ if (digicertResult.privateKey) encryptedPrivateKey = await encryptPrivateKey(digicertResult.privateKey);
- const transitioned = await certificateRequestDAL.transitionToPendingValidation(certificateRequestId, {
- metadata: JSON.stringify(metadataWithRenewal),
- ...(encryptedPrivateKey && { encryptedPrivateKey })
- });
+ const transitioned = await certificateRequestDAL.transitionToPendingValidation(certificateRequestId, {
+ metadata: JSON.stringify(withRenewalMetadata(digicertResult.metadata)),
+ ...(encryptedPrivateKey && { encryptedPrivateKey })
+ });
- if (!transitioned) {
- logger.info(
- `Skipping DigiCert validation transition — request is no longer pending [certificateRequestId=${certificateRequestId}]`
- );
- if (externalConfiguration?.reissue) logger.error(untrackedReissueMessage);
- return;
+ if (!transitioned) {
+ logger.info(
+ `Skipping DigiCert validation transition — request is no longer pending [certificateRequestId=${certificateRequestId}]`
+ );
+ return;
+ }
}
if (digicertResult.immediateCertificateId) {
diff --git a/backend/src/services/certificate-authority/digicert/digicert-api-client.ts b/backend/src/services/certificate-authority/digicert/digicert-api-client.ts
index 35c8ac1a28..49329cbde3 100644
--- a/backend/src/services/certificate-authority/digicert/digicert-api-client.ts
+++ b/backend/src/services/certificate-authority/digicert/digicert-api-client.ts
@@ -122,6 +122,11 @@ export const createDigiCertApiClient = (apiKey: string, baseURL: string) => {
await request.put(`${baseURL}/order/certificate/${orderId}/revoke`, { comments }, { headers });
}, `order revocation for ${orderId}`);
+ const cancelOrderReissue = async (orderId: number, note: string) =>
+ wrap(async () => {
+ await request.put(`${baseURL}/order/certificate/${orderId}/status`, { status: "canceled", note }, { headers });
+ }, `reissue cancellation for order ${orderId}`);
+
const revokeCertificate = async (certificateId: number, comments: string) =>
wrap(async () => {
await request.put(`${baseURL}/certificate/${certificateId}/revoke`, { comments }, { headers });
@@ -147,6 +152,7 @@ export const createDigiCertApiClient = (apiKey: string, baseURL: string) => {
getOrdersByAlternativeId,
revokeOrder,
revokeCertificate,
+ cancelOrderReissue,
listOrderStatusChanges
};
};
diff --git a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-fns.test.ts b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-fns.test.ts
new file mode 100644
index 0000000000..53762fd902
--- /dev/null
+++ b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-fns.test.ts
@@ -0,0 +1,91 @@
+import { CaStatus, CaType } from "../certificate-authority-enums";
+import { DigiCertCertificateAuthorityFns } from "./digicert-certificate-authority-fns";
+
+const client = {
+ getOrder: vi.fn(),
+ reissueOrder: vi.fn(),
+ downloadCertificatePem: vi.fn()
+};
+
+vi.mock("@app/lib/logger", () => ({ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() } }));
+vi.mock("./digicert-api-client", () => ({ createDigiCertApiClient: () => client }));
+vi.mock("./digicert-certificate-authority-shared", () => ({
+ castDbEntryToDigiCertCertificateAuthority: () => ({
+ id: "ca-1",
+ status: CaStatus.ACTIVE,
+ configuration: { appConnectionId: "connection-1", organizationId: 777, productNameId: "ssl_basic" }
+ }),
+ getDigiCertClientCredentials: vi.fn().mockResolvedValue({ apiKey: "key", baseUrl: "https://digicert.example" }),
+ extractLeafAndChain: vi.fn()
+}));
+
+const CA_ID = "ca-1";
+const ORDER_ID = 7001;
+const CURRENT_CERTIFICATE_ID = 50001;
+const ORIGINAL_CERTIFICATE_ID = "00000000-0000-4000-8000-000000000001";
+const CSR = "-----BEGIN CERTIFICATE REQUEST-----\nMIIB\n-----END CERTIFICATE REQUEST-----";
+
+const buildFns = (storedCertificateId: number) => {
+ const certificateDAL = {
+ findById: vi.fn().mockResolvedValue({
+ id: ORIGINAL_CERTIFICATE_ID,
+ serialNumber: "0a1b",
+ externalMetadata: { type: CaType.DIGICERT, orderId: ORDER_ID, certificateId: storedCertificateId }
+ }),
+ updateById: vi.fn()
+ };
+ const certificateAuthorityDAL = {
+ findByIdWithAssociatedCa: vi.fn().mockResolvedValue({ id: CA_ID, externalCa: { type: CaType.DIGICERT } })
+ };
+ return DigiCertCertificateAuthorityFns({
+ certificateDAL,
+ certificateAuthorityDAL
+ } as unknown as Parameters<typeof DigiCertCertificateAuthorityFns>[0]);
+};
+
+const reissue = (fns: ReturnType<typeof buildFns>) =>
+ fns.reissueCertificate({
+ caId: CA_ID,
+ orderId: ORDER_ID,
+ originalCertificateId: ORIGINAL_CERTIFICATE_ID,
+ commonName: "example.com",
+ altNames: ["example.com", "www.example.com"],
+ csr: CSR,
+ ttl: "90d"
+ });
+
+describe("DigiCert reissueCertificate", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ client.getOrder.mockResolvedValue({
+ id: ORDER_ID,
+ status: "issued",
+ certificate: { id: CURRENT_CERTIFICATE_ID },
+ organization: { id: 777 },
+ product: { name_id: "ssl_basic" }
+ });
+ client.reissueOrder.mockResolvedValue({ id: ORDER_ID });
+ });
+
+ test("reissues the original certificate's order with its validity", async () => {
+ await reissue(buildFns(CURRENT_CERTIFICATE_ID));
+
+ expect(client.reissueOrder).toHaveBeenCalledWith(
+ ORDER_ID,
+ expect.objectContaining({
+ certificate: expect.objectContaining({
+ common_name: "example.com",
+ dns_names: ["www.example.com"],
+ cert_validity: { days: 90 }
+ }) as object
+ })
+ );
+ });
+
+ test("refuses to reissue a certificate that is no longer the order's current certificate", async () => {
+ await expect(reissue(buildFns(CURRENT_CERTIFICATE_ID - 1))).rejects.toThrow(
+ `This certificate is no longer the current one on DigiCert order ${ORDER_ID}`
+ );
+ expect(client.reissueOrder).not.toHaveBeenCalled();
+ });
+});
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.ts
index f7bfa864f0..237c55bcd3 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
@@ -531,12 +531,14 @@ export const DigiCertCertificateAuthorityFns = ({
keyAlgorithm = CertKeyAlgorithm.RSA_2048,
csr,
ttl,
- originalCertificateId
+ originalCertificateId,
+ onBeforeSubmit
}: {
caId: string;
orderId: number;
ttl: string;
originalCertificateId: string;
+ onBeforeSubmit?: (prepared: { metadata: TDigiCertCertificateRequestMetadata; privateKey: string }) => Promise<void>;
commonName: string;
altNames?: string[];
signatureAlgorithm?: string;
@@ -560,20 +562,30 @@ export const DigiCertCertificateAuthorityFns = ({
}
if (orderStatus !== DigiCertOrderStatus.Issued || !order.certificate?.id) {
throw new BadRequestError({
- message: `DigiCert order ${orderId} is ${order.status ?? "not issued"}, so it can't be reissued.`
+ message: `DigiCert order ${orderId} can't be reissued because its status in DigiCert is "${order.status ?? "unknown"}". Only issued orders can be reissued.`
});
}
const previousCertificateId = order.certificate.id;
const originalCertificate = await certificateDAL.findById(originalCertificateId);
- const originalMetadata = DigiCertExternalMetadataSchema.safeParse(originalCertificate?.externalMetadata);
- if (originalCertificate && originalMetadata.success && !originalMetadata.data.certificateId) {
- const previousSerialNumber = await $getCertificateSerialNumber(client, previousCertificateId);
- if (previousSerialNumber === originalCertificate.serialNumber.toLowerCase()) {
- await certificateDAL.updateById(originalCertificate.id, {
- externalMetadata: { ...originalMetadata.data, certificateId: previousCertificateId }
- });
- }
+ if (!originalCertificate) {
+ throw new NotFoundError({ message: `Certificate not found [certificateId=${originalCertificateId}]` });
+ }
+ const originalMetadata = DigiCertExternalMetadataSchema.safeParse(originalCertificate.externalMetadata);
+ const storedCertificateId = originalMetadata.success ? originalMetadata.data.certificateId : undefined;
+ const isCurrentOnOrder = storedCertificateId
+ ? storedCertificateId === previousCertificateId
+ : (await $getCertificateSerialNumber(client, previousCertificateId)) ===
+ originalCertificate.serialNumber.toLowerCase();
+ if (!isCurrentOnOrder) {
+ throw new BadRequestError({
+ message: `This certificate is no longer the current one on DigiCert order ${orderId}, so it can't be reissued. Reissue the order's current certificate instead.`
+ });
+ }
+ if (originalMetadata.success && !storedCertificateId) {
+ await certificateDAL.updateById(originalCertificate.id, {
+ externalMetadata: { ...originalMetadata.data, certificateId: previousCertificateId }
+ });
}
const { certificate, privateKeyPem } = await $buildCertificatePayload({
@@ -586,11 +598,24 @@ export const DigiCertCertificateAuthorityFns = ({
});
const reissuePayload: TReissueOrderRequest = {
- certificate,
- cert_validity: { days: Math.min(parseTtlToDays(ttl), DIGICERT_MAX_CERTIFICATE_VALIDITY_DAYS) },
+ certificate: {
+ ...certificate,
+ cert_validity: { days: Math.min(parseTtlToDays(ttl), DIGICERT_MAX_CERTIFICATE_VALIDITY_DAYS) }
+ },
dcv_method: "dns-txt-token",
skip_approval: true
};
+ const metadata: TDigiCertCertificateRequestMetadata = {
+ digicert: {
+ orderId,
+ productNameId,
+ organizationId,
+ orderPlacedAt: new Date().toISOString(),
+ previousCertificateId
+ }
+ };
+ await onBeforeSubmit?.({ metadata, privateKey: privateKeyPem });
+
const reissueResponse = await client.reissueOrder(orderId, reissuePayload);
const immediateCertificateId =
reissueResponse.certificate_id && reissueResponse.certificate_id !== previousCertificateId
@@ -598,22 +623,25 @@ export const DigiCertCertificateAuthorityFns = ({
: undefined;
return {
- metadata: {
- digicert: {
- orderId,
- certificateId: immediateCertificateId,
- productNameId,
- organizationId,
- orderPlacedAt: new Date().toISOString(),
- previousCertificateId
- }
- },
+ metadata: { digicert: { ...metadata.digicert, certificateId: immediateCertificateId } },
privateKey: privateKeyPem,
immediateCertificateId,
orderId
};
};
+ const cancelReissue = async ({ caId, orderId }: { caId: string; orderId: number }): Promise<boolean> => {
+ try {
+ const { client } = await $getActiveDigiCertCa(caId);
+ await client.cancelOrderReissue(orderId, "Canceled from Infisical");
+ logger.info(`DigiCert reissue canceled [caId=${caId}] [orderId=${orderId}]`);
+ return true;
+ } catch (error) {
+ logger.warn(error, `Failed to cancel DigiCert reissue [caId=${caId}] [orderId=${orderId}]`);
+ return false;
+ }
+ };
+
const fetchAndAttachIssuedCertificate = async ({
caId,
certificateRequest,
@@ -865,7 +893,7 @@ export const DigiCertCertificateAuthorityFns = ({
const currentSerialNumber = await $getCertificateSerialNumber(client, currentCertificateId);
if (currentSerialNumber !== cert.serialNumber.toLowerCase()) {
throw new BadRequestError({
- message: `This certificate is no longer the current one on DigiCert order ${orderId}, and revoking the order would also revoke the certificate that replaced it. Revoke this certificate in DigiCert CertCentral.`
+ message: `This certificate is no longer the current one on DigiCert order ${orderId}, and revoking the order would also revoke the certificate that replaced it. Revoke the certificate with serial number ${cert.serialNumber} in DigiCert CertCentral.`
});
}
digicertCertificateId = currentCertificateId;
@@ -901,6 +929,7 @@ export const DigiCertCertificateAuthorityFns = ({
listCertificateAuthorities,
orderCertificate,
reissueCertificate,
+ cancelReissue,
fetchAndAttachIssuedCertificate,
pollOrderForCertificate,
revokeCertificate,
diff --git a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.test.ts b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.test.ts
index b5ff1c52c5..36d4c7bc66 100644
--- a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.test.ts
+++ b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.test.ts
@@ -43,6 +43,7 @@ const buildRequest = (orderPlacedAt = new Date().toISOString()) =>
const buildDeps = () => {
const fetchAndAttachIssuedCertificate = vi.fn().mockResolvedValue({ certificateId: "new-cert", certificatePem: "" });
+ const cancelReissue = vi.fn().mockResolvedValue(true);
const deps = {
certificateAuthorityDAL: { findByIdWithAssociatedCa: vi.fn() },
appConnectionDAL: { findById: vi.fn() },
@@ -53,12 +54,12 @@ const buildDeps = () => {
attachCertificateToRequest: vi.fn()
},
resourceMetadataDAL: { find: vi.fn().mockResolvedValue([]), insertMany: vi.fn() },
- digicertFns: { fetchAndAttachIssuedCertificate },
+ digicertFns: { fetchAndAttachIssuedCertificate, cancelReissue },
projectDAL: { findById: vi.fn().mockResolvedValue({ orgId: "org-1" }) },
telemetryService: { sendPostHogEvents: vi.fn() },
certificateAlertEventEmitter: { notify: vi.fn() }
} as unknown as TProcessDigiCertRequestDeps;
- return { deps, fetchAndAttachIssuedCertificate };
+ return { deps, fetchAndAttachIssuedCertificate, cancelReissue };
};
const buildClientCache = (client: Partial<TDigiCertApiClient>) => new Map([[CA_ID, client as TDigiCertApiClient]]);
@@ -105,16 +106,17 @@ describe("processDigiCertPendingValidationRequest reissue", () => {
expect(result.status).toBe(CertificateRequestStatus.ISSUED);
});
- test("fails a reissue that DigiCert hasn't finished within 24 hours with a next step", async () => {
- const { deps } = buildDeps();
+ test("cancels a reissue that DigiCert hasn't finished within 24 hours", async () => {
+ const { deps, cancelReissue } = buildDeps();
const dayAgo = new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString();
const result = await processDigiCertPendingValidationRequest(deps, buildRequest(dayAgo), buildClientCache({}));
+ expect(cancelReissue).toHaveBeenCalledWith({ caId: CA_ID, orderId: ORDER_ID });
expect(result.status).toBe(CertificateRequestStatus.FAILED);
expect(deps.certificateRequestService.updateCertificateRequestStatus).toHaveBeenCalledWith(
expect.objectContaining({
- errorMessage: expect.stringContaining(`reissue on order ${ORDER_ID} within 24 hours`) as string
+ errorMessage: expect.stringContaining(`within 24 hours, so it was canceled`) as string
})
);
});
diff --git a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.ts b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.ts
index a3d5e9c5ac..a8e3b8d99b 100644
--- a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.ts
+++ b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-processor.ts
@@ -67,7 +67,7 @@ export type TProcessDigiCertRequestDeps = {
certificateRequestDAL: Pick<TCertificateRequestDALFactory, "updateById" | "setPendingMessage">;
certificateRequestService: TDigiCertCertificateRequestServiceDep;
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find" | "insertMany">;
- digicertFns: Pick<TDigiCertCertificateAuthorityFns, "fetchAndAttachIssuedCertificate">;
+ digicertFns: Pick<TDigiCertCertificateAuthorityFns, "fetchAndAttachIssuedCertificate" | "cancelReissue">;
projectDAL: Pick<TProjectDALFactory, "findById">;
telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;
@@ -140,15 +140,22 @@ export const processDigiCertPendingValidationRequest = async (
const age = Date.now() - new Date(parsed.digicert.orderPlacedAt).getTime();
if (age >= DIGICERT_VALIDATION_TIMEOUT_MS) {
+ let errorMessage = "Validation timed out after 24h";
+ if (parsed.digicert.previousCertificateId !== undefined) {
+ const isReissueCanceled = await deps.digicertFns.cancelReissue({
+ caId: request.caId,
+ orderId: parsed.digicert.orderId
+ });
+ errorMessage = isReissueCanceled
+ ? `DigiCert didn't finish the reissue on order ${parsed.digicert.orderId} within 24 hours, so it was canceled. Submit a new request to reissue again.`
+ : `DigiCert didn't finish the reissue on order ${parsed.digicert.orderId} within 24 hours. Cancel the reissue in DigiCert CertCentral and submit a new request. Finishing it in CertCentral won't bring its certificate into Infisical.`;
+ }
await deps.certificateRequestService.updateCertificateRequestStatus({
certificateRequestId: request.id,
status: CertificateRequestStatus.FAILED,
operation: parsed.digicert.isRenewal ? CertificateIssuanceOperation.RENEW : CertificateIssuanceOperation.ORDER,
originalCertificateId: parsed.digicert.originalCertificateId,
- errorMessage:
- parsed.digicert.previousCertificateId !== undefined
- ? `DigiCert didn't finish the reissue on order ${parsed.digicert.orderId} within 24 hours. Finish or cancel it in DigiCert CertCentral.`
- : "Validation timed out after 24h"
+ errorMessage
});
logger.info(`DigiCert validation timed out [certificateRequestId=${request.id}]`);
return { status: CertificateRequestStatus.FAILED, orderStatus: "timeout", reason: "timeout" };
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.ts
index eeab3867a6..3f56482195 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
@@ -32,13 +32,7 @@ export type TPlaceOrderRequest = {
};
export type TReissueOrderRequest = {
- certificate: {
- common_name: string;
- dns_names?: string[];
- csr: string;
- signature_hash?: string;
- };
- cert_validity?: { days: number };
+ certificate: TPlaceOrderRequest["certificate"] & { cert_validity?: { days: number } };
dcv_method?: "dns-txt-token";
skip_approval?: boolean;
};
diff --git a/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.test.ts b/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.test.ts
new file mode 100644
index 0000000000..e5c07da266
--- /dev/null
+++ b/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.test.ts
@@ -0,0 +1,158 @@
+import { webcrypto } from "node:crypto";
+
+import * as x509 from "@peculiar/x509";
+
+import { OcspCertStatus } from "@app/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-enums";
+import { CertStatus } from "@app/services/certificate/certificate-types";
+
+import { digicertRevocationSyncQueueFactory } from "./digicert-revocation-sync-queue";
+
+const getCertificateOcspStatus = vi.fn<(...args: unknown[]) => Promise<unknown>>();
+const listOrderStatusChanges = vi.fn();
+
+vi.mock("@app/lib/logger", () => ({ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() } }));
+vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ isSecondaryInstance: false }) }));
+vi.mock("@app/services/certificate/certificate-ocsp-client", () => ({
+ getCertificateOcspStatus: (...args: unknown[]) => getCertificateOcspStatus(...args)
+}));
+vi.mock("@app/services/project/project-fns", () => ({
+ getProjectKmsCertificateKeyId: vi.fn().mockResolvedValue("kms-1")
+}));
+vi.mock("./digicert-api-client", () => ({ createDigiCertApiClient: () => ({ listOrderStatusChanges }) }));
+vi.mock("./digicert-certificate-authority-fns", () => ({
+ castDbEntryToDigiCertCertificateAuthority: () => ({ id: "ca-1", configuration: { appConnectionId: "connection-1" } }),
+ getDigiCertClientCredentials: vi.fn().mockResolvedValue({ apiKey: "key", baseUrl: "https://digicert.example" })
+}));
+
+const RSA_ALG: RsaHashedKeyGenParams = {
+ name: "RSASSA-PKCS1-v1_5",
+ hash: "SHA-256",
+ publicExponent: new Uint8Array([1, 0, 1]),
+ modulusLength: 2048
+};
+const REVOKED_AT = new Date("2026-10-28T09:02:41.000Z");
+
+const replacedCertificate = (id: string) => ({
+ id,
+ commonName: "example.com",
+ serialNumber: id,
+ projectId: "project-1",
+ applicationId: null
+});
+
+let certificateBody: { encryptedCertificate: Buffer; encryptedCertificateChain: Buffer };
+
+beforeAll(async () => {
+ x509.cryptoProvider.set(webcrypto as unknown as Crypto);
+ const caKeys = (await webcrypto.subtle.generateKey(RSA_ALG, true, ["sign", "verify"])) as CryptoKeyPair;
+ const caCertificate = await x509.X509CertificateGenerator.createSelfSigned({
+ serialNumber: "01",
+ name: "CN=Example Issuing CA",
+ notBefore: new Date(Date.now() - 86_400_000),
+ notAfter: new Date(Date.now() + 86_400_000),
+ signingAlgorithm: RSA_ALG,
+ keys: caKeys
+ });
+ const leafKeys = (await webcrypto.subtle.generateKey(RSA_ALG, true, ["sign", "verify"])) as CryptoKeyPair;
+ const leafCertificate = await x509.X509CertificateGenerator.create({
+ serialNumber: "02",
+ subject: "CN=example.com",
+ issuer: caCertificate.subject,
+ notBefore: new Date(Date.now() - 3_600_000),
+ notAfter: new Date(Date.now() + 3_600_000),
+ signingKey: caKeys.privateKey,
+ publicKey: leafKeys.publicKey,
+ signingAlgorithm: RSA_ALG
+ });
+ certificateBody = {
+ encryptedCertificate: Buffer.from(leafCertificate.rawData),
+ encryptedCertificateChain: Buffer.from(caCertificate.toString("pem"))
+ };
+});
+
+const runSync = async ({
+ replaced,
+ revokedOrderCertificates = []
+}: {
+ replaced: ReturnType<typeof replacedCertificate>[];
+ revokedOrderCertificates?: ReturnType<typeof replacedCertificate>[];
+}) => {
+ let handler: (() => Promise<void>) | undefined;
+ const certificateDAL = {
+ findActiveDigiCertCertsByOrderIds: vi.fn().mockResolvedValue(revokedOrderCertificates),
+ findActiveDigiCertCertsReplacedOnOrder: vi.fn().mockResolvedValue(replaced),
+ updateById: vi.fn()
+ };
+ listOrderStatusChanges.mockResolvedValue({
+ orders: revokedOrderCertificates.length ? [{ order_id: 7001, status: "revoked" }] : []
+ });
+
+ digicertRevocationSyncQueueFactory({
+ cronJob: {
+ register: ({ handler: registered }: { handler: () => Promise<void> }) => {
+ handler = registered;
+ }
+ },
+ certificateAuthorityDAL: { findWithAssociatedCa: vi.fn().mockResolvedValue([{ id: "ca-1" }]) },
+ certificateDAL,
+ certificateBodyDAL: { findOne: vi.fn().mockResolvedValue(certificateBody) },
+ projectDAL: {},
+ appConnectionDAL: {},
+ kmsService: {
+ decryptWithKmsKey: vi.fn().mockResolvedValue(({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob)
+ },
+ auditLogService: { createAuditLog: vi.fn() },
+ certificateAlertEventEmitter: { notify: vi.fn() }
+ } as unknown as Parameters<typeof digicertRevocationSyncQueueFactory>[0]).init();
+
+ await handler!();
+ return certificateDAL;
+};
+
+describe("DigiCert revocation sync, certificates replaced on their order", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ test("marks a replaced certificate revoked when OCSP reports it revoked", async () => {
+ getCertificateOcspStatus.mockResolvedValue({ status: OcspCertStatus.Revoked, revokedAt: REVOKED_AT });
+
+ const certificateDAL = await runSync({ replaced: [replacedCertificate("cert-1")] });
+
+ expect(certificateDAL.updateById).toHaveBeenCalledWith(
+ "cert-1",
+ expect.objectContaining({ status: CertStatus.REVOKED, revokedAt: REVOKED_AT })
+ );
+ });
+
+ test("leaves a replaced certificate active when OCSP reports it good", async () => {
+ getCertificateOcspStatus.mockResolvedValue({ status: OcspCertStatus.Good });
+
+ const certificateDAL = await runSync({ replaced: [replacedCertificate("cert-1")] });
+
+ expect(certificateDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ test("keeps checking the other certificates when one OCSP check fails", async () => {
+ getCertificateOcspStatus
+ .mockRejectedValueOnce(new Error("responder unavailable"))
+ .mockResolvedValueOnce({ status: OcspCertStatus.Revoked, revokedAt: REVOKED_AT });
+
+ const certificateDAL = await runSync({
+ replaced: [replacedCertificate("cert-1"), replacedCertificate("cert-2")]
+ });
+
+ expect(certificateDAL.updateById).toHaveBeenCalledTimes(1);
+ expect(certificateDAL.updateById).toHaveBeenCalledWith("cert-2", expect.any(Object));
+ });
+
+ test("skips certificates already revoked with their order", async () => {
+ const certificateDAL = await runSync({
+ replaced: [replacedCertificate("cert-1")],
+ revokedOrderCertificates: [replacedCertificate("cert-1")]
+ });
+
+ expect(getCertificateOcspStatus).not.toHaveBeenCalled();
+ expect(certificateDAL.updateById).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts b/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts
index d8f8981f6d..509ed43c95 100644
--- a/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts
+++ b/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts
@@ -1,6 +1,9 @@
/* eslint-disable no-await-in-loop */
+import * as x509 from "@peculiar/x509";
+
import { TableName } from "@app/db/schemas";
import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
+import { OcspCertStatus } from "@app/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-enums";
import { getConfig } from "@app/lib/config/env";
import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
@@ -10,12 +13,16 @@ import {
CertificateApplicationAlertEvent,
TCertificateAlertEventEmitter
} from "@app/services/certificate/certificate-alert-events";
+import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
-import { revocationReasonToCrlCode } from "@app/services/certificate/certificate-fns";
+import { parsePemCertificateChain, revocationReasonToCrlCode } from "@app/services/certificate/certificate-fns";
+import { getCertificateOcspStatus } from "@app/services/certificate/certificate-ocsp-client";
import { CertStatus, CrlReason } from "@app/services/certificate/certificate-types";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TPkiAlertV2QueueServiceFactory } from "@app/services/pki-alert-v2/pki-alert-v2-queue";
import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types";
+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";
@@ -34,9 +41,14 @@ const HANDLER_TIMEOUT_MS = 30 * 60 * 1000;
type TDigiCertRevocationSyncQueueFactoryDep = {
cronJob: TCronJobFactory;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findWithAssociatedCa">;
- certificateDAL: Pick<TCertificateDALFactory, "findActiveDigiCertCertsByOrderIds" | "updateById">;
+ certificateDAL: Pick<
+ TCertificateDALFactory,
+ "findActiveDigiCertCertsByOrderIds" | "findActiveDigiCertCertsReplacedOnOrder" | "updateById"
+ >;
+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;
+ projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey" | "decryptWithKmsKey" | "generateKmsKey">;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;
certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "notify">;
@@ -48,6 +60,8 @@ export const digicertRevocationSyncQueueFactory = ({
cronJob,
certificateAuthorityDAL,
certificateDAL,
+ certificateBodyDAL,
+ projectDAL,
appConnectionDAL,
kmsService,
auditLogService,
@@ -56,16 +70,19 @@ export const digicertRevocationSyncQueueFactory = ({
}: TDigiCertRevocationSyncQueueFactoryDep) => {
const appCfg = getConfig();
- const markCertificateRevokedLocally = async (cert: {
- id: string;
- commonName: string;
- serialNumber: string;
- projectId: string;
- applicationId?: string | null;
- }) => {
+ const markCertificateRevokedLocally = async (
+ cert: {
+ id: string;
+ commonName: string;
+ serialNumber: string;
+ projectId: string;
+ applicationId?: string | null;
+ },
+ revokedAt = new Date()
+ ) => {
await certificateDAL.updateById(cert.id, {
status: CertStatus.REVOKED,
- revokedAt: new Date(),
+ revokedAt,
revocationReason: revocationReasonToCrlCode(CrlReason.UNSPECIFIED)
});
@@ -102,6 +119,63 @@ export const digicertRevocationSyncQueueFactory = ({
}
};
+ const loadCertificateAndIssuer = async (
+ cert: { id: string; projectId: string },
+ getKmsDecryptor: (projectId: string) => Promise<(args: { cipherTextBlob: Buffer }) => Promise<Buffer>>
+ ) => {
+ const certBody = await certificateBodyDAL.findOne({ certId: cert.id });
+ if (!certBody?.encryptedCertificateChain) return null;
+
+ const kmsDecryptor = await getKmsDecryptor(cert.projectId);
+ const certificate = new x509.X509Certificate(
+ new Uint8Array(await kmsDecryptor({ cipherTextBlob: certBody.encryptedCertificate }))
+ );
+ const chain = parsePemCertificateChain(
+ (await kmsDecryptor({ cipherTextBlob: certBody.encryptedCertificateChain })).toString()
+ );
+ const issuer = chain?.find((chainCert) => chainCert.subject === certificate.issuer);
+ return issuer ? { certificate, issuer } : null;
+ };
+
+ const syncReplacedCertificateRevocations = async (caId: string, alreadyRevokedIds: Set<string>) => {
+ const replacedCertificates = await certificateDAL.findActiveDigiCertCertsReplacedOnOrder(caId);
+
+ const kmsDecryptorsByProjectId = new Map<string, (args: { cipherTextBlob: Buffer }) => Promise<Buffer>>();
+ const getKmsDecryptor = async (projectId: string) => {
+ const cached = kmsDecryptorsByProjectId.get(projectId);
+ if (cached) return cached;
+ const kmsId = await getProjectKmsCertificateKeyId({ projectId, projectDAL, kmsService });
+ const kmsDecryptor = await kmsService.decryptWithKmsKey({ kmsId });
+ kmsDecryptorsByProjectId.set(projectId, kmsDecryptor);
+ return kmsDecryptor;
+ };
+
+ let revokedCount = 0;
+ for (const cert of replacedCertificates.filter(({ id }) => !alreadyRevokedIds.has(id))) {
+ try {
+ const certificateAndIssuer = await loadCertificateAndIssuer(cert, getKmsDecryptor);
+ if (!certificateAndIssuer) {
+ throw new Error("No issuer certificate stored for the certificate");
+ }
+
+ const { status, revokedAt } = await getCertificateOcspStatus(certificateAndIssuer);
+ if (status === OcspCertStatus.Revoked) {
+ await markCertificateRevokedLocally(cert, revokedAt);
+ revokedCount += 1;
+ logger.info(
+ `digicert-revocation-sync: marked revoked from OCSP [caId=${caId}] [certId=${cert.id}] [serial=${cert.serialNumber}]`
+ );
+ }
+ } catch (err) {
+ logger.warn(err, `digicert-revocation-sync: OCSP check failed [caId=${caId}] [certId=${cert.id}]`);
+ }
+ }
+
+ logger.info(
+ `digicert-revocation-sync: OCSP check done [caId=${caId}] [checked=${replacedCertificates.length}] [revoked=${revokedCount}]`
+ );
+ };
+
const syncRevocationsForCertificateAuthority = async (
caRow: Awaited<ReturnType<typeof certificateAuthorityDAL.findWithAssociatedCa>>[number]
) => {
@@ -120,12 +194,7 @@ export const digicertRevocationSyncQueueFactory = ({
.filter((change) => change.status === "revoked")
.map((change) => change.order_id);
- if (upstreamRevokedOrderIds.length === 0) {
- logger.info(`digicert-revocation-sync: CA done [caId=${ca.id}] [upstreamRevoked=0] [reconciled=0]`);
- return;
- }
-
- let reconciledCount = 0;
+ const reconciledCertificateIds = new Set<string>();
for (let i = 0; i < upstreamRevokedOrderIds.length; i += ORDER_ID_LOOKUP_CHUNK_SIZE) {
const orderIdChunk = upstreamRevokedOrderIds.slice(i, i + ORDER_ID_LOOKUP_CHUNK_SIZE);
const certsToReconcile = await certificateDAL.findActiveDigiCertCertsByOrderIds(ca.id, orderIdChunk);
@@ -133,7 +202,7 @@ export const digicertRevocationSyncQueueFactory = ({
for (const cert of certsToReconcile) {
try {
await markCertificateRevokedLocally(cert);
- reconciledCount += 1;
+ reconciledCertificateIds.add(cert.id);
logger.info(
`digicert-revocation-sync: marked revoked [caId=${ca.id}] [certId=${cert.id}] [serial=${cert.serialNumber}]`
);
@@ -147,8 +216,10 @@ export const digicertRevocationSyncQueueFactory = ({
}
logger.info(
- `digicert-revocation-sync: CA done [caId=${ca.id}] [upstreamRevoked=${upstreamRevokedOrderIds.length}] [reconciled=${reconciledCount}]`
+ `digicert-revocation-sync: CA done [caId=${ca.id}] [upstreamRevoked=${upstreamRevokedOrderIds.length}] [reconciled=${reconciledCertificateIds.size}]`
);
+
+ await syncReplacedCertificateRevocations(ca.id, reconciledCertificateIds);
};
const init = () => {
diff --git a/backend/src/services/certificate-common/certificate-permission-fns.ts b/backend/src/services/certificate-common/certificate-permission-fns.ts
index ff052a0126..760ebb6d82 100644
--- a/backend/src/services/certificate-common/certificate-permission-fns.ts
+++ b/backend/src/services/certificate-common/certificate-permission-fns.ts
@@ -35,7 +35,7 @@ type TAssertCanEditCertificateDTO = {
tx?: Knex;
};
-export const assertCanEditCertificate = async ({
+const assertCertificatePermission = async ({
certificate,
actor,
actorId,
@@ -43,8 +43,15 @@ export const assertCanEditCertificate = async ({
actorOrgId,
permissionService,
resourceMetadataDAL,
- tx
-}: TAssertCanEditCertificateDTO): Promise<{
+ tx,
+ resourceAction,
+ projectAction,
+ extraSubjectFields
+}: TAssertCanEditCertificateDTO & {
+ resourceAction: ResourcePermissionCertificateActions;
+ projectAction: ProjectPermissionCertificateActions;
+ extraSubjectFields?: Record<string, string | undefined>;
+}): Promise<{
certMetadata: { key: string; value: string }[];
projectPermission?: MongoAbility;
}> => {
@@ -58,10 +65,7 @@ export const assertCanEditCertificate = async ({
actorAuthMethod,
actorOrgId
});
- ForbiddenError.from(permission).throwUnlessCan(
- ResourcePermissionCertificateActions.Edit,
- ResourcePermissionSub.Certificates
- );
+ ForbiddenError.from(permission).throwUnlessCan(resourceAction, ResourcePermissionSub.Certificates);
return { certMetadata: [] };
}
@@ -79,11 +83,12 @@ export const assertCanEditCertificate = async ({
});
ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionCertificateActions.Edit,
+ projectAction,
subject(ProjectPermissionSub.Certificates, {
commonName: certificate.commonName ?? undefined,
altNames: certificate.altNames?.split(",").map((s) => s.trim()),
serialNumber: certificate.serialNumber ?? undefined,
+ ...extraSubjectFields,
metadata: certMetadata
})
);
@@ -91,60 +96,29 @@ export const assertCanEditCertificate = async ({
return { certMetadata, projectPermission: permission };
};
-type TAssertCanRevokeCertificateDTO = Omit<TAssertCanEditCertificateDTO, "certificate"> & {
- certificate: TCertificateSubjectFields & { friendlyName?: string | null; status?: string | null };
-};
+export const assertCanEditCertificate = (dto: TAssertCanEditCertificateDTO) =>
+ assertCertificatePermission({
+ ...dto,
+ resourceAction: ResourcePermissionCertificateActions.Edit,
+ projectAction: ProjectPermissionCertificateActions.Edit
+ });
export const assertCanRevokeCertificate = async ({
certificate,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- permissionService,
- resourceMetadataDAL,
- tx
-}: TAssertCanRevokeCertificateDTO) => {
- if (certificate.applicationId) {
- const { permission } = await permissionService.getResourcePermission({
- actor,
- actorId,
- projectId: certificate.projectId,
- resourceType: ResourceType.CertificateApplication,
- resourceId: certificate.applicationId,
- actorAuthMethod,
- actorOrgId
- });
- ForbiddenError.from(permission).throwUnlessCan(
- ResourcePermissionCertificateActions.Delete,
- ResourcePermissionSub.Certificates
- );
- return;
- }
-
- const metadataRows = await resourceMetadataDAL.find({ certificateId: certificate.id }, { tx });
- const certMetadata = metadataRows.map(({ key, value }) => ({ key, value: value || "" }));
-
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- projectId: certificate.projectId,
- actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.CertificateManager
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionCertificateActions.Delete,
- subject(ProjectPermissionSub.Certificates, {
- commonName: certificate.commonName ?? undefined,
- altNames: certificate.altNames?.split(",").map((s) => s.trim()),
- serialNumber: certificate.serialNumber ?? undefined,
+ ...dto
+}: Omit<TAssertCanEditCertificateDTO, "certificate"> & {
+ certificate: TCertificateSubjectFields & { friendlyName?: string | null; status?: string | null };
+}) => {
+ await assertCertificatePermission({
+ ...dto,
+ certificate,
+ resourceAction: ResourcePermissionCertificateActions.Delete,
+ projectAction: ProjectPermissionCertificateActions.Delete,
+ extraSubjectFields: {
friendlyName: certificate.friendlyName ?? undefined,
- status: certificate.status ?? undefined,
- metadata: certMetadata
- })
- );
+ status: certificate.status ?? undefined
+ }
+ });
};
export const assertCanEditCertificateResult = ({
diff --git a/backend/src/services/certificate-common/external-metadata-schemas.ts b/backend/src/services/certificate-common/external-metadata-schemas.ts
index 3b8ce29d8c..87c487adfa 100644
--- a/backend/src/services/certificate-common/external-metadata-schemas.ts
+++ b/backend/src/services/certificate-common/external-metadata-schemas.ts
@@ -71,6 +71,10 @@ export const CertificateImportLinkageMap: Partial<Record<CaType, TCertificateImp
}
};
+export const CertificateReissueOrderSchemaMap: Partial<Record<CaType, z.ZodTypeAny>> = {
+ [CaType.DIGICERT]: DigiCertExternalMetadataSchema
+};
+
export const CA_TYPE_LABEL: Record<CaType, string> = {
[CaType.INTERNAL]: "Internal CA",
[CaType.ACME]: "ACME",
diff --git a/backend/src/services/certificate-request/certificate-request-service.test.ts b/backend/src/services/certificate-request/certificate-request-service.test.ts
index 6d816d7398..1acf0764fb 100644
--- a/backend/src/services/certificate-request/certificate-request-service.test.ts
+++ b/backend/src/services/certificate-request/certificate-request-service.test.ts
@@ -84,7 +84,8 @@ describe("CertificateRequestService", () => {
identityDAL: mockIdentityDAL as any,
certificateProfileDAL: mockCertificateProfileDAL as any,
certificateAuthorityDAL: mockCertificateAuthorityDAL as any,
- auditLogService: mockAuditLogService
+ auditLogService: mockAuditLogService,
+ digicertFns: { cancelReissue: vi.fn().mockResolvedValue(true) }
});
});
diff --git a/backend/src/services/certificate-request/certificate-request-service.ts b/backend/src/services/certificate-request/certificate-request-service.ts
index 584776d73a..4fb080eae1 100644
--- a/backend/src/services/certificate-request/certificate-request-service.ts
+++ b/backend/src/services/certificate-request/certificate-request-service.ts
@@ -34,6 +34,8 @@ import { TCertificateServiceFactory } from "@app/services/certificate/certificat
import { TPkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";
import { ActorAuthMethod, ActorType } from "../auth/auth-type";
+import { TDigiCertCertificateAuthorityFns } from "../certificate-authority/digicert/digicert-certificate-authority-fns";
+import { DigiCertCertificateRequestMetadataSchema } from "../certificate-authority/digicert/digicert-certificate-authority-schemas";
import { TIdentityDALFactory } from "../identity/identity-dal";
import { TResourceMetadataDALFactory } from "../resource-metadata/resource-metadata-dal";
import { TUserDALFactory } from "../user/user-dal";
@@ -62,6 +64,19 @@ type TCertificateRequestServiceFactoryDep = {
certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findById">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;
auditLogService: Pick<TAuditLogServiceFactory, "createCollapsedAuditLog">;
+ digicertFns: Pick<TDigiCertCertificateAuthorityFns, "cancelReissue">;
+};
+
+const getPendingDigiCertReissueOrderId = (metadata: string | null | undefined) => {
+ if (!metadata) return undefined;
+ try {
+ const parsed = DigiCertCertificateRequestMetadataSchema.safeParse(JSON.parse(metadata));
+ return parsed.success && parsed.data.digicert.previousCertificateId !== undefined
+ ? parsed.data.digicert.orderId
+ : undefined;
+ } catch {
+ return undefined;
+ }
};
export type TCertificateRequestServiceFactory = ReturnType<typeof certificateRequestServiceFactory>;
@@ -162,7 +177,8 @@ export const certificateRequestServiceFactory = ({
identityDAL,
certificateProfileDAL,
certificateAuthorityDAL,
- auditLogService
+ auditLogService,
+ digicertFns
}: TCertificateRequestServiceFactoryDep) => {
const $resolveApplicationName = async (applicationId?: string | null) => {
if (!applicationId) return null;
@@ -745,6 +761,11 @@ export const certificateRequestServiceFactory = ({
);
}
+ const reissueOrderId = getPendingDigiCertReissueOrderId(certificateRequest.metadata);
+ if (previousStatus === CertificateRequestStatus.PENDING_VALIDATION && certificateRequest.caId && reissueOrderId) {
+ await digicertFns.cancelReissue({ caId: certificateRequest.caId, orderId: reissueOrderId });
+ }
+
return {
certificateRequest: updated,
projectId: certificateRequest.projectId,
diff --git a/backend/src/services/certificate-v3/certificate-renewal-service.ts b/backend/src/services/certificate-v3/certificate-renewal-service.ts
index bbd0f50672..0be6871b19 100644
--- a/backend/src/services/certificate-v3/certificate-renewal-service.ts
+++ b/backend/src/services/certificate-v3/certificate-renewal-service.ts
@@ -20,7 +20,10 @@ import {
} from "@app/services/certificate-authority/certificate-authority-dal";
import { CaCapability, CaType } from "@app/services/certificate-authority/certificate-authority-enums";
import { assertCaInProfileProject } from "@app/services/certificate-authority/certificate-authority-fns";
-import { caSupportsCapability } from "@app/services/certificate-authority/certificate-authority-maps";
+import {
+ caSupportsCapability,
+ CERTIFICATE_AUTHORITIES_TYPE_MAP
+} from "@app/services/certificate-authority/certificate-authority-maps";
import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service";
import {
TProfileCustomExtension,
@@ -80,7 +83,7 @@ import {
validateCertificateRequestLicense,
validatePqcLicense
} from "../certificate-common/certificate-utils";
-import { DigiCertExternalMetadataSchema } from "../certificate-common/external-metadata-schemas";
+import { CertificateReissueOrderSchemaMap } from "../certificate-common/external-metadata-schemas";
import { TCertificateRequest } from "../certificate-policy/certificate-policy-types";
import { TCertificateRequestDALFactory } from "../certificate-request/certificate-request-dal";
import {
@@ -1134,24 +1137,24 @@ export const certificateRenewalServiceFactory = ({
tx
);
- if (
- externalConfiguration?.reissue &&
- !(caType && caSupportsCapability(caType, CaCapability.REISSUE_CERTIFICATES))
- ) {
- throw new BadRequestError({
- message: "Reissue is only available for DigiCert certificates."
- });
- }
- if (externalConfiguration?.reissue && attributes?.ttl) {
- throw new BadRequestError({ message: "Remove the TTL. It can't be set on a reissue." });
- }
- if (
- externalConfiguration?.reissue &&
- !DigiCertExternalMetadataSchema.safeParse(originalCert.externalMetadata).success
- ) {
- throw new BadRequestError({
- message: "This certificate has no DigiCert order to reissue. Place a new order instead."
- });
+ if (externalConfiguration?.reissue) {
+ if (!(caType && caSupportsCapability(caType, CaCapability.REISSUE_CERTIFICATES))) {
+ const reissuingCaNames = Object.values(CaType)
+ .filter((type) => caSupportsCapability(type, CaCapability.REISSUE_CERTIFICATES))
+ .map((type) => CERTIFICATE_AUTHORITIES_TYPE_MAP[type]);
+ throw new BadRequestError({
+ message: `Reissue is only available for certificates issued by these CAs: ${reissuingCaNames.join(", ")}.`
+ });
+ }
+ if (attributes?.ttl) {
+ throw new BadRequestError({ message: "Remove the TTL. It can't be set on a reissue." });
+ }
+ const reissueOrderSchema = CertificateReissueOrderSchemaMap[caType];
+ if (!reissueOrderSchema?.safeParse(originalCert.externalMetadata).success) {
+ throw new BadRequestError({
+ message: "This certificate has no order with its CA to reissue. Place a new order instead."
+ });
+ }
}
const { certificateRequest, replayedRequest, ttl, resolvedCustomExtensions } = $buildValidatedRenewalRequest({
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
index f668ec85fe..309a80f6fa 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
@@ -2609,6 +2609,52 @@ describe("CertificateV3Service", () => {
});
});
+ describe("DigiCert reissue", () => {
+ const setupRenewal = (ca: unknown) => {
+ vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert);
+ vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);
+ vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
+ vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(ca as any);
+ vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
+ vi.mocked(mockCertificatePolicyService.validateRequestAgainstPolicy).mockReturnValue({
+ isValid: true,
+ errors: [],
+ warnings: []
+ } as any);
+ };
+
+ it("rejects a reissue for a certificate that a DigiCert CA did not issue", async () => {
+ setupRenewal(mockCA);
+
+ await expect(
+ service.renewCertificate({
+ certificateId: "cert-123",
+ externalConfiguration: { reissue: true },
+ ...mockActor
+ })
+ ).rejects.toThrow("Reissue is only available for certificates issued by these CAs: DigiCert.");
+ expect(mockCertificateIssuanceQueue.queueCertificateIssuance).not.toHaveBeenCalled();
+ });
+
+ it("rejects a TTL on a DigiCert reissue", async () => {
+ setupRenewal({
+ ...mockCA,
+ internalCa: undefined,
+ externalCa: { id: "ext-ca-1", type: CaType.DIGICERT, configuration: {} }
+ });
+
+ await expect(
+ service.renewCertificate({
+ certificateId: "cert-123",
+ externalConfiguration: { reissue: true },
+ attributes: { ttl: "30d" },
+ ...mockActor
+ })
+ ).rejects.toThrow("Remove the TTL. It can't be set on a reissue.");
+ expect(mockCertificateIssuanceQueue.queueCertificateIssuance).not.toHaveBeenCalled();
+ });
+ });
+
it("should successfully renew eligible certificate", async () => {
// Three reads: the pre-transaction licence check, the in-transaction load, then the renewed row.
vi.mocked(mockCertificateDAL.findById)
diff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.ts
index ae14d20a1d..62c3195d5a 100644
--- a/backend/src/services/certificate/certificate-dal.ts
+++ b/backend/src/services/certificate/certificate-dal.ts
@@ -130,6 +130,29 @@ export const certificateDALFactory = (db: TDbClient) => {
}
};
+ const findActiveDigiCertCertsReplacedOnOrder = async (caId: string) => {
+ try {
+ const certs = await db
+ .replicaNode()(TableName.Certificate)
+ .where({ caId, status: CertStatus.ACTIVE })
+ .where("notAfter", ">", new Date())
+ .whereRaw(`"externalMetadata"->>'type' = ?`, ["digicert"])
+ .whereExists((qb) => {
+ void qb
+ .select(db.raw("1"))
+ .from({ newer: TableName.Certificate })
+ .whereRaw(`newer."caId" = ${TableName.Certificate}."caId"`)
+ .whereRaw(`newer."externalMetadata"->>'orderId' = ${TableName.Certificate}."externalMetadata"->>'orderId'`)
+ .whereRaw(`newer."createdAt" > ${TableName.Certificate}."createdAt"`);
+ })
+ .select("id", "commonName", "serialNumber", "projectId", "applicationId");
+
+ return certs;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find active DigiCert certs replaced on their order" });
+ }
+ };
+
type TInventoryFilterParams = {
friendlyName?: string;
commonName?: string;
@@ -1463,6 +1486,7 @@ export const certificateDALFactory = (db: TDbClient) => {
findLatestActiveCertForSubscriber,
findAllActiveCertsForSubscriber,
findActiveDigiCertCertsByOrderIds,
+ findActiveDigiCertCertsReplacedOnOrder,
findExpiredSyncedCertificates,
findByThumbprintInOrg,
findActiveCertificatesByIds,
diff --git a/backend/src/services/certificate/certificate-ocsp-client.test.ts b/backend/src/services/certificate/certificate-ocsp-client.test.ts
new file mode 100644
index 0000000000..f8c7de531c
--- /dev/null
+++ b/backend/src/services/certificate/certificate-ocsp-client.test.ts
@@ -0,0 +1,124 @@
+import { webcrypto } from "node:crypto";
+
+import * as x509 from "@peculiar/x509";
+import * as pkijs from "pkijs";
+
+import { OcspCertStatus } from "@app/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-enums";
+import {
+ buildSignedOcspResponse,
+ parseOcspRequest
+} from "@app/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-fns";
+import { TOcspCertStatus } from "@app/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-types";
+import { asNonSharedBuffer } from "@app/lib/fn";
+import { TCaSigner } from "@app/services/certificate-authority/ca-signer";
+
+import { getCertificateOcspStatus } from "./certificate-ocsp-client";
+
+const post = vi.fn<(url: string, body: Buffer) => Promise<{ data: ArrayBuffer }>>();
+vi.mock("@app/lib/validator/safe-request", () => ({
+ safeRequest: { post: (url: string, body: Buffer) => post(url, body) }
+}));
+
+const RSA_ALG: RsaHashedKeyGenParams = {
+ name: "RSASSA-PKCS1-v1_5",
+ hash: "SHA-256",
+ publicExponent: new Uint8Array([1, 0, 1]),
+ modulusLength: 2048
+};
+const OCSP_URL = "http://ocsp.example.com";
+const REVOKED_AT = new Date("2026-10-28T09:02:41.000Z");
+
+const createCa = async (name: string) => {
+ const keys = (await webcrypto.subtle.generateKey(RSA_ALG, true, ["sign", "verify"])) as CryptoKeyPair;
+ const certificate = await x509.X509CertificateGenerator.createSelfSigned({
+ serialNumber: "01",
+ name,
+ notBefore: new Date(Date.now() - 86_400_000),
+ notAfter: new Date(Date.now() + 86_400_000),
+ signingAlgorithm: RSA_ALG,
+ keys,
+ extensions: [new x509.BasicConstraintsExtension(true, 2, true)]
+ });
+ const signer = {
+ caPublicKey: keys.publicKey,
+ signingAlgorithm: RSA_ALG,
+ signTbs: (tbs: Buffer) => webcrypto.subtle.sign(RSA_ALG, keys.privateKey, asNonSharedBuffer(tbs))
+ } as unknown as TCaSigner;
+ return { keys, certificate, signer };
+};
+
+let issuingCa: Awaited<ReturnType<typeof createCa>>;
+let otherCa: Awaited<ReturnType<typeof createCa>>;
+let leafCertificate: x509.X509Certificate;
+
+const respondWith = (status: TOcspCertStatus, responder = issuingCa) =>
+ post.mockImplementation(async (_url: string, body: Buffer) => {
+ const parsed = parseOcspRequest(body);
+ const data = await buildSignedOcspResponse({
+ signer: responder.signer,
+ caCertificate: responder.certificate,
+ statuses: parsed!.entries.map((entry) => ({ entry, status })),
+ thisUpdate: new Date(),
+ nextUpdate: new Date(Date.now() + 3_600_000)
+ });
+ return { data: new Uint8Array(data).buffer };
+ });
+
+beforeAll(async () => {
+ x509.cryptoProvider.set(webcrypto as unknown as Crypto);
+ pkijs.setEngine("test", new pkijs.CryptoEngine({ crypto: webcrypto as unknown as Crypto }));
+
+ issuingCa = await createCa("CN=Example Issuing CA");
+ otherCa = await createCa("CN=Example Other CA");
+
+ const leafKeys = (await webcrypto.subtle.generateKey(RSA_ALG, true, ["sign", "verify"])) as CryptoKeyPair;
+ leafCertificate = await x509.X509CertificateGenerator.create({
+ serialNumber: "4f2a9c1b33",
+ subject: "CN=example.com",
+ issuer: issuingCa.certificate.subject,
+ notBefore: new Date(Date.now() - 3_600_000),
+ notAfter: new Date(Date.now() + 3_600_000),
+ signingKey: issuingCa.keys.privateKey,
+ publicKey: leafKeys.publicKey,
+ signingAlgorithm: RSA_ALG,
+ extensions: [new x509.AuthorityInfoAccessExtension({ ocsp: [new x509.GeneralName("url", OCSP_URL)] })]
+ });
+});
+
+describe("getCertificateOcspStatus", () => {
+ beforeEach(() => {
+ post.mockReset();
+ });
+
+ test("reports a good certificate", async () => {
+ respondWith({ kind: OcspCertStatus.Good });
+
+ await expect(
+ getCertificateOcspStatus({ certificate: leafCertificate, issuer: issuingCa.certificate })
+ ).resolves.toEqual({ status: OcspCertStatus.Good });
+ expect(post).toHaveBeenCalledWith(OCSP_URL, expect.any(Buffer), expect.any(Object));
+ });
+
+ test("reports a revoked certificate with its revocation time", async () => {
+ respondWith({ kind: OcspCertStatus.Revoked, revokedAt: REVOKED_AT });
+
+ await expect(
+ getCertificateOcspStatus({ certificate: leafCertificate, issuer: issuingCa.certificate })
+ ).resolves.toEqual({ status: OcspCertStatus.Revoked, revokedAt: REVOKED_AT });
+ });
+
+ test("rejects a response signed by a CA other than the issuer", async () => {
+ respondWith({ kind: OcspCertStatus.Revoked, revokedAt: REVOKED_AT }, otherCa);
+
+ await expect(
+ getCertificateOcspStatus({ certificate: leafCertificate, issuer: issuingCa.certificate })
+ ).rejects.toThrow("failed signature verification");
+ });
+
+ test("refuses a certificate without an OCSP responder URL", async () => {
+ await expect(
+ getCertificateOcspStatus({ certificate: issuingCa.certificate, issuer: issuingCa.certificate })
+ ).rejects.toThrow("has no OCSP responder URL");
+ expect(post).not.toHaveBeenCalled();
+ });
+});
diff --git a/backend/src/services/certificate/certificate-ocsp-client.ts b/backend/src/services/certificate/certificate-ocsp-client.ts
new file mode 100644
index 0000000000..b220eeae8d
--- /dev/null
+++ b/backend/src/services/certificate/certificate-ocsp-client.ts
@@ -0,0 +1,97 @@
+import * as x509 from "@peculiar/x509";
+import * as asn1js from "asn1js";
+import * as pkijs from "pkijs";
+
+import {
+ OCSP_REQUEST_CONTENT_TYPE,
+ OcspCertStatus,
+ OcspResponseStatus
+} from "@app/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-enums";
+import { BadRequestError } from "@app/lib/errors";
+import { safeRequest } from "@app/lib/validator/safe-request";
+
+const OCSP_CLIENT_TIMEOUT_MS = 10_000;
+const PKIJS_CERT_STATUS: Record<number, OcspCertStatus> = {
+ 0: OcspCertStatus.Good,
+ 1: OcspCertStatus.Revoked,
+ 2: OcspCertStatus.Unknown
+};
+
+const toPkijsCertificate = (cert: x509.X509Certificate) =>
+ pkijs.Certificate.fromBER(new Uint8Array(cert.rawData).buffer);
+
+export const getCertificateOcspUrl = (cert: x509.X509Certificate) => {
+ const authorityInfoAccess = cert.getExtension(x509.AuthorityInfoAccessExtension);
+ return authorityInfoAccess?.ocsp.find((name) => name.type === "url")?.value;
+};
+
+const getRevocationTime = (basicResponse: pkijs.BasicOCSPResponse, certificate: pkijs.Certificate) => {
+ const serialHex = Buffer.from(certificate.serialNumber.valueBlock.valueHexView).toString("hex");
+ const singleResponse = basicResponse.tbsResponseData.responses.find(
+ (response) => Buffer.from(response.certID.serialNumber.valueBlock.valueHexView).toString("hex") === serialHex
+ );
+ const revokedInfo = singleResponse?.certStatus as asn1js.Constructed | undefined;
+ const revocationTime = revokedInfo?.valueBlock?.value?.[0];
+ return revocationTime instanceof asn1js.GeneralizedTime ? revocationTime.toDate() : undefined;
+};
+
+export const getCertificateOcspStatus = async ({
+ certificate,
+ issuer
+}: {
+ certificate: x509.X509Certificate;
+ issuer: x509.X509Certificate;
+}): Promise<{ status: OcspCertStatus; revokedAt?: Date }> => {
+ const ocspUrl = getCertificateOcspUrl(certificate);
+ if (!ocspUrl) {
+ throw new BadRequestError({ message: `Certificate ${certificate.serialNumber} has no OCSP responder URL` });
+ }
+
+ const pkijsCertificate = toPkijsCertificate(certificate);
+ const pkijsIssuer = toPkijsCertificate(issuer);
+
+ const ocspRequest = new pkijs.OCSPRequest();
+ await ocspRequest.createForCertificate(pkijsCertificate, { hashAlgorithm: "SHA-1", issuerCertificate: pkijsIssuer });
+
+ const { data } = await safeRequest.post<ArrayBuffer>(ocspUrl, Buffer.from(ocspRequest.toSchema(true).toBER(false)), {
+ headers: { "Content-Type": OCSP_REQUEST_CONTENT_TYPE },
+ responseType: "arraybuffer",
+ timeout: OCSP_CLIENT_TIMEOUT_MS
+ });
+
+ const ocspResponse = pkijs.OCSPResponse.fromBER(new Uint8Array(data).buffer);
+ const responseStatus = ocspResponse.responseStatus.valueBlock.valueDec;
+ if (responseStatus !== OcspResponseStatus.Successful || !ocspResponse.responseBytes) {
+ throw new BadRequestError({ message: `OCSP responder ${ocspUrl} returned status ${responseStatus}` });
+ }
+
+ const basicResponse = pkijs.BasicOCSPResponse.fromBER(
+ ocspResponse.responseBytes.response.valueBlock.valueHexView.slice().buffer
+ );
+ const isSignedByIssuer = await pkijs
+ .getCrypto(true)
+ .verifyWithPublicKey(
+ new Uint8Array(basicResponse.tbsResponseData.tbsView),
+ basicResponse.signature,
+ pkijsIssuer.subjectPublicKeyInfo,
+ basicResponse.signatureAlgorithm
+ )
+ .catch(() => false);
+ const isSignatureValid =
+ isSignedByIssuer ||
+ (Boolean(basicResponse.certs?.length) &&
+ (await basicResponse.verify({ trustedCerts: [pkijsIssuer] }).catch(() => false)));
+ if (!isSignatureValid) {
+ throw new BadRequestError({ message: `OCSP response from ${ocspUrl} failed signature verification` });
+ }
+
+ const { isForCertificate, status } = await basicResponse.getCertificateStatus(pkijsCertificate, pkijsIssuer);
+ if (!isForCertificate) {
+ throw new BadRequestError({ message: `OCSP response from ${ocspUrl} does not cover the requested certificate` });
+ }
+
+ const certStatus = PKIJS_CERT_STATUS[status] ?? OcspCertStatus.Unknown;
+ return certStatus === OcspCertStatus.Revoked
+ ? { status: certStatus, revokedAt: getRevocationTime(basicResponse, pkijsCertificate) }
+ : { status: certStatus };
+};
diff --git a/docs/documentation/platform/pki/applications/certificate-renewal.mdx b/docs/documentation/platform/pki/applications/certificate-renewal.mdx
index 389cd8dc57..746b603af6 100644
--- a/docs/documentation/platform/pki/applications/certificate-renewal.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-renewal.mdx
@@ -77,6 +77,8 @@ Reuse is available for certificates issued with an Infisical-managed key pair. A
Renewing a certificate as it stands needs only permission to issue from its certificate profile. Changing any of the properties above additionally needs **Edit** on certificates, so a role scoped to issuance alone can keep certificates current without being able to alter what they contain.
+A [DigiCert reissue](#reissuing-a-digicert-certificate) that removes or changes a name also needs permission to revoke the certificate, because DigiCert revokes the previous one.
+
### Renewing from a signing request
When you supply a CSR, that request is the source of truth for the subject and the key, so there are no separate fields for them. The validity, the basic constraints and the custom extensions are set alongside it, and custom extensions keep their current values unless you change them.
@@ -85,12 +87,14 @@ Sending a property the CSR already carries is rejected rather than quietly ignor
## Reissuing a DigiCert certificate
-If a [DigiCert CA](/documentation/platform/pki/ca/digicert-direct) issued the certificate, you can reissue it on the same DigiCert order instead of placing a new order. On the first step of the renewal, select **Reissue the existing order** under **DigiCert order**.
+If a [DigiCert CA](/documentation/platform/pki/ca/digicert-direct) issued the certificate, you can reissue it on the same DigiCert order instead of placing a new order. A reissue uses the order you already paid for, for example to replace an exposed key or to change the names on the certificate. On the first step of the renewal, select **Reissue the existing order** under **DigiCert order**.
+
+A reissue requests the same validity as the current certificate, capped at 199 days and at the end of the order, so the **Validity (TTL)** field is read-only and the API rejects `ttl`. The profile's policy still applies to it, so a validity the policy doesn't allow is flagged before you submit. If you need a certificate that lasts longer than the order, select **Place a new order** instead.
-If you add a name that DigiCert hasn't validated yet, validate it in DigiCert CertCentral within 24 hours, or the reissue fails.
+If you add a name that DigiCert hasn't validated yet, validate it in DigiCert CertCentral within 24 hours. Otherwise the reissue is canceled and the request fails.
<Warning>
- If the reissue removes or changes a name, DigiCert revokes the previous certificate within 72 hours.
+ If the reissue removes or changes a name, DigiCert revokes the previous certificate and any earlier copies on the order within 72 hours, so you also need permission to revoke the certificate.
</Warning>
## Renewing a certificate
@@ -157,7 +161,7 @@ If you add a name that DigiCert hasn't validated yet, validate it in DigiCert Ce
The renewal produces a new certificate with its own serial number, linked to the one it replaced.
- The previous certificate reports a status of **Renewed** rather than **Active**, and links to its replacement under **Renewed by**. The replacement links back under **Renewed from**.
-- Unless a [DigiCert reissue](#reissuing-a-digicert-certificate) removed or changed a name, the previous certificate stays valid until its own expiry, so you can roll over on your own schedule (it can't be renewed a second time)
+- The previous certificate stays valid until its own expiry, so you can roll over on your own schedule. The exception is a [DigiCert reissue](#reissuing-a-digicert-certificate) that removes or changes a name: DigiCert revokes the previous certificate within 72 hours. The previous certificate can't be renewed a second time.
- Because it's no longer the current certificate, it drops out of the active count on the dashboard and out of expiry alerts. Filter the inventory by the **Renewed** status, or open the **Renewed** view, to list every certificate that has been superseded.
- Metadata carries over to the renewed certificate.
- Certificate syncs attached to the certificate move to the renewed one and push it to their destinations.
@@ -169,7 +173,7 @@ The renewal produces a new certificate with its own serial number, linked to the
because it has to stay shorter than the certificate it applies to.
</Note>
-Deploy the renewed certificate before the previous one expires. Renewing doesn't revoke the certificate it replaces, so if the old one was compromised, [revoke it](/documentation/platform/pki/applications/certificates) explicitly.
+Deploy the renewed certificate before the previous one expires. Renewing doesn't revoke the certificate it replaces, so if the old one was compromised, [revoke it](/documentation/platform/pki/applications/certificates) explicitly. The exception is a [DigiCert reissue](#reissuing-a-digicert-certificate) that removes or changes a name, where DigiCert revokes the previous certificate within 72 hours.
## FAQ
diff --git a/docs/documentation/platform/pki/ca/digicert-direct.mdx b/docs/documentation/platform/pki/ca/digicert-direct.mdx
index 7708ff3b5c..4def3f6120 100644
--- a/docs/documentation/platform/pki/ca/digicert-direct.mdx
+++ b/docs/documentation/platform/pki/ca/digicert-direct.mdx
@@ -116,11 +116,17 @@ When you request a certificate through a DigiCert CertCentral CA, the request mo
<Accordion title="What happens when I revoke a DigiCert-issued certificate in Infisical?">
Revoking the certificate in Infisical immediately marks it `Revoked` in the local inventory
**and** asks DigiCert CertCentral to revoke that certificate only, so other certificates on the
- same order stay valid. If a newer certificate has already replaced it on the order, for example
- after a reissue made in CertCentral, revoke it in DigiCert CertCentral instead.
+ same order stay valid. If the certificate was issued before individual DigiCert certificates were
+ tracked and a newer certificate has since replaced it on the order, the revocation is refused, so
+ revoke it in DigiCert CertCentral instead.
Depending on your CertCentral account's revocation policy, DigiCert may queue that request for
administrator approval before the certificate is actually revoked on their side.
</Accordion>
+ <Accordion title="What happens when a certificate is revoked in DigiCert CertCentral?">
+ It's marked `Revoked` in the inventory within a day. That includes a certificate replaced by a
+ [reissue](/documentation/platform/pki/applications/certificate-renewal#reissuing-a-digicert-certificate),
+ which DigiCert revokes within 72 hours when the reissue removes or changes a name.
+ </Accordion>
</AccordionGroup>
## What's next
diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
index beabb7af0e..39ce5a6eb6 100644
--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
@@ -420,7 +420,8 @@ const Page = () => {
onClick={() =>
handlePopUpOpen("renewCertificate", {
certificateId: certificate.id,
- commonName: displayName
+ commonName: displayName,
+ canRevoke: canDeleteCertificate
})
}
>
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
index 600850dc03..f9d5e04800 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx
@@ -2,11 +2,22 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useNavigate } from "@tanstack/react-router";
-import { RefreshCw } from "lucide-react";
+import { RefreshCw, TriangleAlertIcon } from "lucide-react";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import {
+ Alert,
+ AlertDescription,
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertTitle,
Field,
FieldContent,
FieldDescription,
@@ -53,6 +64,7 @@ import { buildPolicyRules, withRequiredRows } from "./certificatePolicyGuidance"
import {
buildRenewalFormDefaults,
buildRenewalRequestAttributes,
+ getRemovedCertificateNames,
unionUsageOptions
} from "./certificateRenewalUtils";
import { isExternalTemplateCa, rowErrorsOf } from "./certificateUtils";
@@ -274,6 +286,9 @@ const ChoiceCards = <T extends string>({
</Field>
);
+const REISSUE_VALIDITY_DESCRIPTION =
+ "Same as the current certificate. DigiCert caps it at 199 days and at the end of the order.";
+
enum DigiCertOrderChoice {
NewOrder = "new-order",
Reissue = "reissue"
@@ -320,7 +335,8 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
const navigate = useNavigate();
const isOpen = Boolean(popUp?.renewCertificate?.isOpen);
- const { certificateId } = (popUp?.renewCertificate?.data as { certificateId?: string }) ?? {};
+ const { certificateId, canRevoke = true } =
+ (popUp?.renewCertificate?.data as { certificateId?: string; canRevoke?: boolean }) ?? {};
const { data: certificateData } = useGetCertificateById(
isOpen && certificateId ? certificateId : ""
@@ -405,6 +421,24 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
CaCapability.REISSUE_CERTIFICATES
);
const isReissuing = isReissueAvailable && watch("reissue");
+ const removedNames =
+ isReissuing && certificate && keySource !== CertificateRenewalKeySource.Csr
+ ? getRemovedCertificateNames({
+ certificate,
+ formData: {
+ subjectAttributes: watch("subjectAttributes"),
+ subjectAltNames: watch("subjectAltNames")
+ },
+ constraints
+ })
+ : [];
+ const nameRemovalError =
+ removedNames.length && !canRevoke
+ ? "Removing or changing a name on a reissue revokes the current certificate, and you don't have permission to revoke it."
+ : undefined;
+ const [pendingNameRemovalRenewal, setPendingNameRemovalRenewal] =
+ useState<RenewalFormData | null>(null);
+ const [isConfirmingNameRemoval, setIsConfirmingNameRemoval] = useState(false);
const watchedIsCA = watch("basicConstraints.isCA") || false;
const sanTypesInForm = (watch("subjectAltNames") ?? []).map((san) => san.type).join(",");
const watchedKeyUsages = Object.keys(watch("keyUsages") ?? {})
@@ -537,7 +571,7 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
isSubjectSectionShown: constraints.shouldShowSubjectSection,
isSanSectionShown: constraints.shouldShowSanSection,
isSubjectEvaluated: keySource !== CertificateRenewalKeySource.Csr,
- isValidityEvaluated: !isExternalTemplateProfile && !isReissuing,
+ isValidityEvaluated: !isExternalTemplateProfile,
resetKey: certificate?.id
});
@@ -548,6 +582,7 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
validateStep: async (fields) => {
// Leaving a step reveals the findings on its own fields; entering it must stay quiet.
policy.reveal(fields);
+ if (nameRemovalError && fields.includes("subjectAltNames")) return false;
if (!(await trigger(fields as (keyof RenewalFormData)[]))) return false;
return policy.findBlockedFields(fields).length === 0;
}
@@ -642,23 +677,9 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
setStep(0);
};
- const onFormSubmit = async (formData: RenewalFormData) => {
+ const submitRenewal = async (formData: RenewalFormData) => {
if (!certificateId) return;
- // Reachable when a step was skipped or its values changed after it was cleared. Reveal the
- // whole offending step, so the finding is visible wherever in it the requester lands.
- const [blockedField] = policy.findBlockedFields(stepKeys.flatMap((key) => STEP_FIELDS[key]));
- if (blockedField) {
- const blockedStep = stepKeys.findIndex((key) => STEP_FIELDS[key].includes(blockedField));
- policy.reveal(blockedStep >= 0 ? STEP_FIELDS[stepKeys[blockedStep]] : [blockedField]);
- if (blockedStep >= 0) setStep(blockedStep);
- createNotification({
- text: "Resolve the policy violations before renewing this certificate.",
- type: "error"
- });
- return;
- }
-
const attributes = buildRenewalRequestAttributes({
formData,
constraints,
@@ -694,6 +715,48 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
}
};
+ const onFormSubmit = async (formData: RenewalFormData) => {
+ if (!certificateId) return;
+
+ // Reachable when a step was skipped or its values changed after it was cleared. Reveal the
+ // whole offending step, so the finding is visible wherever in it the requester lands.
+ const [blockedField] = policy.findBlockedFields(stepKeys.flatMap((key) => STEP_FIELDS[key]));
+ if (blockedField) {
+ const blockedStep = stepKeys.findIndex((key) => STEP_FIELDS[key].includes(blockedField));
+ policy.reveal(blockedStep >= 0 ? STEP_FIELDS[stepKeys[blockedStep]] : [blockedField]);
+ if (blockedStep >= 0) setStep(blockedStep);
+ createNotification({
+ text: "Resolve the policy violations before renewing this certificate.",
+ type: "error"
+ });
+ return;
+ }
+
+ if (nameRemovalError) {
+ setStep(stepKeys.indexOf("subject"));
+ createNotification({ text: nameRemovalError, type: "error" });
+ return;
+ }
+
+ if (removedNames.length) {
+ setPendingNameRemovalRenewal(formData);
+ return;
+ }
+
+ await submitRenewal(formData);
+ };
+
+ const confirmNameRemoval = async () => {
+ if (!pendingNameRemovalRenewal) return;
+ setIsConfirmingNameRemoval(true);
+ try {
+ await submitRenewal(pendingNameRemovalRenewal);
+ } finally {
+ setIsConfirmingNameRemoval(false);
+ setPendingNameRemovalRenewal(null);
+ }
+ };
+
const keySourceOptions = useMemo(
() => [
{
@@ -763,7 +826,7 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
value: DigiCertOrderChoice.Reissue,
label: "Reissue the existing order",
description:
- "Issues the certificate on the same DigiCert order. Removing or changing a name revokes the current certificate within 72 hours."
+ "Issues the certificate on the same DigiCert order, so it can't outlast the order. For longer coverage, place a new order. Removing or changing a name revokes the current certificate and any earlier copies on the order within 72 hours."
}
]}
/>
@@ -812,15 +875,15 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
</Field>
)}
/>
- {!isReissuing && (
- <ValidityField
- control={control}
- label="Validity (TTL)"
- hint={policy.ttlHint}
- policyError={policy.ttlError}
- revealPolicyError={policy.isRevealed("ttl")}
- />
- )}
+ <ValidityField
+ control={control}
+ label="Validity (TTL)"
+ isReadOnly={isReissuing}
+ description={isReissuing ? REISSUE_VALIDITY_DESCRIPTION : undefined}
+ hint={policy.ttlHint}
+ policyError={policy.ttlError}
+ revealPolicyError={policy.isRevealed("ttl")}
+ />
</div>
)}
@@ -831,6 +894,7 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
control={control}
allowedAttributeTypes={selectableSubjectAttributeTypes}
error={
+ (!constraints.shouldShowSanSection && nameRemovalError) ||
(formState.errors as { subjectAttributes?: { message?: string } }).subjectAttributes
?.message
}
@@ -847,6 +911,7 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
control={control}
allowedSanTypes={selectableSanTypes}
error={
+ nameRemovalError ??
(formState.errors as { subjectAltNames?: { message?: string } }).subjectAltNames
?.message
}
@@ -858,6 +923,17 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
revealPolicyErrors={policy.isRevealed("subjectAltNames")}
/>
)}
+ {removedNames.length > 0 && !nameRemovalError && (
+ <Alert variant="warning">
+ <TriangleAlertIcon />
+ <AlertTitle>DigiCert will revoke the current certificate</AlertTitle>
+ <AlertDescription>
+ This reissue removes {removedNames.join(", ")}. Once the new certificate is issued,
+ DigiCert revokes the current certificate and any earlier reissues and duplicates on
+ this order within 72 hours.
+ </AlertDescription>
+ </Alert>
+ )}
<IssuerModifiedNotice fields={subjectIssuerChanges} />
</div>
)}
@@ -877,12 +953,17 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
{currentStepKey === "options" && (
<div className="space-y-4">
- {!isExternalTemplateProfile && !isReissuing && (
+ {!isExternalTemplateProfile && (
<ValidityField
control={control}
className="mb-4"
label="Validity (TTL)"
- description="The renewed certificate is valid for this long, starting now."
+ isReadOnly={isReissuing}
+ description={
+ isReissuing
+ ? REISSUE_VALIDITY_DESCRIPTION
+ : "The renewed certificate is valid for this long, starting now."
+ }
hint={policy.ttlHint}
policyError={policy.ttlError}
revealPolicyError={policy.isRevealed("ttl")}
@@ -947,6 +1028,32 @@ export const CertificateRenewalModal = ({ popUp, applicationName, handlePopUpTog
<IssuerModifiedNotice fields={optionsIssuerChanges} />
</div>
)}
+ <AlertDialog
+ open={pendingNameRemovalRenewal !== null}
+ onOpenChange={(open) => {
+ if (!open && !isConfirmingNameRemoval) setPendingNameRemovalRenewal(null);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Reissue without {removedNames.join(", ")}?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Once the new certificate is issued, DigiCert revokes the current certificate and any
+ earlier reissues and duplicates on this order within 72 hours.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel isDisabled={isConfirmingNameRemoval}>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="danger"
+ isDisabled={isConfirmingNameRemoval}
+ onClick={confirmNameRemoval}
+ >
+ Reissue Certificate
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</CertificateWizardSheet>
);
};
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx
index 52eb7db319..5b3df6ee17 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx
@@ -135,6 +135,7 @@ type Props = {
renewalError?: string;
renewedFromCertificateId?: string;
renewedByCertificateId?: string;
+ canRevoke?: boolean;
}
) => void;
externalFilter?: {
@@ -1247,7 +1248,8 @@ export const CertificatesTable = ({
e.stopPropagation();
handlePopUpOpen("renewCertificate", {
certificateId: certificate.id,
- commonName: certificate.commonName
+ commonName: certificate.commonName,
+ canRevoke: canDeleteCertificate
});
}}
>
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/ValidityField.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/ValidityField.tsx
index 080f43724f..bab7a1c39a 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/ValidityField.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/ValidityField.tsx
@@ -17,6 +17,7 @@ type Props = {
policyError?: string;
/** Policy findings stay hidden until the requester tries to leave the step. */
revealPolicyError?: boolean;
+ isReadOnly?: boolean;
};
/**
@@ -30,7 +31,8 @@ export const ValidityField = ({
className,
hint,
policyError,
- revealPolicyError
+ revealPolicyError,
+ isReadOnly
}: Props) => (
<Controller
control={control}
@@ -43,7 +45,12 @@ export const ValidityField = ({
<FieldLabel>
{label} <span className="text-danger">*</span>
</FieldLabel>
- <Input {...field} placeholder="30d, 1y, 8760h" isError={Boolean(shownError)} />
+ <Input
+ {...field}
+ readOnly={isReadOnly}
+ placeholder="30d, 1y, 8760h"
+ isError={Boolean(shownError)}
+ />
{description && <FieldDescription>{description}</FieldDescription>}
{shownError && <PolicyRowMessage isError lines={[shownError]} />}
{!shownError && hint && <PolicyRowMessage lines={hint} />}
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.test.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.test.ts
index 4178034e63..5f7f93fe20 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.test.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.test.ts
@@ -1,8 +1,11 @@
import { describe, expect, it } from "vitest";
-import { CertSubjectAlternativeNameType } from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
+import {
+ CertSubjectAlternativeNameType,
+ CertSubjectAttributeType
+} from "@app/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/shared/certificate-constants";
-import { buildRenewalFormDefaults } from "./certificateRenewalUtils";
+import { buildRenewalFormDefaults, getRemovedCertificateNames } from "./certificateRenewalUtils";
const certificate = {
id: "cert-1",
@@ -68,3 +71,58 @@ describe("buildRenewalFormDefaults", () => {
expect(defaults.signatureAlgorithm).toBe("RSA-SHA384");
});
});
+
+describe("getRemovedCertificateNames", () => {
+ const reissuedCertificate = {
+ commonName: "example.com",
+ altNames: "example.com,www.example.com"
+ };
+ const shownSections = { shouldShowSubjectSection: true, shouldShowSanSection: true };
+ const formWith = (commonName: string, altNames: string[]) => ({
+ subjectAttributes: [{ type: CertSubjectAttributeType.COMMON_NAME, value: commonName }],
+ subjectAltNames: altNames.map((value) => ({
+ type: CertSubjectAlternativeNameType.DNS_NAME,
+ value
+ }))
+ });
+
+ it("lists nothing when every name is kept, ignoring case and order", () => {
+ expect(
+ getRemovedCertificateNames({
+ certificate: reissuedCertificate,
+ formData: formWith("Example.com", ["new.example.com", "WWW.example.com", "example.com"]),
+ constraints: shownSections
+ })
+ ).toEqual([]);
+ });
+
+ it("lists an alternative name that is dropped", () => {
+ expect(
+ getRemovedCertificateNames({
+ certificate: reissuedCertificate,
+ formData: formWith("example.com", ["example.com"]),
+ constraints: shownSections
+ })
+ ).toEqual(["www.example.com"]);
+ });
+
+ it("lists the common name when it changes", () => {
+ expect(
+ getRemovedCertificateNames({
+ certificate: { commonName: "example.com", altNames: "www.example.com" },
+ formData: formWith("other.example.com", ["www.example.com"]),
+ constraints: shownSections
+ })
+ ).toEqual(["example.com"]);
+ });
+
+ it("keeps the current names of a section the policy hides", () => {
+ expect(
+ getRemovedCertificateNames({
+ certificate: reissuedCertificate,
+ formData: formWith("example.com", []),
+ constraints: { shouldShowSubjectSection: true, shouldShowSanSection: false }
+ })
+ ).toEqual([]);
+ });
+});
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts
index 104d0351e0..471cf1cbb2 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/certificateRenewalUtils.ts
@@ -264,3 +264,30 @@ export const buildRenewalRequestAttributes = ({
return attributes;
};
+
+export const getRemovedCertificateNames = ({
+ certificate,
+ formData,
+ constraints
+}: {
+ certificate: Pick<TCertificate, "commonName" | "altNames">;
+ formData: Pick<RenewalFormData, "subjectAttributes" | "subjectAltNames">;
+ constraints: Pick<TemplateConstraints, "shouldShowSubjectSection" | "shouldShowSanSection">;
+}): string[] => {
+ const normalize = (names: (string | null | undefined)[]) =>
+ names.map((name) => name?.trim().toLowerCase()).filter((name): name is string => Boolean(name));
+ const originalAltNames = (certificate.altNames ?? "").split(",");
+ const requestedNames = new Set(
+ normalize([
+ constraints.shouldShowSubjectSection
+ ? getAttributeValue(formData.subjectAttributes, CertSubjectAttributeType.COMMON_NAME)
+ : certificate.commonName,
+ ...(constraints.shouldShowSanSection
+ ? (formData.subjectAltNames ?? []).map((san) => san.value)
+ : originalAltNames)
+ ])
+ );
+ return [...new Set(normalize([certificate.commonName, ...originalAltNames]))].filter(
+ (name) => !requestedNames.has(name)
+ );
+};