Skip to content

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

feat(pki): soft delete certificates

Carlos Monastyrski5cea1e010cf2
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 7179879863..0c7b8750c6 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -943,6 +943,53 @@ logger.error({ sessionId, err }, "Failed to get connection details");
Note that `logger.ts` also has a `redactedKeys` list applied to structured-object fields up to depth three. It only matches by key name, so it does **not** help with a secret embedded in a `url` field.
+### Certificate soft delete
+
+Deleting a certificate stamps `deletedAt`, `deletedByActorType`, `deletedByActorId` and `deletedVia` on
+the row and, in the same transaction, removes its `certificate_bodies`, `certificate_secrets` and
+`certificate_syncs` rows. The row itself stays, so the inventory, audit trail and renewal chain keep
+pointing at something. Things that rely on that:
+
+- **Every background or enumeration query filters `whereNull("deletedAt")`**: expiry alerts, auto-renewal,
+ syncs, discovery, HSM connector usage and stats. A new query over `certificates` needs the same filter unless
+ it is deliberately showing deleted rows. Reads the API serves skip deleted certificates by default too:
+ `GET /certificates/:id` returns 404 and list or search returns none unless the caller passes
+ `includeDeleted` (or a `deleted` status filter), so clients written before soft delete keep seeing what they
+ saw when the row was hard deleted. The one background job that still reads deleted rows is the DigiCert
+ revocation sync: it records an upstream revocation on a deleted certificate (without alerts) so the quota
+ stops counting it.
+- **The licence quota still counts a deleted certificate Infisical issued until it expires or is revoked**,
+ because deleting neither revokes it nor requires it to be expired, so excluding it would let an org free
+ its cap while the certificate stays trusted. Deleted imported and discovered certificates stop counting, as
+ the hard delete used to make them.
+- **CRL and OCSP keep deleted certificates.** Deletion is not revocation, so a revoked certificate stays on
+ the CRL after it is deleted, and revoking a deleted certificate is still allowed.
+- **A deleted certificate is never renewed or changed.** `assertCertificateNotDeleted` guards the renewal
+ entry points, EST re-enroll and SCEP renewal refuse a deleted client certificate, and
+ external-CA renewals lock the original with `lockRenewalOriginalCertificate` as the first statement of
+ the transaction that stores the successor (before the insert, whose foreign key would otherwise take a
+ weaker lock first and deadlock two concurrent renewals), so a delete that commits while a CA is still
+ issuing aborts the link, and the error names the serial the CA issued so it can be revoked upstream.
+ Internal-CA and self-signed renewals run in one transaction that checks the original first, so they take no
+ extra lock. The issuance queue and the DigiCert and GoDaddy pollers also check the original before calling
+ the CA.
+- **Re-import restores the row** (`restoreDeleted`) when the deleted row has the same fingerprint, Application,
+ project, profile and CA (`canRestoreDeletedCertificate`). The import has to name the deleted row's profile, so the
+ profile's `IssueCert` check always runs before a profile-managed certificate comes back. Both restore paths
+ emit `restore-cert` with `restoredVia`, and `restoreDeleted` resets the HSM key fields. **Rediscovery restores it only when the
+ discovery job has `restoreDeletedCertificates` on** and the row has no Application, profile or CA (the same
+ `canRestoreDeletedCertificate` rule, which also requires the same project); otherwise the installation is linked to the deleted row,
+ so the inventory can still show where a deleted certificate is deployed.
+- **Discovery matches deleted rows by fingerprint, and certificates issued before 2026-01-27 have none.** The
+ delete computes and stores a missing fingerprint before it removes the body, so discovery can still find the
+ deleted row.
+- **A deleted certificate can keep `keySource = hsm` after its HSM connector is deleted.** The key source CHECK
+ allows a null `hsmConnectorId` on deleted rows, so deleting a connector only detaches them and the record
+ still says the key lived in an HSM.
+- **Serial numbers stay globally unique, deleted rows included** (`certificates_serialnumber_unique`), so a
+ deleted certificate still holds its serial: re-importing it restores the row, and a re-import that cannot be
+ restored (another Application, profile or CA) is refused with a message naming where to import it instead.
+
### Certificate revocation: CRL and OCSP
Internal CAs publish revocation two ways, both unauthenticated public endpoints under
diff --git a/backend/src/db/migrations/20261020143827_add-soft-delete-to-certificates.ts b/backend/src/db/migrations/20261020143827_add-soft-delete-to-certificates.ts
new file mode 100644
index 0000000000..6b2d845d1e
--- /dev/null
+++ b/backend/src/db/migrations/20261020143827_add-soft-delete-to-certificates.ts
@@ -0,0 +1,133 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+const DELETED_INDEX_NAME = "certificates_projectid_deleted_index";
+const DELETION_AWARE_QUOTA_KEY_INDEX = "certificates_projectid_quotakey_deletion_index";
+const LEGACY_QUOTA_KEY_INDEX = "certificates_projectid_quotakey_index";
+const KEY_SOURCE_CHECK_NAME = "certificates_key_source_chk";
+const LIVE_HSM_KEY_SOURCE_CHECK = `("keySource" = 'infisical') OR ("keySource" = 'hsm' AND "hsmConnectorId" IS NOT NULL AND "hsmKeyLabel" IS NOT NULL)`;
+const SOFT_DELETE_HSM_KEY_SOURCE_CHECK = `("keySource" = 'infisical') OR ("keySource" = 'hsm' AND "hsmKeyLabel" IS NOT NULL AND ("hsmConnectorId" IS NOT NULL OR "deletedAt" IS NOT NULL))`;
+
+const ALTER_LOCK_TIMEOUT = 10 * 1000;
+const MIGRATION_TIMEOUT = 60 * 60 * 1000;
+const MIGRATION_LOCK_TIMEOUT = 30 * 1000;
+
+const withMigrationConnection = async (knex: Knex, run: (raw: (sql: string) => Knex.Raw) => Promise<void>) => {
+ const connection = await knex.client.acquireConnection();
+ const raw = (sql: string) => knex.raw(sql).connection(connection);
+
+ try {
+ const stmtResult = await raw("SHOW statement_timeout");
+ const originalStatementTimeout = stmtResult.rows[0].statement_timeout as string;
+ const lockResult = await raw("SHOW lock_timeout");
+ const originalLockTimeout = lockResult.rows[0].lock_timeout as string;
+
+ try {
+ await raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);
+ await raw(`SET lock_timeout = ${MIGRATION_LOCK_TIMEOUT}`);
+ await run(raw);
+ } finally {
+ await raw(`SET statement_timeout = '${originalStatementTimeout}'`);
+ await raw(`SET lock_timeout = '${originalLockTimeout}'`);
+ }
+ } finally {
+ await knex.client.releaseConnection(connection);
+ }
+};
+
+const createIndexConcurrently = async (raw: (sql: string) => Knex.Raw, name: string, definition: string) => {
+ const invalid = await raw(
+ `SELECT 1 FROM pg_class c JOIN pg_index i ON i.indexrelid = c.oid WHERE c.relname = '${name}' AND NOT i.indisvalid`
+ );
+ if (invalid.rows.length > 0) {
+ await raw(`DROP INDEX CONCURRENTLY IF EXISTS "${name}"`);
+ }
+ await raw(`CREATE INDEX CONCURRENTLY IF NOT EXISTS "${name}" ${definition}`);
+};
+
+const replaceKeySourceCheck = async (knex: Knex, checkExpression: string) => {
+ await knex.transaction(async (tx) => {
+ await tx.raw(`SET LOCAL lock_timeout = ${ALTER_LOCK_TIMEOUT}`);
+ await tx.raw(`ALTER TABLE ?? DROP CONSTRAINT IF EXISTS ??`, [TableName.Certificate, KEY_SOURCE_CHECK_NAME]);
+ await tx.raw(`ALTER TABLE ?? ADD CONSTRAINT ?? CHECK (${checkExpression}) NOT VALID`, [
+ TableName.Certificate,
+ KEY_SOURCE_CHECK_NAME
+ ]);
+ });
+
+ await withMigrationConnection(knex, async (raw) => {
+ await raw(`ALTER TABLE "${TableName.Certificate}" VALIDATE CONSTRAINT "${KEY_SOURCE_CHECK_NAME}"`);
+ });
+};
+
+export async function up(knex: Knex): Promise<void> {
+ await knex.transaction(async (tx) => {
+ await tx.raw(`SET LOCAL lock_timeout = ${ALTER_LOCK_TIMEOUT}`);
+ await tx.raw(
+ `ALTER TABLE ?? ADD COLUMN IF NOT EXISTS "deletedAt" timestamptz, ADD COLUMN IF NOT EXISTS "deletedByActorType" varchar(255), ADD COLUMN IF NOT EXISTS "deletedByActorId" uuid, ADD COLUMN IF NOT EXISTS "deletedVia" varchar(255)`,
+ [TableName.Certificate]
+ );
+ await tx.raw(
+ `ALTER TABLE ?? ADD COLUMN IF NOT EXISTS "restoreDeletedCertificates" boolean NOT NULL DEFAULT false`,
+ [TableName.PkiDiscoveryConfig]
+ );
+ });
+
+ await replaceKeySourceCheck(knex, SOFT_DELETE_HSM_KEY_SOURCE_CHECK);
+
+ const hasQuotaKey = await knex.schema.hasColumn(TableName.Certificate, "quotaKey");
+ await withMigrationConnection(knex, async (raw) => {
+ await createIndexConcurrently(
+ raw,
+ DELETED_INDEX_NAME,
+ `ON "${TableName.Certificate}" ("projectId") WHERE "deletedAt" IS NOT NULL`
+ );
+
+ if (hasQuotaKey) {
+ await createIndexConcurrently(
+ raw,
+ DELETION_AWARE_QUOTA_KEY_INDEX,
+ `ON "${TableName.Certificate}" ("projectId", "quotaKey") INCLUDE ("notAfter", "status", "hasWildcard", "deletedAt", "source")`
+ );
+ await raw(`DROP INDEX CONCURRENTLY IF EXISTS "${LEGACY_QUOTA_KEY_INDEX}"`);
+ }
+
+ await raw(`ANALYZE "${TableName.Certificate}" ("deletedAt")`);
+ });
+}
+
+export async function down(knex: Knex): Promise<void> {
+ const hasQuotaKey = await knex.schema.hasColumn(TableName.Certificate, "quotaKey");
+ await withMigrationConnection(knex, async (raw) => {
+ if (hasQuotaKey) {
+ await createIndexConcurrently(
+ raw,
+ LEGACY_QUOTA_KEY_INDEX,
+ `ON "${TableName.Certificate}" ("projectId", "quotaKey") INCLUDE ("notAfter", "status", "hasWildcard")`
+ );
+ await raw(`DROP INDEX CONCURRENTLY IF EXISTS "${DELETION_AWARE_QUOTA_KEY_INDEX}"`);
+ }
+ await raw(`DROP INDEX CONCURRENTLY IF EXISTS "${DELETED_INDEX_NAME}"`);
+ });
+
+ if (await knex.schema.hasColumn(TableName.Certificate, "deletedAt")) {
+ await knex(TableName.Certificate)
+ .where("keySource", "hsm")
+ .whereNull("hsmConnectorId")
+ .update({ keySource: "infisical", hsmKeyLabel: null, hsmKeyId: null, hsmPublicKeySpki: null });
+ await replaceKeySourceCheck(knex, LIVE_HSM_KEY_SOURCE_CHECK);
+ }
+
+ await knex.transaction(async (tx) => {
+ await tx.raw(`SET LOCAL lock_timeout = ${ALTER_LOCK_TIMEOUT}`);
+ await tx.raw(
+ `ALTER TABLE ?? DROP COLUMN IF EXISTS "deletedAt", DROP COLUMN IF EXISTS "deletedByActorType", DROP COLUMN IF EXISTS "deletedByActorId", DROP COLUMN IF EXISTS "deletedVia"`,
+ [TableName.Certificate]
+ );
+ await tx.raw(`ALTER TABLE ?? DROP COLUMN IF EXISTS "restoreDeletedCertificates"`, [TableName.PkiDiscoveryConfig]);
+ });
+}
+
+const config = { transaction: false };
+export { config };
diff --git a/backend/src/db/schemas/certificates.ts b/backend/src/db/schemas/certificates.ts
index bb0a91c277..7c711e3ae8 100644
--- a/backend/src/db/schemas/certificates.ts
+++ b/backend/src/db/schemas/certificates.ts
@@ -58,7 +58,11 @@ export const CertificatesSchema = z.object({
customExtensions: z.unknown().nullable().optional(),
quotaKey: z.string().nullable().optional(),
hasWildcard: z.boolean().nullable().optional(),
- hsmKeyId: z.string().nullable().optional()
+ hsmKeyId: z.string().nullable().optional(),
+ deletedAt: z.date().nullable().optional(),
+ deletedByActorType: z.string().nullable().optional(),
+ deletedByActorId: z.string().uuid().nullable().optional(),
+ deletedVia: z.string().nullable().optional()
});
export type TCertificates = z.infer<typeof CertificatesSchema>;
diff --git a/backend/src/db/schemas/pki-discovery-configs.ts b/backend/src/db/schemas/pki-discovery-configs.ts
index 1f8a93b7c1..fa2da13f14 100644
--- a/backend/src/db/schemas/pki-discovery-configs.ts
+++ b/backend/src/db/schemas/pki-discovery-configs.ts
@@ -24,7 +24,8 @@ export const PkiDiscoveryConfigsSchema = z.object({
lastScannedAt: z.date().nullable().optional(),
createdAt: z.date(),
updatedAt: z.date(),
- gatewayPoolId: z.string().uuid().nullable().optional()
+ gatewayPoolId: z.string().uuid().nullable().optional(),
+ restoreDeletedCertificates: z.boolean().default(false)
});
export type TPkiDiscoveryConfigs = z.infer<typeof PkiDiscoveryConfigsSchema>;
diff --git a/backend/src/ee/routes/v1/pki-discovery-router.ts b/backend/src/ee/routes/v1/pki-discovery-router.ts
index 95a765e61a..793bc8f2a6 100644
--- a/backend/src/ee/routes/v1/pki-discovery-router.ts
+++ b/backend/src/ee/routes/v1/pki-discovery-router.ts
@@ -25,6 +25,9 @@ const DiscoveryConnectionsSchema = z
.array(z.object({ id: z.string().uuid(), name: z.string(), app: z.nativeEnum(AppConnection) }))
.optional();
+const RESTORE_DELETED_CERTIFICATES_DESCRIPTION =
+ "Restore a deleted certificate when a scan finds it again. Certificates in an Application, or issued from a certificate profile or certificate authority, are never restored.";
+
export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
@@ -85,7 +88,12 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
isAutoScanEnabled: z.boolean().optional().default(false).describe("Enable automatic scheduled scans"),
scanIntervalDays: z.number().min(1).max(365).optional().describe("Interval in days between automatic scans"),
gatewayId: z.string().uuid().optional().describe("Gateway ID for scanning private networks"),
- gatewayPoolId: z.string().uuid().optional().describe("Gateway pool ID for scanning private networks")
+ gatewayPoolId: z.string().uuid().optional().describe("Gateway pool ID for scanning private networks"),
+ restoreDeletedCertificates: z
+ .boolean()
+ .optional()
+ .default(false)
+ .describe(RESTORE_DELETED_CERTIFICATES_DESCRIPTION)
})
.superRefine((data, ctx) => {
if (data.gatewayId && data.gatewayPoolId) {
@@ -113,6 +121,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
gatewayId: req.body.gatewayId,
gatewayPoolId: req.body.gatewayPoolId,
orgActor: req.permission,
+ restoreDeletedCertificates: req.body.restoreDeletedCertificates,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -126,7 +135,8 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
type: EventType.CREATE_PKI_DISCOVERY,
metadata: {
discoveryId: discovery.id,
- name: discovery.name
+ name: discovery.name,
+ restoreDeletedCertificates: discovery.restoreDeletedCertificates
}
}
});
@@ -292,7 +302,8 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
.optional()
.nullable()
.describe("Gateway pool ID for scanning private networks"),
- isActive: z.boolean().optional().describe("Whether the discovery configuration is active")
+ isActive: z.boolean().optional().describe("Whether the discovery configuration is active"),
+ restoreDeletedCertificates: z.boolean().optional().describe(RESTORE_DELETED_CERTIFICATES_DESCRIPTION)
})
.superRefine((data, ctx) => {
if (data.gatewayId && data.gatewayPoolId) {
@@ -319,6 +330,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
gatewayPoolId: req.body.gatewayPoolId,
isActive: req.body.isActive,
orgActor: req.permission,
+ restoreDeletedCertificates: req.body.restoreDeletedCertificates,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -332,7 +344,8 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
type: EventType.UPDATE_PKI_DISCOVERY,
metadata: {
discoveryId: discovery.id,
- name: discovery.name
+ name: discovery.name,
+ restoreDeletedCertificates: discovery.restoreDeletedCertificates
}
}
});
diff --git a/backend/src/ee/routes/v1/pki-installation-router.ts b/backend/src/ee/routes/v1/pki-installation-router.ts
index f71941c846..9b8dd662fd 100644
--- a/backend/src/ee/routes/v1/pki-installation-router.ts
+++ b/backend/src/ee/routes/v1/pki-installation-router.ts
@@ -107,6 +107,7 @@ export const registerPkiInstallationRouter = async (server: FastifyZodProvider)
notBefore: z.date().nullable().optional(),
notAfter: z.date().nullable().optional(),
status: z.string().nullable().optional(),
+ deletedAt: z.date().nullable().optional(),
friendlyName: z.string().nullable().optional(),
fingerprintSha256: z.string().nullable().optional(),
subjectOrganization: z.string().nullable().optional(),
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 06b50206d7..385778c138 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -42,8 +42,10 @@ import { ActorType } from "@app/services/auth/auth-type";
import {
CertExtendedKeyUsage,
CertificateDeletionEligibility,
+ CertificateRestoreSource,
CertKeyAlgorithm,
CertKeyUsage,
+ CertStatus,
CrlReason
} from "@app/services/certificate/certificate-types";
import { CaStatus } from "@app/services/certificate-authority/certificate-authority-enums";
@@ -442,6 +444,7 @@ export enum EventType {
GET_CA_CERTIFICATE_TEMPLATES = "get-ca-certificate-templates",
GET_CERT = "get-cert",
DELETE_CERT = "delete-cert",
+ RESTORE_CERT = "restore-cert",
REVOKE_CERT = "revoke-cert",
ASSIGN_CERT_TO_APPLICATION = "assign-cert-to-application",
GET_CERT_BODY = "get-cert-body",
@@ -3237,6 +3240,24 @@ interface ImportCert {
};
}
+interface RestoreCert {
+ type: EventType.RESTORE_CERT;
+ metadata: {
+ certId: string;
+ cn: string;
+ serialNumber: string;
+ restoredVia: CertificateRestoreSource;
+ applicationId?: string | null;
+ applicationName?: string | null;
+ certificateProfileId?: string;
+ profileName?: string;
+ caId?: string;
+ caName?: string;
+ discoveryId?: string;
+ discoveryName?: string;
+ };
+}
+
interface SignCert {
type: EventType.SIGN_CERT;
metadata: {
@@ -3274,7 +3295,8 @@ interface DeleteCert {
serialNumber: string;
notAfter: string;
source: CertificateSource;
- deletionAllowedReason: CertificateDeletionEligibility;
+ statusAtDeletion: CertStatus;
+ deletionAllowedReason?: CertificateDeletionEligibility;
applicationId?: string | null;
applicationName?: string | null;
};
@@ -4952,6 +4974,7 @@ interface CreatePkiDiscoveryEvent {
metadata: {
discoveryId: string;
name: string;
+ restoreDeletedCertificates?: boolean;
};
}
@@ -4960,6 +4983,7 @@ interface UpdatePkiDiscoveryEvent {
metadata: {
discoveryId: string;
name: string;
+ restoreDeletedCertificates?: boolean;
};
}
@@ -8272,6 +8296,7 @@ export type Event =
| GetCaCertificateTemplates
| GetCert
| DeleteCert
+ | RestoreCert
| RevokeCert
| AssignCertToApplication
| GetCertBody
diff --git a/backend/src/ee/services/pki-acme/pki-acme-service.ts b/backend/src/ee/services/pki-acme/pki-acme-service.ts
index 62e598335f..6d76e66c69 100644
--- a/backend/src/ee/services/pki-acme/pki-acme-service.ts
+++ b/backend/src/ee/services/pki-acme/pki-acme-service.ts
@@ -29,6 +29,8 @@ import {
} from "@app/services/approval-policy/cert-request/cert-request-policy-types";
import { ActorType } from "@app/services/auth/auth-type";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
+import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
+import { assertCertificateMaterialAvailable } from "@app/services/certificate/certificate-fns";
import { CertSubjectAlternativeNameType } from "@app/services/certificate/certificate-types";
import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";
import { CaCapability, CaType } from "@app/services/certificate-authority/certificate-authority-enums";
@@ -149,6 +151,7 @@ type TPkiAcmeServiceFactoryDep = {
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;
certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithOwnerOrgId" | "findByIdWithConfigs">;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne" | "create">;
+ certificateDAL: Pick<TCertificateDALFactory, "findById">;
certificatePolicyDAL: Pick<TCertificatePolicyDALFactory, "findById">;
acmeAccountDAL: Pick<
TPkiAcmeAccountDALFactory,
@@ -205,6 +208,7 @@ export const pkiAcmeServiceFactory = ({
certificateAuthorityDAL,
certificateProfileDAL,
certificateBodyDAL,
+ certificateDAL,
certificatePolicyDAL,
acmeAccountDAL,
acmeOrderDAL,
@@ -1661,6 +1665,9 @@ export const pkiAcmeServiceFactory = ({
throw new NotFoundError({ message: "The certificate for this ACME order no longer exists" });
}
+ const certificate = await certificateDAL.findById(syncedOrder.certificateId);
+ if (certificate) assertCertificateMaterialAvailable(certificate);
+
const certBody = await certificateBodyDAL.findOne({ certId: syncedOrder.certificateId });
const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
projectId: profile.projectId,
diff --git a/backend/src/ee/services/pki-discovery/pki-certificate-installation-dal.ts b/backend/src/ee/services/pki-discovery/pki-certificate-installation-dal.ts
index fb48154075..6f272acb1f 100644
--- a/backend/src/ee/services/pki-discovery/pki-certificate-installation-dal.ts
+++ b/backend/src/ee/services/pki-discovery/pki-certificate-installation-dal.ts
@@ -237,6 +237,7 @@ export const pkiCertificateInstallationDALFactory = (db: TDbClient) => {
`${TableName.Certificate}.notBefore`,
`${TableName.Certificate}.notAfter`,
`${TableName.Certificate}.status`,
+ `${TableName.Certificate}.deletedAt`,
`${TableName.Certificate}.friendlyName`,
`${TableName.Certificate}.fingerprintSha256`,
`${TableName.Certificate}.subjectOrganization`,
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.ts
index de92071e00..60e4926651 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.ts
@@ -3,6 +3,7 @@ import { Knex } from "knex";
import net from "net";
import pLimit from "p-limit";
+import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
@@ -49,7 +50,12 @@ import {
TCertificateScanResponse
} from "./pki-discovery-host-fns";
import { TPkiDiscoveryInstallationDALFactory } from "./pki-discovery-installation-dal";
-import { processDiscoveredCertificate, TKmsEncryptor } from "./pki-discovery-scan-fns";
+import {
+ buildDeletedCertificatePolicy,
+ processDiscoveredCertificate,
+ TDeletedCertificatePolicy,
+ TKmsEncryptor
+} from "./pki-discovery-scan-fns";
import { TPkiDiscoveryScanHistoryDALFactory } from "./pki-discovery-scan-history-dal";
import {
discardScanRunIfDeleted,
@@ -91,6 +97,7 @@ export type THostScanDeps = {
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "selectGatewayFromPool">;
keyStore: Pick<TKeyStoreFactory, "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete">;
telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
};
type TResolvedHost = {
@@ -311,6 +318,7 @@ type TWriteContext = {
scanTime: Date;
importStandaloneCaCertificates: boolean;
kmsEncryptor: TKmsEncryptor;
+ deletedCertificatePolicy: TDeletedCertificatePolicy;
certificateIdsByFingerprint: Map<string, string>;
targetInstallationId?: string;
};
@@ -354,7 +362,8 @@ const importCertificateChains = async (
{
certificateDAL: deps.certificateDAL,
certificateBodyDAL: deps.certificateBodyDAL,
- kmsEncryptor: ctx.kmsEncryptor
+ kmsEncryptor: ctx.kmsEncryptor,
+ deletedCertificatePolicy: ctx.deletedCertificatePolicy
},
{
discoveredBy: ctx.discoveryId,
@@ -612,6 +621,12 @@ export const executeLinuxServerScan = async (discoveryId: string, deps: THostSca
scanTime: startedAt,
importStandaloneCaCertificates: targetConfig.importStandaloneCaCertificates,
kmsEncryptor,
+ deletedCertificatePolicy: buildDeletedCertificatePolicy(deps, {
+ projectId: discoveryConfig.projectId,
+ discoveryId,
+ discoveryName: discoveryConfig.name,
+ restoreDeletedCertificates: discoveryConfig.restoreDeletedCertificates
+ }),
certificateIdsByFingerprint: new Map()
},
writeLimit: pLimit(1),
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts b/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts
index 2e87354f06..828533f213 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts
@@ -1,3 +1,4 @@
+import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
@@ -40,6 +41,7 @@ type TPkiDiscoveryQueueFactoryDep = {
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId" | "selectGatewayFromPool">;
telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
keyStore: Pick<TKeyStoreFactory, "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete">;
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
};
const SCAN_WORKER_CONCURRENCY = 3;
@@ -64,7 +66,8 @@ export const pkiDiscoveryQueueFactory = ({
gatewayV2DAL,
gatewayPoolService,
telemetryService,
- keyStore
+ keyStore,
+ auditLogService
}: TPkiDiscoveryQueueFactoryDep) => {
const scanDeps = {
appConnectionDAL,
@@ -81,7 +84,8 @@ export const pkiDiscoveryQueueFactory = ({
gatewayV2DAL,
gatewayPoolService,
telemetryService,
- keyStore
+ keyStore,
+ auditLogService
};
const startPkiDiscoveryScanQueue = () => {
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-rescan-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-rescan-fns.ts
index 4396cb40a7..80de5fb3b3 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-rescan-fns.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-rescan-fns.ts
@@ -11,6 +11,7 @@ import {
toHostScanErrorMessage,
writeHostFile
} from "./pki-discovery-host-scan-fns";
+import { buildDeletedCertificatePolicy } from "./pki-discovery-scan-fns";
import { DB_SHORT_VARCHAR_LIMIT, truncateString } from "./pki-discovery-scan-run-fns";
import { LinuxServerTargetConfigSchema } from "./pki-discovery-schemas";
import {
@@ -97,6 +98,12 @@ export const rescanInstallation = async (installationId: string, deps: THostScan
scanTime: new Date(),
importStandaloneCaCertificates: targetConfig.importStandaloneCaCertificates,
kmsEncryptor,
+ deletedCertificatePolicy: buildDeletedCertificatePolicy(deps, {
+ projectId: installation.projectId,
+ discoveryId: discoveryConfig?.id ?? "",
+ discoveryName: discoveryConfig?.name ?? "",
+ restoreDeletedCertificates: discoveryConfig?.restoreDeletedCertificates ?? false
+ }),
certificateIdsByFingerprint: new Map(),
targetInstallationId: installation.id
},
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.ts
index 90267a0ea9..912285ebae 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.ts
@@ -3,7 +3,8 @@ import { Knex } from "knex";
import net from "net";
import pLimit from "p-limit";
-import { TCertificatesInsert, TPkiCertificateInstallationsInsert } from "@app/db/schemas";
+import { TCertificates, TCertificatesInsert, TPkiCertificateInstallationsInsert } from "@app/db/schemas";
+import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
@@ -12,9 +13,11 @@ import { hasPostgresErrorCode } from "@app/lib/errors/postgres";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
+import { ActorType } from "@app/services/auth/auth-type";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
-import { CertStatus } from "@app/services/certificate/certificate-types";
+import { canRestoreDeletedCertificate } from "@app/services/certificate/certificate-fns";
+import { CertificateRestoreSource, CertStatus } from "@app/services/certificate/certificate-types";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
@@ -66,8 +69,44 @@ type TExecuteScanDeps = {
gatewayV2DAL?: Pick<TGatewayV2DALFactory, "findById">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
telemetryService?: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
};
+export type TDeletedCertificatePolicy = {
+ restoreDeletedCertificates: boolean;
+ onCertificateRestored: (certificate: TCertificates) => Promise<void>;
+};
+
+export const buildDeletedCertificatePolicy = (
+ deps: { auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog"> },
+ discovery: { projectId: string; discoveryId: string; discoveryName: string; restoreDeletedCertificates: boolean }
+): TDeletedCertificatePolicy => ({
+ restoreDeletedCertificates: discovery.restoreDeletedCertificates,
+ onCertificateRestored: (restoredCertificate) =>
+ deps.auditLogService
+ .createAuditLog({
+ projectId: discovery.projectId,
+ actor: { type: ActorType.PLATFORM, metadata: {} },
+ event: {
+ type: EventType.RESTORE_CERT,
+ metadata: {
+ certId: restoredCertificate.id,
+ cn: restoredCertificate.commonName,
+ serialNumber: restoredCertificate.serialNumber,
+ restoredVia: CertificateRestoreSource.Discovery,
+ discoveryId: discovery.discoveryId,
+ discoveryName: discovery.discoveryName
+ }
+ }
+ })
+ .catch((error: unknown) => {
+ logger.error(
+ error,
+ `Failed to record the restore of a deleted certificate [certificateId=${restoredCertificate.id}] [discoveryId=${discovery.discoveryId}]`
+ );
+ })
+});
+
export const findOrCreateNetworkInstallation = async (
deps: Pick<TExecuteScanDeps, "pkiCertificateInstallationDAL">,
tx: Knex,
@@ -301,6 +340,12 @@ export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps):
if (await discardScanRunIfDeleted(discoveryId, scanHistoryId, deps)) return;
const uniqueCertificateIds = new Set<string>();
+ const deletedCertificatePolicy = buildDeletedCertificatePolicy(deps, {
+ projectId: discoveryConfig.projectId,
+ discoveryId,
+ discoveryName: discoveryConfig.name,
+ restoreDeletedCertificates: discoveryConfig.restoreDeletedCertificates
+ });
const uniqueInstallationIds = new Set<string>();
let successfulScans = 0;
let certParseErrors = 0;
@@ -320,6 +365,7 @@ export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps):
now,
deps,
kmsEncryptor,
+ deletedCertificatePolicy,
effectiveGatewayId ?? undefined,
gatewayName,
discoveryConfig.gatewayPoolId ?? effectiveGatewayId ?? undefined
@@ -499,6 +545,7 @@ const processEndpointResult = async (
scanTime: Date,
deps: TExecuteScanDeps,
kmsEncryptor: TKmsEncryptor,
+ deletedCertificatePolicy: TDeletedCertificatePolicy,
gatewayId?: string,
gatewayName?: string,
fingerprintGatewayKey?: string
@@ -544,7 +591,7 @@ const processEndpointResult = async (
const certId = await processDiscoveredCertificate(
certResult,
projectId,
- { certificateDAL, certificateBodyDAL, kmsEncryptor },
+ { certificateDAL, certificateBodyDAL, kmsEncryptor, deletedCertificatePolicy },
{
discoveredBy: discoveryId,
host: result.host,
@@ -593,6 +640,7 @@ type TProcessDiscoveredCertDeps = {
certificateDAL: TCertificateDALFactory;
certificateBodyDAL: TCertificateBodyDALFactory;
kmsEncryptor: TKmsEncryptor;
+ deletedCertificatePolicy: TDeletedCertificatePolicy;
};
export const processDiscoveredCertificate = async (
@@ -601,7 +649,7 @@ export const processDiscoveredCertificate = async (
deps: TProcessDiscoveredCertDeps,
discoveryMetadata?: Record<string, unknown>
): Promise<string | null> => {
- const { certificateDAL, certificateBodyDAL, kmsEncryptor } = deps;
+ const { certificateDAL, certificateBodyDAL, kmsEncryptor, deletedCertificatePolicy } = deps;
try {
const existingCerts = await certificateDAL.find({
@@ -609,8 +657,17 @@ export const processDiscoveredCertificate = async (
fingerprintSha256: certResult.fingerprint
});
- if (existingCerts.length > 0) {
- return existingCerts[0].id;
+ const liveMatch = existingCerts.find((existing) => !existing.deletedAt);
+ if (liveMatch) {
+ return liveMatch.id;
+ }
+ const deletedMatch = existingCerts[0];
+ if (
+ deletedMatch &&
+ (!deletedCertificatePolicy.restoreDeletedCertificates ||
+ !canRestoreDeletedCertificate(deletedMatch, { projectId, applicationId: null, profileId: null, caId: null }))
+ ) {
+ return deletedMatch.id;
}
const friendlyName =
@@ -622,9 +679,8 @@ export const processDiscoveredCertificate = async (
// Deliberately not gated on the certificate quota: this is a background scan, and every PKI
// license gate blocks creation only. A scan can push an org past its cap, after which new
// issuance is refused until it upgrades or cleans up.
- const certData: Omit<TCertificatesInsert, "quotaKey"> = {
+ const certData: Omit<TCertificatesInsert, "quotaKey" | "status"> = {
projectId,
- status: CertStatus.ACTIVE,
serialNumber: truncateString(serialNumber, DB_SHORT_VARCHAR_LIMIT) || "unknown",
friendlyName,
commonName: truncateString(certResult.commonName, DB_SHORT_VARCHAR_LIMIT) || "Unknown",
@@ -667,7 +723,23 @@ export const processDiscoveredCertificate = async (
}
const newCert = await certificateDAL.transaction(async (tx) => {
- const cert = await certificateDAL.create(certData, tx);
+ const cert = deletedMatch
+ ? await certificateDAL.restoreDeleted(
+ deletedMatch.id,
+ {
+ ...certData,
+ serialNumber: deletedMatch.serialNumber,
+ friendlyName: deletedMatch.friendlyName,
+ source: deletedMatch.source,
+ discoveryMetadata:
+ deletedMatch.source === CertificateSource.Discovered
+ ? certData.discoveryMetadata
+ : deletedMatch.discoveryMetadata
+ },
+ tx
+ )
+ : await certificateDAL.create({ status: CertStatus.ACTIVE, ...certData }, tx);
+ if (!cert) return undefined;
if (encryptedCertificate) {
await certificateBodyDAL.create(
@@ -683,6 +755,9 @@ export const processDiscoveredCertificate = async (
return cert;
});
+ if (!newCert) return deletedMatch?.id ?? null;
+ if (deletedMatch) await deletedCertificatePolicy.onCertificateRestored(newCert);
+
return newCert.id;
} catch (error) {
const dbError = error as { code?: string };
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-service.ts b/backend/src/ee/services/pki-discovery/pki-discovery-service.ts
index d513562b09..bcf52b7798 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-service.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-service.ts
@@ -181,6 +181,7 @@ export const pkiDiscoveryServiceFactory = ({
gatewayId,
gatewayPoolId,
orgActor,
+ restoreDeletedCertificates,
actor,
actorId,
actorAuthMethod,
@@ -272,7 +273,8 @@ export const pkiDiscoveryServiceFactory = ({
scanIntervalDays: isAutoScanEnabled ? scanIntervalDays : null,
gatewayId: gatewayPoolId ? null : gatewayId,
gatewayPoolId: gatewayPoolId ?? null,
- isActive: true
+ isActive: true,
+ restoreDeletedCertificates
});
return discovery;
@@ -298,6 +300,7 @@ export const pkiDiscoveryServiceFactory = ({
gatewayPoolId,
isActive,
orgActor,
+ restoreDeletedCertificates,
actor,
actorId,
actorAuthMethod,
@@ -396,7 +399,8 @@ export const pkiDiscoveryServiceFactory = ({
scanIntervalDays: isAutoScanEnabled ? scanIntervalDays : null,
gatewayId: gatewayIdValue,
gatewayPoolId: gatewayPoolIdValue,
- isActive
+ isActive,
+ restoreDeletedCertificates
});
return updatedDiscovery;
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-types.ts b/backend/src/ee/services/pki-discovery/pki-discovery-types.ts
index 25da2d47be..93ba6281aa 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-types.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-types.ts
@@ -132,6 +132,7 @@ export type TCreatePkiDiscoveryDTO = {
gatewayId?: string | null;
gatewayPoolId?: string | null;
orgActor: OrgServiceActor;
+ restoreDeletedCertificates?: boolean;
} & Omit<TProjectPermission, "projectId">;
export type TUpdatePkiDiscoveryDTO = {
@@ -145,6 +146,7 @@ export type TUpdatePkiDiscoveryDTO = {
gatewayPoolId?: string | null;
isActive?: boolean;
orgActor: OrgServiceActor;
+ restoreDeletedCertificates?: boolean;
} & Omit<TProjectPermission, "projectId">;
export type TDeletePkiDiscoveryDTO = {
diff --git a/backend/src/ee/services/pki-scep/pki-scep-fns.test.ts b/backend/src/ee/services/pki-scep/pki-scep-fns.test.ts
index 6a30309d3a..8cac35e3ba 100644
--- a/backend/src/ee/services/pki-scep/pki-scep-fns.test.ts
+++ b/backend/src/ee/services/pki-scep/pki-scep-fns.test.ts
@@ -458,6 +458,19 @@ describe("evaluateScepRenewalAuthorization", () => {
).toEqual({ authorized: true });
});
+ test("denies when the signer certificate was deleted", () => {
+ expect(
+ evaluateScepRenewalAuthorization({
+ isValidSigner: true,
+ storedSignerCert: { profileId: PROFILE_ID, deletedAt: new Date() },
+ profileId: PROFILE_ID,
+ csrForwardedToCa: false,
+ csrSubjectName: new x509.Name("CN=device-01"),
+ signerCertSubjectName: new x509.Name("CN=device-01")
+ })
+ ).toEqual({ authorized: false, reason: ScepRenewalDenyReason.SignerDeleted });
+ });
+
test("denies when the signer certificate belongs to another profile", () => {
expect(
evaluateScepRenewalAuthorization({
diff --git a/backend/src/ee/services/pki-scep/pki-scep-fns.ts b/backend/src/ee/services/pki-scep/pki-scep-fns.ts
index ecd1031314..e93063a202 100644
--- a/backend/src/ee/services/pki-scep/pki-scep-fns.ts
+++ b/backend/src/ee/services/pki-scep/pki-scep-fns.ts
@@ -325,6 +325,7 @@ export const isSignerCertIssuedByCa = async ({
export enum ScepRenewalDenyReason {
InvalidSigner = "invalid-signer",
+ SignerDeleted = "signer-deleted",
WrongProfile = "wrong-profile",
WrongApplication = "wrong-application",
SubjectMismatch = "subject-mismatch",
@@ -422,7 +423,7 @@ export const evaluateScepRenewalAuthorization = ({
signerCertSubjectAltNames
}: {
isValidSigner: boolean;
- storedSignerCert?: { profileId?: string | null; applicationId?: string | null } | null;
+ storedSignerCert?: { profileId?: string | null; applicationId?: string | null; deletedAt?: Date | null } | null;
profileId: string;
applicationId?: string | null;
csrForwardedToCa: boolean;
@@ -436,6 +437,10 @@ export const evaluateScepRenewalAuthorization = ({
return { authorized: false, reason: ScepRenewalDenyReason.InvalidSigner };
}
+ if (storedSignerCert?.deletedAt) {
+ return { authorized: false, reason: ScepRenewalDenyReason.SignerDeleted };
+ }
+
if (!storedSignerCert || storedSignerCert.profileId !== profileId) {
return { authorized: false, reason: ScepRenewalDenyReason.WrongProfile };
}
diff --git a/backend/src/ee/services/pki-scep/pki-scep-service.ts b/backend/src/ee/services/pki-scep/pki-scep-service.ts
index d6b5ff0bae..1bcca4b385 100644
--- a/backend/src/ee/services/pki-scep/pki-scep-service.ts
+++ b/backend/src/ee/services/pki-scep/pki-scep-service.ts
@@ -726,6 +726,8 @@ export const pkiScepServiceFactory = ({
const failReasonByDenyReason: Record<ScepRenewalDenyReason, string> = {
[ScepRenewalDenyReason.InvalidSigner]:
"Signer certificate is missing, malformed, expired, revoked, or does not chain to profile CA",
+ [ScepRenewalDenyReason.SignerDeleted]:
+ "Signer certificate was deleted and can no longer be renewed. Enroll a new certificate instead",
[ScepRenewalDenyReason.WrongProfile]: "Signer certificate does not belong to this profile",
[ScepRenewalDenyReason.WrongApplication]:
"Signer certificate was not issued through the application handling this request",
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index b6f691916a..168126116c 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -1121,9 +1121,10 @@ export const PROJECTS = {
offset: "The offset to start from. If you enter 10, it will start from the 10th certificate.",
limit: "The number of certificates to return.",
forPkiSync: "Retrieve only certificates available for PKI sync.",
+ includeDeleted: "Also return deleted certificates when no status filter is set.",
search: "Search by SAN, CN, certificate ID, or serial number.",
status:
- "Comma-separated list of certificate statuses to filter by. Supported values are active, renewed, expired and revoked. A certificate superseded by a renewal matches renewed rather than active until it expires or is revoked.",
+ "Comma-separated list of certificate statuses to filter by. Supported values are active, renewed, expired, revoked and deleted. A certificate superseded by a renewal matches renewed rather than active until it expires or is revoked. Deleted certificates match only deleted.",
profileIds: "Filter by certificate profile IDs.",
fromDate: "Filter certificates created from this date.",
toDate: "Filter certificates created until this date.",
@@ -2300,11 +2301,19 @@ export const CERTIFICATES = {
GET: {
id: "The ID of the certificate to get.",
serialNumber: "The serial number of the certificate to get.",
+ includeDeleted: "Return the certificate even if it was deleted. Without it, a deleted certificate returns 404.",
hasPrivateKey: "Whether Infisical holds the private key for this certificate.",
externalMetadata:
"Identifies this certificate at the provider that issued it, for certificates issued by or linked to an external certificate authority. Null for everything else.",
latestRenewalCertificateId:
- "The ID of the newest certificate that has replaced this one through renewal, or null if no newer replacement is available. Revoked certificates are never named, so this is null when this certificate has never been renewed and also when every renewal of it has since been revoked. Use this to follow renewals without walking the chain one certificate at a time."
+ "The ID of the newest certificate that has replaced this one through renewal, or null if no newer replacement is available. Revoked and deleted certificates are never named, so this is null when this certificate has never been renewed and also when every renewal of it has since been revoked or deleted. Use this to follow renewals without walking the chain one certificate at a time.",
+ deletedAt:
+ "When this certificate was deleted, or null if it has not been. A deleted certificate keeps its record, metadata and renewal history, but its certificate and private key are no longer available.",
+ deletedByActorType: "The type of actor that deleted this certificate: 'user' or 'identity'.",
+ deletedByActorId: "The ID of the user or machine identity that deleted this certificate.",
+ deletedByActorName: "The name of the user or machine identity that deleted this certificate, if it still exists.",
+ deletedVia:
+ "The client the certificate was deleted from, such as 'web' for the Infisical UI or 'terraform' for the Terraform provider."
},
RENEW: {
id: "The ID of the certificate to renew.",
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 9a33acae17..a555b458e1 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -3820,7 +3820,10 @@ export const registerRoutes = async (
licenseService,
usageMeteringService,
caKeySourceService,
- internalCertificateAuthorityDAL
+ internalCertificateAuthorityDAL,
+ signerDAL,
+ userDAL,
+ identityDAL
});
const godaddyCaFns = GoDaddyCertificateAuthorityFns({
@@ -4166,6 +4169,7 @@ export const registerRoutes = async (
});
const digicertCaQueue = digicertCertificateAuthorityQueueServiceFactory({
+ certificateDAL,
cronJob,
certificateRequestDAL,
certificateRequestService,
@@ -4192,6 +4196,7 @@ export const registerRoutes = async (
});
const godaddyCaQueue = godaddyCertificateAuthorityQueueServiceFactory({
+ certificateDAL,
cronJob,
certificateRequestDAL,
certificateRequestService,
@@ -4266,6 +4271,7 @@ export const registerRoutes = async (
certificateAuthorityDAL,
certificateProfileDAL,
certificateBodyDAL,
+ certificateDAL,
certificatePolicyDAL,
acmeAccountDAL,
acmeOrderDAL,
@@ -4341,7 +4347,8 @@ export const registerRoutes = async (
gatewayV2DAL,
gatewayPoolService,
telemetryService,
- keyStore
+ keyStore,
+ auditLogService
});
const pkiDiscoveryService = pkiDiscoveryServiceFactory({
diff --git a/backend/src/server/routes/v1/certificate-profiles-router.ts b/backend/src/server/routes/v1/certificate-profiles-router.ts
index 87369e3925..603c1c49d1 100644
--- a/backend/src/server/routes/v1/certificate-profiles-router.ts
+++ b/backend/src/server/routes/v1/certificate-profiles-router.ts
@@ -810,6 +810,7 @@ export const registerCertificateProfilesRouter = async (
notBefore: z.date(),
notAfter: z.date(),
revokedAt: z.date().nullable().optional(),
+ deletedAt: z.date().nullable().optional(),
createdAt: z.date()
})
)
diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.ts
index a046686f39..2300df1402 100644
--- a/backend/src/server/routes/v1/certificate-router.ts
+++ b/backend/src/server/routes/v1/certificate-router.ts
@@ -2,7 +2,7 @@
import RE2 from "re2";
import { z } from "zod";
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
import { CertificateSource } from "@app/ee/services/pki-discovery/pki-discovery-types";
import { ApiDocsTags, CERTIFICATES } from "@app/lib/api-docs";
import { BadRequestError } from "@app/lib/errors";
@@ -14,9 +14,14 @@ import { addNoCacheHeaders } from "@app/server/lib/caching";
import { openApiHidden } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
+import { ActorType, AuthMode } from "@app/services/auth/auth-type";
import { SanitizedCertificateSchema } from "@app/services/certificate/certificate-schemas";
-import { CertKeyAlgorithm, CertSignatureAlgorithm, CrlReason } from "@app/services/certificate/certificate-types";
+import {
+ CertificateRestoreSource,
+ CertKeyAlgorithm,
+ CertSignatureAlgorithm,
+ CrlReason
+} from "@app/services/certificate/certificate-types";
import { CaType } from "@app/services/certificate-authority/certificate-authority-enums";
import { validateCaDateField } from "@app/services/certificate-authority/certificate-authority-validators";
import {
@@ -453,6 +458,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
certificateId: z.string().nullable(),
privateKey: z.string().nullable(),
serialNumber: z.string().nullable(),
+ certificateDeletedAt: z.date().nullable().optional(),
errorMessage: z.string().nullable(),
pendingMessage: z.string().nullable().optional(),
commonName: z.string().nullable().optional(),
@@ -1461,6 +1467,9 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
params: z.object({
id: z.string().trim().uuid().describe(CERTIFICATES.GET.id)
}),
+ querystring: z.object({
+ includeDeleted: booleanSchema.optional().describe(CERTIFICATES.GET.includeDeleted)
+ }),
response: {
200: z.object({
certificate: SanitizedCertificateSchema.extend({
@@ -1499,6 +1508,15 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
.nullable()
.optional()
.describe(CERTIFICATES.GET.latestRenewalCertificateId),
+ deletedAt: z.date().nullable().optional().describe(CERTIFICATES.GET.deletedAt),
+ deletedByActorType: z
+ .nativeEnum(ActorType)
+ .nullable()
+ .optional()
+ .describe(CERTIFICATES.GET.deletedByActorType),
+ deletedByActorId: z.string().uuid().nullable().optional().describe(CERTIFICATES.GET.deletedByActorId),
+ deletedByActorName: z.string().nullable().optional().describe(CERTIFICATES.GET.deletedByActorName),
+ deletedVia: z.nativeEnum(UserAgentType).nullable().optional().describe(CERTIFICATES.GET.deletedVia),
metadata: z.array(z.object({ key: z.string(), value: z.string() })).optional()
})
})
@@ -1507,6 +1525,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
handler: async (req) => {
const { cert } = await server.services.certificate.getCert({
id: req.params.id,
+ includeDeleted: req.query.includeDeleted,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -1769,33 +1788,45 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
}
},
handler: async (req) => {
- const { certificate, certificateChain, privateKey, serialNumber, cert, profileName, caName, applicationName } =
- await server.services.certificate.importCert({
- actor: req.permission.type,
- actorId: req.permission.id,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- projectId: req.internalCertManagerProjectId,
- ...req.body
- });
+ const {
+ certificate,
+ certificateChain,
+ privateKey,
+ serialNumber,
+ cert,
+ profileName,
+ caName,
+ applicationName,
+ restoredFromDeletion
+ } = await server.services.certificate.importCert({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.internalCertManagerProjectId,
+ ...req.body
+ });
+ const importMetadata = {
+ certId: cert.id,
+ cn: cert.commonName,
+ serialNumber,
+ applicationId: cert.applicationId,
+ applicationName,
+ certificateProfileId: cert.profileId ?? undefined,
+ profileName: profileName ?? undefined,
+ caId: cert.caId ?? undefined,
+ caName: caName ?? undefined
+ };
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
projectId: cert.projectId,
- event: {
- type: EventType.IMPORT_CERT,
- metadata: {
- certId: cert.id,
- cn: cert.commonName,
- serialNumber,
- applicationId: cert.applicationId,
- applicationName,
- certificateProfileId: cert.profileId ?? undefined,
- profileName: profileName ?? undefined,
- caId: cert.caId ?? undefined,
- caName: caName ?? undefined
- }
- }
+ event: restoredFromDeletion
+ ? {
+ type: EventType.RESTORE_CERT,
+ metadata: { ...importMetadata, restoredVia: CertificateRestoreSource.Import }
+ }
+ : { type: EventType.IMPORT_CERT, metadata: importMetadata }
});
await server.services.telemetry.sendPostHogEvents({
@@ -1904,7 +1935,8 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
hide: false,
operationId: "deleteCertificate",
tags: [ApiDocsTags.PkiCertificates],
- description: "Delete certificate. Only expired, discovered, or imported certificates can be deleted.",
+ description:
+ "Delete a certificate and its private key. Its details stay in the inventory with a deleted status. Deleting a certificate does not revoke it.",
params: z.object({
id: z.string().trim().uuid().describe(CERTIFICATES.DELETE.id)
}),
@@ -1915,14 +1947,15 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
}
},
handler: async (req) => {
- const { deletedCert, applicationName, deletionEligibility } = await server.services.certificate.deleteCert({
- id: req.params.id,
- actor: req.permission.type,
- actorId: req.permission.id,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- auditLogInfo: req.auditLogInfo
- });
+ const { deletedCert, applicationName, statusAtDeletion, deletionAllowedReason } =
+ await server.services.certificate.deleteCert({
+ id: req.params.id,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ auditLogInfo: req.auditLogInfo
+ });
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
@@ -1936,7 +1969,8 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
serialNumber: deletedCert.serialNumber,
notAfter: deletedCert.notAfter.toISOString(),
source: (deletedCert.source as CertificateSource | null) ?? CertificateSource.Issued,
- deletionAllowedReason: deletionEligibility,
+ statusAtDeletion,
+ deletionAllowedReason,
applicationId: deletedCert.applicationId,
applicationName
}
diff --git a/backend/src/server/routes/v1/deprecated-certificate-router.ts b/backend/src/server/routes/v1/deprecated-certificate-router.ts
index 3c66035410..151c30e378 100644
--- a/backend/src/server/routes/v1/deprecated-certificate-router.ts
+++ b/backend/src/server/routes/v1/deprecated-certificate-router.ts
@@ -13,7 +13,12 @@ import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
import { SanitizedCertificateSchema } from "@app/services/certificate/certificate-schemas";
-import { CertExtendedKeyUsage, CertKeyUsage, CrlReason } from "@app/services/certificate/certificate-types";
+import {
+ CertExtendedKeyUsage,
+ CertificateRestoreSource,
+ CertKeyUsage,
+ CrlReason
+} from "@app/services/certificate/certificate-types";
import {
validateAltNamesField,
validateCaDateField
@@ -325,7 +330,7 @@ export const registerDeprecatedCertRouter = async (server: FastifyZodProvider) =
}
},
handler: async (req) => {
- const { certificate, certificateChain, privateKey, serialNumber, cert, applicationName } =
+ const { certificate, certificateChain, privateKey, serialNumber, cert, applicationName, restoredFromDeletion } =
await server.services.certificate.importCert({
actor: req.permission.type,
actorId: req.permission.id,
@@ -337,16 +342,28 @@ export const registerDeprecatedCertRouter = async (server: FastifyZodProvider) =
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
projectId: cert.projectId,
- event: {
- type: EventType.IMPORT_CERT,
- metadata: {
- certId: cert.id,
- cn: cert.commonName,
- serialNumber,
- applicationId: cert.applicationId,
- applicationName
- }
- }
+ event: restoredFromDeletion
+ ? {
+ type: EventType.RESTORE_CERT,
+ metadata: {
+ certId: cert.id,
+ cn: cert.commonName,
+ serialNumber,
+ restoredVia: CertificateRestoreSource.Import,
+ applicationId: cert.applicationId,
+ applicationName
+ }
+ }
+ : {
+ type: EventType.IMPORT_CERT,
+ metadata: {
+ certId: cert.id,
+ cn: cert.commonName,
+ serialNumber,
+ applicationId: cert.applicationId,
+ applicationName
+ }
+ }
});
return {
@@ -541,7 +558,8 @@ export const registerDeprecatedCertRouter = async (server: FastifyZodProvider) =
schema: {
hide: false,
tags: [ApiDocsTags.PkiCertificates],
- description: "Delete certificate. Only expired, discovered, or imported certificates can be deleted.",
+ description:
+ "Delete a certificate and its private key. Its details stay in the inventory with a deleted status. Deleting a certificate does not revoke it.",
params: z.object({
serialNumber: z.string().trim().describe(CERTIFICATES.DELETE.serialNumber)
}),
@@ -552,14 +570,15 @@ export const registerDeprecatedCertRouter = async (server: FastifyZodProvider) =
}
},
handler: async (req) => {
- const { deletedCert, applicationName, deletionEligibility } = await server.services.certificate.deleteCert({
- serialNumber: req.params.serialNumber,
- actor: req.permission.type,
- actorId: req.permission.id,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- auditLogInfo: req.auditLogInfo
- });
+ const { deletedCert, applicationName, statusAtDeletion, deletionAllowedReason } =
+ await server.services.certificate.deleteCert({
+ serialNumber: req.params.serialNumber,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ auditLogInfo: req.auditLogInfo
+ });
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
@@ -573,7 +592,8 @@ export const registerDeprecatedCertRouter = async (server: FastifyZodProvider) =
serialNumber: deletedCert.serialNumber,
notAfter: deletedCert.notAfter.toISOString(),
source: (deletedCert.source as CertificateSource | null) ?? CertificateSource.Issued,
- deletionAllowedReason: deletionEligibility,
+ statusAtDeletion,
+ deletionAllowedReason,
applicationId: deletedCert.applicationId,
applicationName
}
diff --git a/backend/src/server/routes/v1/project-router.ts b/backend/src/server/routes/v1/project-router.ts
index b1cd61e148..0283b94291 100644
--- a/backend/src/server/routes/v1/project-router.ts
+++ b/backend/src/server/routes/v1/project-router.ts
@@ -1494,6 +1494,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
.array(z.string().uuid())
.optional()
.describe("Filter to certificates issued through any of the supplied Applications."),
+ includeDeleted: z.boolean().optional().describe(PROJECTS.SEARCH_CERTIFICATES.includeDeleted),
sortBy: z
.enum(["notAfter", "notBefore", "createdAt", "commonName", "keyAlgorithm", "status"])
.optional()
diff --git a/backend/src/services/alert/providers/cert-manager-certificate-alert-dal.ts b/backend/src/services/alert/providers/cert-manager-certificate-alert-dal.ts
index e34b6b6e1b..a31ef2c6be 100644
--- a/backend/src/services/alert/providers/cert-manager-certificate-alert-dal.ts
+++ b/backend/src/services/alert/providers/cert-manager-certificate-alert-dal.ts
@@ -90,10 +90,9 @@ export const certManagerCertificateAlertDALFactory = (db: TDbClient) => {
tx?: Knex
): Promise<TAlertCertificate[]> => {
try {
- const certificates = (await $selectCertificates(tx || db, scope).whereIn(
- `${TableName.Certificate}.id`,
- scope.certificateIds
- )) as TAlertCertificate[];
+ const certificates = (await $selectCertificates(tx || db, scope)
+ .whereIn(`${TableName.Certificate}.id`, scope.certificateIds)
+ .whereNull(`${TableName.Certificate}.deletedAt`)) as TAlertCertificate[];
return certificates;
} catch (error) {
diff --git a/backend/src/services/alert/providers/cert-manager-expiring-certificates-fns.ts b/backend/src/services/alert/providers/cert-manager-expiring-certificates-fns.ts
index 08673ddc68..92bd68f1fe 100644
--- a/backend/src/services/alert/providers/cert-manager-expiring-certificates-fns.ts
+++ b/backend/src/services/alert/providers/cert-manager-expiring-certificates-fns.ts
@@ -23,6 +23,7 @@ export const scanExpiringCertificates = async <T>(
const selectDue = () =>
selectCertificates()
.whereNot(`${TableName.Certificate}.status`, CertStatus.REVOKED)
+ .whereNull(`${TableName.Certificate}.deletedAt`)
.whereRaw(`"${TableName.Certificate}"."notAfter" > ?::timestamptz`, [asOf])
.whereRaw(`"${TableName.Certificate}"."notAfter" <= ?::timestamptz + ?::interval + ?::interval`, [
asOf,
diff --git a/backend/src/services/cert-manager-instance/cert-manager-instance-service.ts b/backend/src/services/cert-manager-instance/cert-manager-instance-service.ts
index 8258361711..f5406a9f0e 100644
--- a/backend/src/services/cert-manager-instance/cert-manager-instance-service.ts
+++ b/backend/src/services/cert-manager-instance/cert-manager-instance-service.ts
@@ -126,7 +126,12 @@ export const certManagerInstanceServiceFactory = ({
const replica = db.replicaNode();
const [certCounts, syncCounts, alertCounts] = await Promise.all([
- replica(TableName.Certificate).whereIn("projectId", projectIds).groupBy("projectId").select("projectId").count(),
+ replica(TableName.Certificate)
+ .whereIn("projectId", projectIds)
+ .whereNull("deletedAt")
+ .groupBy("projectId")
+ .select("projectId")
+ .count(),
replica(TableName.PkiSync).whereIn("projectId", projectIds).groupBy("projectId").select("projectId").count(),
replica(TableName.PkiAlertsV2).whereIn("projectId", projectIds).groupBy("projectId").select("projectId").count()
]);
diff --git a/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts b/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts
index 2449121370..3e58aa1322 100644
--- a/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts
@@ -34,7 +34,8 @@ import { TCertificateBodyDALFactory } from "@app/services/certificate/certificat
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import {
extractExternallyIssuedCertificateFields,
- linkRenewedCertificate
+ linkRenewedCertificate,
+ lockRenewalOriginalCertificate
} from "@app/services/certificate/certificate-fns";
import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
import {
@@ -155,7 +156,10 @@ type TAcmeCertificateAuthorityFnsDeps = {
"create" | "transaction" | "findByIdWithAssociatedCa" | "updateById" | "findWithAssociatedCa" | "findById"
>;
externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "create" | "update" | "findOne">;
- certificateDAL: Pick<TCertificateDALFactory, "create" | "findById" | "transaction" | "updateById">;
+ certificateDAL: Pick<
+ TCertificateDALFactory,
+ "create" | "findById" | "findByIdForUpdate" | "transaction" | "updateById"
+ >;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
kmsService: Pick<
@@ -176,7 +180,10 @@ type TOrderCertificateDeps = {
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;
externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "update">;
- certificateDAL: Pick<TCertificateDALFactory, "create" | "findById" | "transaction" | "updateById">;
+ certificateDAL: Pick<
+ TCertificateDALFactory,
+ "create" | "findById" | "findByIdForUpdate" | "transaction" | "updateById"
+ >;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
kmsService: Pick<
@@ -698,6 +705,16 @@ export const executeAcmeOrder = async (
const parsedFields = extractExternallyIssuedCertificateFields(certObj);
return (tx || certificateDAL).transaction(async (innerTx: Knex) => {
+ const lockedOriginalCertificate =
+ isRenewal && originalCertificateId
+ ? await lockRenewalOriginalCertificate(
+ certificateDAL,
+ originalCertificateId,
+ innerTx,
+ parsedFields.serialNumber
+ )
+ : undefined;
+
const cert = await certificateDAL.create(
{
...parsedFields,
@@ -718,8 +735,8 @@ export const executeAcmeOrder = async (
innerTx
);
- if (isRenewal && originalCertificateId) {
- await linkRenewedCertificate(certificateDAL, originalCertificateId, cert.id, innerTx);
+ if (lockedOriginalCertificate) {
+ await linkRenewedCertificate(certificateDAL, lockedOriginalCertificate, cert.id, innerTx);
}
await certificateBodyDAL.create(
diff --git a/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-fns.ts b/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-fns.ts
index ffc8a06eb0..e182dc6db8 100644
--- a/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/adcs/adcs-certificate-authority-fns.ts
@@ -23,7 +23,8 @@ import { TCertificateBodyDALFactory } from "@app/services/certificate/certificat
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import {
extractExternallyIssuedCertificateFields,
- linkRenewedCertificate
+ linkRenewedCertificate,
+ lockRenewalOriginalCertificate
} from "@app/services/certificate/certificate-fns";
import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
import {
@@ -132,7 +133,10 @@ type TADCSCertificateAuthorityFnsDeps = {
"create" | "transaction" | "findByIdWithAssociatedCa" | "updateById" | "findWithAssociatedCa" | "findById"
>;
externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "create" | "update">;
- certificateDAL: Pick<TCertificateDALFactory, "create" | "findById" | "findOne" | "transaction" | "updateById">;
+ certificateDAL: Pick<
+ TCertificateDALFactory,
+ "create" | "findById" | "findByIdForUpdate" | "findOne" | "transaction" | "updateById"
+ >;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
kmsService: Pick<
@@ -563,6 +567,11 @@ export const ADCSCertificateAuthorityFns = ({
const parsedFields = extractExternallyIssuedCertificateFields(certObj, customExtensions);
await certificateDAL.transaction(async (tx) => {
+ const lockedOriginalCertificate =
+ isRenewal && originalCertificateId
+ ? await lockRenewalOriginalCertificate(certificateDAL, originalCertificateId, tx, parsedFields.serialNumber)
+ : undefined;
+
const cert = await certificateDAL.create(
{
...parsedFields,
@@ -584,8 +593,8 @@ export const ADCSCertificateAuthorityFns = ({
certificateId = cert.id;
- if (isRenewal && originalCertificateId) {
- await linkRenewedCertificate(certificateDAL, originalCertificateId, cert.id, tx);
+ if (lockedOriginalCertificate) {
+ await linkRenewedCertificate(certificateDAL, lockedOriginalCertificate, cert.id, tx);
}
await certificateBodyDAL.create(
diff --git a/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns.ts b/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns.ts
index bf172feec5..4cb4adf637 100644
--- a/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns.ts
@@ -28,7 +28,8 @@ import { TCertificateBodyDALFactory } from "@app/services/certificate/certificat
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import {
extractExternallyIssuedCertificateFields,
- linkRenewedCertificate
+ linkRenewedCertificate,
+ lockRenewalOriginalCertificate
} from "@app/services/certificate/certificate-fns";
import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
import {
@@ -83,7 +84,10 @@ type TAwsAcmPublicCaCertificateAuthorityFnsDeps = {
"create" | "transaction" | "findByIdWithAssociatedCa" | "updateById" | "findWithAssociatedCa" | "findById"
>;
externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "create" | "update">;
- certificateDAL: Pick<TCertificateDALFactory, "create" | "findById" | "findOne" | "transaction" | "updateById">;
+ certificateDAL: Pick<
+ TCertificateDALFactory,
+ "create" | "findById" | "findByIdForUpdate" | "findOne" | "transaction" | "updateById"
+ >;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
kmsService: Pick<
@@ -684,6 +688,11 @@ export const AwsAcmPublicCaCertificateAuthorityFns = ({
let newCertId: string;
await certificateDAL.transaction(async (tx) => {
+ const lockedOriginalCertificate =
+ isRenewal && originalCertificateId
+ ? await lockRenewalOriginalCertificate(certificateDAL, originalCertificateId, tx, parsedFields.serialNumber)
+ : undefined;
+
const cert = await certificateDAL.create(
{
...parsedFields,
@@ -703,8 +712,8 @@ export const AwsAcmPublicCaCertificateAuthorityFns = ({
newCertId = cert.id;
- if (isRenewal && originalCertificateId) {
- await linkRenewedCertificate(certificateDAL, originalCertificateId, cert.id, tx);
+ if (lockedOriginalCertificate) {
+ await linkRenewedCertificate(certificateDAL, lockedOriginalCertificate, cert.id, tx);
}
await certificateBodyDAL.create(
diff --git a/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts
index c6e4e28c97..e79ee7bbfe 100644
--- a/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts
@@ -31,7 +31,8 @@ import { TCertificateBodyDALFactory } from "@app/services/certificate/certificat
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import {
extractExternallyIssuedCertificateFields,
- linkRenewedCertificate
+ linkRenewedCertificate,
+ lockRenewalOriginalCertificate
} from "@app/services/certificate/certificate-fns";
import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
import {
@@ -184,7 +185,10 @@ type TAwsPcaCertificateAuthorityFnsDeps = {
"create" | "transaction" | "findByIdWithAssociatedCa" | "updateById" | "findWithAssociatedCa" | "findById"
>;
externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "create" | "update">;
- certificateDAL: Pick<TCertificateDALFactory, "create" | "findById" | "transaction" | "updateById">;
+ certificateDAL: Pick<
+ TCertificateDALFactory,
+ "create" | "findById" | "findByIdForUpdate" | "transaction" | "updateById"
+ >;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
kmsService: Pick<
@@ -829,6 +833,11 @@ export const AwsPcaCertificateAuthorityFns = ({
const parsedFields = extractExternallyIssuedCertificateFields(certObj, customExtensions);
await certificateDAL.transaction(async (tx) => {
+ const lockedOriginalCertificate =
+ isRenewal && originalCertificateId
+ ? await lockRenewalOriginalCertificate(certificateDAL, originalCertificateId, tx, parsedFields.serialNumber)
+ : undefined;
+
const cert = await certificateDAL.create(
{
...parsedFields,
@@ -850,8 +859,8 @@ export const AwsPcaCertificateAuthorityFns = ({
certificateId = cert.id;
- if (isRenewal && originalCertificateId) {
- await linkRenewedCertificate(certificateDAL, originalCertificateId, cert.id, tx);
+ if (lockedOriginalCertificate) {
+ await linkRenewedCertificate(certificateDAL, lockedOriginalCertificate, cert.id, tx);
}
await certificateBodyDAL.create(
diff --git a/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts b/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts
index c1c729dd5e..3aa60b2ccd 100644
--- a/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts
@@ -20,6 +20,7 @@ import { TCertificateDALFactory } from "@app/services/certificate/certificate-da
import {
extractExternallyIssuedCertificateFields,
linkRenewedCertificate,
+ lockRenewalOriginalCertificate,
splitPemChain
} from "@app/services/certificate/certificate-fns";
import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
@@ -113,7 +114,10 @@ type TAzureAdCsCertificateAuthorityFnsDeps = {
"create" | "transaction" | "findByIdWithAssociatedCa" | "updateById" | "findWithAssociatedCa" | "findById"
>;
externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "create" | "update">;
- certificateDAL: Pick<TCertificateDALFactory, "create" | "findById" | "transaction" | "updateById">;
+ certificateDAL: Pick<
+ TCertificateDALFactory,
+ "create" | "findById" | "findByIdForUpdate" | "transaction" | "updateById"
+ >;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
kmsService: Pick<
@@ -1421,6 +1425,11 @@ export const AzureAdCsCertificateAuthorityFns = ({
const parsedFields = extractExternallyIssuedCertificateFields(certObj);
await certificateDAL.transaction(async (tx) => {
+ const lockedOriginalCertificate =
+ isRenewal && originalCertificateId
+ ? await lockRenewalOriginalCertificate(certificateDAL, originalCertificateId, tx, parsedFields.serialNumber)
+ : undefined;
+
const cert = await certificateDAL.create(
{
...parsedFields,
@@ -1442,8 +1451,8 @@ export const AzureAdCsCertificateAuthorityFns = ({
certificateId = cert.id;
- if (isRenewal && originalCertificateId) {
- await linkRenewedCertificate(certificateDAL, originalCertificateId, cert.id, tx);
+ if (lockedOriginalCertificate) {
+ await linkRenewedCertificate(certificateDAL, lockedOriginalCertificate, cert.id, tx);
}
await certificateBodyDAL.create(
diff --git a/backend/src/services/certificate-authority/certificate-authority-service.ts b/backend/src/services/certificate-authority/certificate-authority-service.ts
index f53f45bfdb..03da770625 100644
--- a/backend/src/services/certificate-authority/certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-service.ts
@@ -149,7 +149,10 @@ type TCertificateAuthorityServiceFactoryDep = {
projectDAL: Pick<TProjectDALFactory, "findProjectBySlug" | "findOne" | "updateById" | "findById" | "transaction">;
telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
- certificateDAL: Pick<TCertificateDALFactory, "create" | "findById" | "findOne" | "transaction" | "updateById">;
+ certificateDAL: Pick<
+ TCertificateDALFactory,
+ "create" | "findById" | "findByIdForUpdate" | "findOne" | "transaction" | "updateById"
+ >;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
kmsService: Pick<
@@ -1507,6 +1510,7 @@ export const certificateAuthorityServiceFactory = ({
ca.externalCa.type === CaType.GODADDY
? await processGoDaddyPendingValidationRequest(
{
+ certificateDAL,
certificateAuthorityDAL,
appConnectionDAL,
kmsService,
@@ -1523,6 +1527,7 @@ export const certificateAuthorityServiceFactory = ({
)
: await processDigiCertPendingValidationRequest(
{
+ certificateDAL,
certificateAuthorityDAL,
appConnectionDAL,
kmsService,
diff --git a/backend/src/services/certificate-authority/certificate-issuance-queue.ts b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
index e55637e31c..a4e30b09b1 100644
--- a/backend/src/services/certificate-authority/certificate-issuance-queue.ts
+++ b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
@@ -13,6 +13,7 @@ import {
TCertificateAlertEventEmitter
} from "@app/services/certificate/certificate-alert-events";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
+import { assertCertificateNotDeleted } from "@app/services/certificate/certificate-fns";
import {
CertExtendedKeyUsage,
CertKeyUsage,
@@ -445,6 +446,11 @@ export const certificateIssuanceQueueFactory = ({
});
}
+ if (isRenewal && originalCertificateId) {
+ const originalCertificate = await certificateDAL.findById(originalCertificateId);
+ if (originalCertificate) assertCertificateNotDeleted(originalCertificate);
+ }
+
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
if (customExtensions?.length) {
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 1282580d82..f2f8ba0fc4 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
@@ -16,7 +16,8 @@ import { TCertificateBodyDALFactory } from "@app/services/certificate/certificat
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import {
extractExternallyIssuedCertificateFields,
- linkRenewedCertificate
+ linkRenewedCertificate,
+ lockRenewalOriginalCertificate
} from "@app/services/certificate/certificate-fns";
import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
import { CertKeyAlgorithm, CertStatus, CrlReason, TAltNameType } from "@app/services/certificate/certificate-types";
@@ -62,7 +63,10 @@ type TDigiCertCertificateAuthorityFnsDeps = {
"create" | "transaction" | "findByIdWithAssociatedCa" | "updateById" | "findWithAssociatedCa" | "findById"
>;
externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "create" | "update">;
- certificateDAL: Pick<TCertificateDALFactory, "create" | "findById" | "transaction" | "updateById" | "findOne">;
+ certificateDAL: Pick<
+ TCertificateDALFactory,
+ "create" | "findById" | "findByIdForUpdate" | "transaction" | "updateById" | "findOne"
+ >;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
kmsService: Pick<
@@ -523,6 +527,11 @@ export const DigiCertCertificateAuthorityFns = ({
});
const createdCertificateId = await certificateDAL.transaction(async (tx) => {
+ const lockedOriginalCertificate =
+ isRenewal && originalCertificateId
+ ? await lockRenewalOriginalCertificate(certificateDAL, originalCertificateId, tx, parsedFields.serialNumber)
+ : undefined;
+
const cert = await certificateDAL.create(
{
...parsedFields,
@@ -546,8 +555,8 @@ export const DigiCertCertificateAuthorityFns = ({
tx
);
- if (isRenewal && originalCertificateId) {
- await linkRenewedCertificate(certificateDAL, originalCertificateId, cert.id, tx);
+ if (lockedOriginalCertificate) {
+ await linkRenewedCertificate(certificateDAL, lockedOriginalCertificate, cert.id, tx);
}
await certificateBodyDAL.create(
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 350684998f..bc356903ba 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
@@ -14,9 +14,11 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
+import { TCertificateDALFactory } from "../../certificate/certificate-dal";
import { CertificateIssuanceOperation, CertificateRequestStatus } from "../../certificate-common/certificate-constants";
import { reportCertificateIssued } from "../../certificate-common/certificate-telemetry-fns";
import { TCertificateRequestDALFactory } from "../../certificate-request/certificate-request-dal";
+import { failRenewalIfOriginalDeleted } from "../../certificate-request/certificate-request-fns";
import {
TAttachCertificateToRequestDTO,
TUpdateCertificateRequestStatusDTO
@@ -60,6 +62,7 @@ export type TDigiCertOrderMetadata = {
};
export type TProcessDigiCertRequestDeps = {
+ certificateDAL: Pick<TCertificateDALFactory, "findById">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
@@ -150,6 +153,18 @@ export const processDigiCertPendingValidationRequest = async (
return { status: CertificateRequestStatus.FAILED, orderStatus: "timeout", reason: "timeout" };
}
+ const abandonedRenewal =
+ parsed.digicert.isRenewal && parsed.digicert.originalCertificateId
+ ? await failRenewalIfOriginalDeleted({
+ certificateDAL: deps.certificateDAL,
+ certificateRequestService: deps.certificateRequestService,
+ certificateRequestId: request.id,
+ originalCertificateId: parsed.digicert.originalCertificateId,
+ upstreamOrderReference: `DigiCert order ${parsed.digicert.orderId}`
+ })
+ : null;
+ if (abandonedRenewal) return abandonedRenewal;
+
const client = await getOrCreateClient(request, deps, clientCache);
const orderInfo = await client.getOrder(parsed.digicert.orderId);
diff --git a/backend/src/services/certificate-authority/digicert/digicert-code-signing-fns.ts b/backend/src/services/certificate-authority/digicert/digicert-code-signing-fns.ts
index 26abdd35be..c664d530f0 100644
--- a/backend/src/services/certificate-authority/digicert/digicert-code-signing-fns.ts
+++ b/backend/src/services/certificate-authority/digicert/digicert-code-signing-fns.ts
@@ -11,7 +11,10 @@ import {
} from "@app/services/app-connection/digicert/digicert-connection-fns";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
-import { extractExternallyIssuedCertificateFields } from "@app/services/certificate/certificate-fns";
+import {
+ extractExternallyIssuedCertificateFields,
+ getCertificateDeletedMessage
+} from "@app/services/certificate/certificate-fns";
import { CertStatus } from "@app/services/certificate/certificate-types";
import { TDigiCertExternalMetadata } from "@app/services/certificate-common/external-metadata-schemas";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -367,6 +370,14 @@ export const digiCertCodeSigningFns = ({
});
const existingCert = await certificateDAL.findOne({ serialNumber: certObj.serialNumber });
+ if (existingCert?.deletedAt) {
+ throw new BadRequestError({
+ message: getCertificateDeletedMessage(
+ { ...existingCert, deletedAt: existingCert.deletedAt },
+ "be downloaded. Request a new code signing certificate instead"
+ )
+ });
+ }
if (existingCert) {
if (existingCert.caId !== ca.id) throw differentCaError;
return { certificatePem: leaf, existingCertificateId: existingCert.id, insert: null };
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..3813bb921b 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
@@ -62,6 +62,7 @@ export const digicertRevocationSyncQueueFactory = ({
serialNumber: string;
projectId: string;
applicationId?: string | null;
+ deletedAt?: Date | null;
}) => {
await certificateDAL.updateById(cert.id, {
status: CertStatus.REVOKED,
@@ -69,12 +70,14 @@ export const digicertRevocationSyncQueueFactory = ({
revocationReason: revocationReasonToCrlCode(CrlReason.UNSPECIFIED)
});
- await certificateAlertEventEmitter.notify({
- certificateId: cert.id,
- projectId: cert.projectId,
- eventType: CertificateApplicationAlertEvent.Revocation,
- applicationId: cert.applicationId ?? null
- });
+ if (!cert.deletedAt) {
+ await certificateAlertEventEmitter.notify({
+ certificateId: cert.id,
+ projectId: cert.projectId,
+ eventType: CertificateApplicationAlertEvent.Revocation,
+ applicationId: cert.applicationId ?? null
+ });
+ }
await auditLogService.createAuditLog({
projectId: cert.projectId,
@@ -90,6 +93,8 @@ export const digicertRevocationSyncQueueFactory = ({
}
});
+ if (cert.deletedAt) return;
+
try {
await pkiAlertV2Queue?.queueCertificateEvent({
certificateId: cert.id,
diff --git a/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-fns.ts b/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-fns.ts
index 6c5a0aefcc..e605218fa0 100644
--- a/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-fns.ts
@@ -19,7 +19,8 @@ import { TCertificateBodyDALFactory } from "@app/services/certificate/certificat
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import {
extractExternallyIssuedCertificateFields,
- linkRenewedCertificate
+ linkRenewedCertificate,
+ lockRenewalOriginalCertificate
} from "@app/services/certificate/certificate-fns";
import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
import { CertKeyAlgorithm, CertStatus, CrlReason } from "@app/services/certificate/certificate-types";
@@ -53,7 +54,10 @@ type TGoDaddyCertificateAuthorityFnsDeps = {
"create" | "transaction" | "findByIdWithAssociatedCa" | "updateById" | "findWithAssociatedCa" | "findById"
>;
externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "create" | "update">;
- certificateDAL: Pick<TCertificateDALFactory, "create" | "findById" | "transaction" | "updateById" | "findOne">;
+ certificateDAL: Pick<
+ TCertificateDALFactory,
+ "create" | "findById" | "findByIdForUpdate" | "transaction" | "updateById" | "findOne"
+ >;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
kmsService: Pick<
@@ -554,6 +558,11 @@ export const GoDaddyCertificateAuthorityFns = ({
});
const createdCertificateId = await certificateDAL.transaction(async (tx) => {
+ const lockedOriginalCertificate =
+ isRenewal && originalCertificateId
+ ? await lockRenewalOriginalCertificate(certificateDAL, originalCertificateId, tx, parsedFields.serialNumber)
+ : undefined;
+
const cert = await certificateDAL.create(
{
...parsedFields,
@@ -577,8 +586,8 @@ export const GoDaddyCertificateAuthorityFns = ({
tx
);
- if (isRenewal && originalCertificateId) {
- await linkRenewedCertificate(certificateDAL, originalCertificateId, cert.id, tx);
+ if (lockedOriginalCertificate) {
+ await linkRenewedCertificate(certificateDAL, lockedOriginalCertificate, cert.id, tx);
}
await certificateBodyDAL.create(
diff --git a/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-processor.ts b/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-processor.ts
index fde6510be1..9c746af99a 100644
--- a/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-processor.ts
+++ b/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-processor.ts
@@ -15,9 +15,11 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
+import { TCertificateDALFactory } from "../../certificate/certificate-dal";
import { CertificateIssuanceOperation, CertificateRequestStatus } from "../../certificate-common/certificate-constants";
import { reportCertificateIssued } from "../../certificate-common/certificate-telemetry-fns";
import { TCertificateRequestDALFactory } from "../../certificate-request/certificate-request-dal";
+import { failRenewalIfOriginalDeleted } from "../../certificate-request/certificate-request-fns";
import {
TAttachCertificateToRequestDTO,
TUpdateCertificateRequestStatusDTO
@@ -60,6 +62,7 @@ export type TGoDaddyCertificateRequestServiceDep = {
};
export type TProcessGoDaddyRequestDeps = {
+ certificateDAL: Pick<TCertificateDALFactory, "findById">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
@@ -153,6 +156,18 @@ export const processGoDaddyPendingValidationRequest = async (
return { status: CertificateRequestStatus.FAILED, orderStatus: "timeout", reason: "timeout" };
}
+ const abandonedRenewal =
+ parsed.godaddy.isRenewal && parsed.godaddy.originalCertificateId
+ ? await failRenewalIfOriginalDeleted({
+ certificateDAL: deps.certificateDAL,
+ certificateRequestService: deps.certificateRequestService,
+ certificateRequestId: request.id,
+ originalCertificateId: parsed.godaddy.originalCertificateId,
+ upstreamOrderReference: `GoDaddy certificate ${parsed.godaddy.certificateId}`
+ })
+ : null;
+ if (abandonedRenewal) return abandonedRenewal;
+
const client = await getOrCreateClient(request, deps, clientCache);
const certificateInfo = await client.getCertificate(parsed.godaddy.certificateId);
diff --git a/backend/src/services/certificate-authority/venafi-tpp/venafi-tpp-certificate-authority-fns.ts b/backend/src/services/certificate-authority/venafi-tpp/venafi-tpp-certificate-authority-fns.ts
index e56558b857..9cb4cbf75e 100644
--- a/backend/src/services/certificate-authority/venafi-tpp/venafi-tpp-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/venafi-tpp/venafi-tpp-certificate-authority-fns.ts
@@ -26,6 +26,7 @@ import { TCertificateDALFactory } from "@app/services/certificate/certificate-da
import {
extractExternallyIssuedCertificateFields,
linkRenewedCertificate,
+ lockRenewalOriginalCertificate,
splitPemChain
} from "@app/services/certificate/certificate-fns";
import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
@@ -348,7 +349,10 @@ type TVenafiTppCertificateAuthorityFnsDeps = {
"create" | "transaction" | "findByIdWithAssociatedCa" | "updateById" | "findWithAssociatedCa" | "findById"
>;
externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "create" | "update">;
- certificateDAL: Pick<TCertificateDALFactory, "create" | "findById" | "transaction" | "updateById">;
+ certificateDAL: Pick<
+ TCertificateDALFactory,
+ "create" | "findById" | "findByIdForUpdate" | "transaction" | "updateById"
+ >;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey" | "createCipherPairWithDataKey">;
@@ -848,6 +852,11 @@ export const VenafiTppCertificateAuthorityFns = ({
const parsedFields = extractExternallyIssuedCertificateFields(certObj);
await certificateDAL.transaction(async (tx) => {
+ const lockedOriginalCertificate =
+ isRenewal && originalCertificateId
+ ? await lockRenewalOriginalCertificate(certificateDAL, originalCertificateId, tx, parsedFields.serialNumber)
+ : undefined;
+
const cert = await certificateDAL.create(
{
...parsedFields,
@@ -869,8 +878,8 @@ export const VenafiTppCertificateAuthorityFns = ({
certificateId = cert.id;
- if (isRenewal && originalCertificateId) {
- await linkRenewedCertificate(certificateDAL, originalCertificateId, cert.id, tx);
+ if (lockedOriginalCertificate) {
+ await linkRenewedCertificate(certificateDAL, lockedOriginalCertificate, cert.id, tx);
}
await certificateBodyDAL.create(
diff --git a/backend/src/services/certificate-est-v3/certificate-est-v3-service.test.ts b/backend/src/services/certificate-est-v3/certificate-est-v3-service.test.ts
index bb2b803061..71feab549a 100644
--- a/backend/src/services/certificate-est-v3/certificate-est-v3-service.test.ts
+++ b/backend/src/services/certificate-est-v3/certificate-est-v3-service.test.ts
@@ -518,6 +518,25 @@ describe("CertificateEstV3Service", () => {
expect(mockCertificateV3Service.signCertificateFromProfile).not.toHaveBeenCalled();
});
+
+ it("should reject re-enrollment when the client certificate was deleted", async () => {
+ mockCertificateDAL.findOne.mockResolvedValue({
+ status: CertStatus.ACTIVE,
+ deletedAt: new Date(),
+ commonName: "device.example.com",
+ serialNumber: "01"
+ });
+
+ await expect(
+ service.simpleReenrollByProfile({
+ csr: "mock-csr",
+ profileId: "profile-123",
+ sslClientCert: encodeURIComponent("-----BEGIN CERTIFICATE-----\nMIIB...\n-----END CERTIFICATE-----")
+ })
+ ).rejects.toThrow("was deleted and can no longer be re-enrolled");
+
+ expect(mockCertificateV3Service.signCertificateFromProfile).not.toHaveBeenCalled();
+ });
});
describe("getCaCertsByProfile", () => {
diff --git a/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts b/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts
index eef5ed2665..7e9617212a 100644
--- a/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts
+++ b/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts
@@ -370,6 +370,12 @@ export const certificateEstV3ServiceFactory = ({
throw new UnauthorizedError({ message: "Client certificate has been revoked" });
}
+ if (storedCert?.deletedAt) {
+ throw new UnauthorizedError({
+ message: `Client certificate with serial number '${cert.serialNumber}' was deleted and can no longer be re-enrolled. Enroll a new certificate instead.`
+ });
+ }
+
const $rejectReenrollCsr = async (message: string) => {
const error = new BadRequestError({ message });
await $recordEstFailure({
diff --git a/backend/src/services/certificate-inventory-view/certificate-inventory-view-service.ts b/backend/src/services/certificate-inventory-view/certificate-inventory-view-service.ts
index 9687ea225c..c020fc1221 100644
--- a/backend/src/services/certificate-inventory-view/certificate-inventory-view-service.ts
+++ b/backend/src/services/certificate-inventory-view/certificate-inventory-view-service.ts
@@ -74,6 +74,14 @@ const SYSTEM_VIEWS: TSystemView[] = [
isSystem: true,
createdByUserId: null
},
+ {
+ id: "system-deleted",
+ name: "Deleted",
+ filters: { status: ["deleted"] },
+ columns: null,
+ isSystem: true,
+ createdByUserId: null
+ },
{
id: "system-pqc",
name: "Post-Quantum (PQC)",
diff --git a/backend/src/services/certificate-profile/certificate-profile-dal.ts b/backend/src/services/certificate-profile/certificate-profile-dal.ts
index fb5e4c79f1..20f46a6f9c 100644
--- a/backend/src/services/certificate-profile/certificate-profile-dal.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-dal.ts
@@ -699,6 +699,8 @@ export const certificateProfileDALFactory = (db: TDbClient) => {
});
}
+ query = status === CertStatus.DELETED ? query.whereNotNull("deletedAt") : query.whereNull("deletedAt");
+
if (status) {
switch (status) {
case CertStatus.ACTIVE:
@@ -727,13 +729,15 @@ export const certificateProfileDALFactory = (db: TDbClient) => {
.select((tx || db).ref("notAfter").withSchema(TableName.Certificate))
.select((tx || db).ref("revokedAt").withSchema(TableName.Certificate))
.select((tx || db).ref("createdAt").withSchema(TableName.Certificate))
+ .select((tx || db).ref("deletedAt").withSchema(TableName.Certificate))
.orderBy("createdAt", "desc")
.offset(offset)
.limit(limit);
return certificates.map((cert) => ({
...cert,
- revokedAt: cert.revokedAt ?? null
+ revokedAt: cert.revokedAt ?? null,
+ deletedAt: cert.deletedAt ?? null
}));
} catch (error) {
throw new DatabaseError({ error, name: "Get certificates by profile" });
@@ -749,6 +753,7 @@ export const certificateProfileDALFactory = (db: TDbClient) => {
.where("status", "active")
.where("notAfter", ">", now)
.whereNull("revokedAt")
+ .whereNull("deletedAt")
.orderBy("createdAt", "desc")
.first();
diff --git a/backend/src/services/certificate-profile/certificate-profile-types.ts b/backend/src/services/certificate-profile/certificate-profile-types.ts
index 1ac020b20e..d53546945b 100644
--- a/backend/src/services/certificate-profile/certificate-profile-types.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-types.ts
@@ -155,5 +155,6 @@ export interface TCertificateProfileCertificate {
notBefore: Date;
notAfter: Date;
revokedAt: Date | null;
+ deletedAt: Date | null;
createdAt: Date;
}
diff --git a/backend/src/services/certificate-request/certificate-request-dal.ts b/backend/src/services/certificate-request/certificate-request-dal.ts
index 1873b5d1cd..e7b4b74168 100644
--- a/backend/src/services/certificate-request/certificate-request-dal.ts
+++ b/backend/src/services/certificate-request/certificate-request-dal.ts
@@ -10,6 +10,7 @@ import {
type ProcessedPermissionRules
} from "@app/lib/knex/permission-filter-utils";
import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
+import { CertStatus } from "@app/services/certificate/certificate-types";
import { CaStatus } from "@app/services/certificate-authority/certificate-authority-enums";
import { applyMetadataFilter } from "@app/services/resource-metadata/resource-metadata-fns";
@@ -35,6 +36,7 @@ type TCertificateRequestQueryResult = TCertificateRequests & {
certId: string | null;
certSerialNumber: string | null;
certStatus: string | null;
+ certDeletedAt: Date | null;
profileName: string | null;
};
@@ -62,17 +64,19 @@ export const certificateRequestDALFactory = (db: TDbClient) => {
.select(db.ref("id").withSchema(TableName.Certificate).as("certId"))
.select(db.ref("serialNumber").withSchema(TableName.Certificate).as("certSerialNumber"))
.select(db.ref("status").withSchema(TableName.Certificate).as("certStatus"))
+ .select(db.ref("deletedAt").withSchema(TableName.Certificate).as("certDeletedAt"))
.first()) as TCertificateRequestQueryResult | undefined;
if (!result) return null;
- const { certId, certSerialNumber, certStatus, profileName, ...certificateRequestData } = result;
+ const { certId, certSerialNumber, certStatus, certDeletedAt, profileName, ...certificateRequestData } = result;
const certificate: TCertificates | null = certId
? ({
id: certId,
serialNumber: certSerialNumber,
- status: certStatus
+ status: certStatus,
+ deletedAt: certDeletedAt
} as TCertificates)
: null;
@@ -391,6 +395,7 @@ export const certificateRequestDALFactory = (db: TDbClient) => {
.select(db.ref("id").withSchema(TableName.Certificate).as("certId"))
.select(db.ref("serialNumber").withSchema(TableName.Certificate).as("certSerialNumber"))
.select(db.ref("status").withSchema(TableName.Certificate).as("certStatus"))
+ .select(db.ref("deletedAt").withSchema(TableName.Certificate).as("certDeletedAt"))
.where(`${TableName.CertificateRequests}.projectId`, projectId);
if (search) {
@@ -433,13 +438,20 @@ export const certificateRequestDALFactory = (db: TDbClient) => {
.limit(limit)) as TCertificateRequestQueryResult[];
return results.map((row): TCertificateRequestWithCertificate => {
- const { certId, certSerialNumber, certStatus, profileName: rowProfileName, ...certificateRequestData } = row;
+ const {
+ certId,
+ certSerialNumber,
+ certStatus,
+ certDeletedAt,
+ profileName: rowProfileName,
+ ...certificateRequestData
+ } = row;
const certificate: TCertificates | null = certId
? ({
id: certId,
serialNumber: certSerialNumber,
- status: certStatus
+ status: certDeletedAt ? CertStatus.DELETED : certStatus
} as TCertificates)
: null;
diff --git a/backend/src/services/certificate-request/certificate-request-fns.ts b/backend/src/services/certificate-request/certificate-request-fns.ts
index eea3c1d5ff..390200f738 100644
--- a/backend/src/services/certificate-request/certificate-request-fns.ts
+++ b/backend/src/services/certificate-request/certificate-request-fns.ts
@@ -5,6 +5,8 @@ import { InternalServerError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { ActorType } from "../auth/auth-type";
+import { TCertificateDALFactory } from "../certificate/certificate-dal";
+import { getCertificateDeletedMessage } from "../certificate/certificate-fns";
import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";
import { CaType } from "../certificate-authority/certificate-authority-enums";
import { caUsesExternalIssuanceQueue } from "../certificate-authority/certificate-authority-maps";
@@ -17,7 +19,7 @@ import {
import { TCertificateProfileDALFactory } from "../certificate-profile/certificate-profile-dal";
import { EnrollmentType } from "../certificate-profile/certificate-profile-types";
import { TCertificateRequestDALFactory } from "./certificate-request-dal";
-import { CertificateRequestStatus } from "./certificate-request-types";
+import { CertificateRequestStatus, TUpdateCertificateRequestStatusDTO } from "./certificate-request-types";
type TCertificateRequestBookkeepingDAL = Pick<
TCertificateRequestDALFactory,
@@ -73,6 +75,41 @@ export const markPendingRequestFailed = async (
}
};
+export const failRenewalIfOriginalDeleted = async ({
+ certificateDAL,
+ certificateRequestService,
+ certificateRequestId,
+ originalCertificateId,
+ upstreamOrderReference
+}: {
+ certificateDAL: Pick<TCertificateDALFactory, "findById">;
+ certificateRequestService: {
+ updateCertificateRequestStatus: (args: TUpdateCertificateRequestStatusDTO) => Promise<unknown>;
+ };
+ certificateRequestId: string;
+ originalCertificateId: string;
+ upstreamOrderReference: string;
+}) => {
+ const originalCertificate = await certificateDAL.findById(originalCertificateId);
+ if (!originalCertificate?.deletedAt) return null;
+
+ await certificateRequestService.updateCertificateRequestStatus({
+ certificateRequestId,
+ status: CertificateRequestStatus.FAILED,
+ operation: CertificateIssuanceOperation.RENEW,
+ originalCertificateId,
+ errorMessage: `${getCertificateDeletedMessage({ ...originalCertificate, deletedAt: originalCertificate.deletedAt })} Cancel ${upstreamOrderReference} with the certificate authority if you no longer need it.`
+ });
+ logger.info(
+ `Renewal abandoned because the original certificate was deleted [certificateRequestId=${certificateRequestId}] [originalCertificateId=${originalCertificateId}]`
+ );
+ return {
+ status: CertificateRequestStatus.FAILED as const,
+ orderStatus: "original-deleted",
+ reason: "original certificate deleted"
+ };
+};
+
export type TRecordCertificateRequestFailureDeps = Omit<
TRecordCertificateIssuanceFailureDeps,
"certificateAuthorityDAL"
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 2cc72175db..4121d38cc2 100644
--- a/backend/src/services/certificate-request/certificate-request-service.test.ts
+++ b/backend/src/services/certificate-request/certificate-request-service.test.ts
@@ -331,6 +331,44 @@ describe("CertificateRequestService", () => {
expect(projectId).toEqual("550e8400-e29b-41d4-a716-446655440003");
});
+ it("returns the deleted certificate's id and serial number but no certificate body", async () => {
+ const mockPermission = {
+ permission: createMongoAbility<ProjectPermissionSet>([
+ {
+ action: ProjectPermissionCertificateActions.Read,
+ subject: ProjectPermissionSub.Certificates
+ }
+ ])
+ };
+ const mockRequestWithDeletedCert = {
+ id: "550e8400-e29b-41d4-a716-446655440008",
+ projectId: "550e8400-e29b-41d4-a716-446655440003",
+ status: CertificateRequestStatus.ISSUED,
+ certificate: {
+ id: "550e8400-e29b-41d4-a716-446655440009",
+ serialNumber: "0a1b2c",
+ deletedAt: new Date("2026-10-20T14:38:27.000Z")
+ },
+ errorMessage: null,
+ createdAt: new Date(),
+ updatedAt: new Date()
+ };
+
+ (mockPermissionService.getProjectPermission as any).mockResolvedValue(mockPermission);
+ (mockCertificateRequestDAL.findByIdWithCertificate as any).mockResolvedValue(mockRequestWithDeletedCert);
+
+ const { certificateRequest } = await service.getCertificateFromRequest(mockGetData);
+
+ expect(certificateRequest).toMatchObject({
+ status: CertificateRequestStatus.ISSUED,
+ certificateId: "550e8400-e29b-41d4-a716-446655440009",
+ serialNumber: "0a1b2c",
+ certificate: null,
+ privateKey: null
+ });
+ expect(mockCertificateService.getCertBody).not.toHaveBeenCalled();
+ });
+
it("should get certificate from request successfully when no certificate is attached", async () => {
const mockPermission = {
permission: createMongoAbility<ProjectPermissionSet>([
@@ -361,6 +399,7 @@ describe("CertificateRequestService", () => {
certificate: null,
privateKey: null,
serialNumber: null,
+ certificateDeletedAt: null,
errorMessage: null,
pendingMessage: null,
commonName: null,
@@ -556,6 +595,7 @@ describe("CertificateRequestService", () => {
certificateId: null,
privateKey: null,
serialNumber: null,
+ certificateDeletedAt: null,
errorMessage: "Certificate issuance failed",
pendingMessage: null,
commonName: null,
diff --git a/backend/src/services/certificate-request/certificate-request-service.ts b/backend/src/services/certificate-request/certificate-request-service.ts
index 2d6ee1fad2..027b152203 100644
--- a/backend/src/services/certificate-request/certificate-request-service.ts
+++ b/backend/src/services/certificate-request/certificate-request-service.ts
@@ -366,14 +366,15 @@ export const certificateRequestServiceFactory = ({
} | null;
// If no certificate is attached, return basic info
- if (!certificateRequest.certificate) {
+ if (!certificateRequest.certificate || certificateRequest.certificate.deletedAt) {
return {
certificateRequest: {
status: certificateRequest.status as CertificateRequestStatus,
certificate: null,
- certificateId: null,
+ certificateId: certificateRequest.certificate?.id ?? null,
privateKey: null,
- serialNumber: null,
+ serialNumber: certificateRequest.certificate?.serialNumber ?? null,
+ certificateDeletedAt: certificateRequest.certificate?.deletedAt ?? null,
errorMessage: certificateRequest.errorMessage || null,
pendingMessage: certificateRequest.pendingMessage || null,
commonName: certificateRequest.commonName || null,
diff --git a/backend/src/services/certificate-v3/certificate-renewal-service.ts b/backend/src/services/certificate-v3/certificate-renewal-service.ts
index aa887570e6..313887e648 100644
--- a/backend/src/services/certificate-v3/certificate-renewal-service.ts
+++ b/backend/src/services/certificate-v3/certificate-renewal-service.ts
@@ -20,6 +20,7 @@ import {
} from "@app/services/certificate/certificate-alert-events";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory, TOriginatingCertificateRequest } from "@app/services/certificate/certificate-dal";
+import { assertCertificateNotDeleted, lockRenewalOriginalCertificate } from "@app/services/certificate/certificate-fns";
import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
import { CertKeyAlgorithm, CertSignatureAlgorithm, CertStatus } from "@app/services/certificate/certificate-types";
import {
@@ -136,6 +137,7 @@ type TCertificateRenewalServiceFactoryDep = {
certificateDAL: Pick<
TCertificateDALFactory,
| "findById"
+ | "findByIdForUpdate"
| "updateById"
| "transaction"
| "create"
@@ -265,6 +267,8 @@ export const certificateRenewalServiceFactory = ({
},
tx: Knex
) => {
+ await lockRenewalOriginalCertificate(certificateDAL, originalCert.id, tx);
+
const renewalUpdate: {
profileId?: string | null;
renewedFromCertificateId?: string;
@@ -587,7 +591,7 @@ export const certificateRenewalServiceFactory = ({
{ certificateId, keySource }: { certificateId: string; keySource: CertificateRenewalKeySource },
tx: Knex
) => {
- const originalCert = await certificateDAL.findById(certificateId, tx);
+ const originalCert = await certificateDAL.findByIdForUpdate(certificateId, tx);
if (!originalCert) {
throw new NotFoundError({ message: "Certificate not found" });
}
@@ -1120,6 +1124,8 @@ export const certificateRenewalServiceFactory = ({
? undefined
: await $authorizeRenewal({ originalCert, profile, actorCtx, isEditingCertificate }, tx);
+ assertCertificateNotDeleted(originalCert);
+
const { issuerType, ca, caType, policy } = await $resolveRenewalIssuer(
{
originalCert,
@@ -1537,6 +1543,8 @@ export const certificateRenewalServiceFactory = ({
resourceMetadataDAL
});
+ assertCertificateNotDeleted(certificate);
+
if (!certificate.profileId) {
throw new BadRequestError({
message: "Certificate is not eligible for auto-renewal: certificate was not issued from a profile"
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 d745d5872c..6f0e8a2951 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
@@ -91,6 +91,7 @@ describe("CertificateV3Service", () => {
TCertificateDALFactory,
| "findOne"
| "findById"
+ | "findByIdForUpdate"
| "updateById"
| "transaction"
| "create"
@@ -102,6 +103,7 @@ describe("CertificateV3Service", () => {
> = {
findOne: vi.fn(),
findById: vi.fn(),
+ findByIdForUpdate: vi.fn(),
findCertificatesMatchingSyncFilters: vi.fn().mockResolvedValue([]),
findActiveCertificatesByIds: vi.fn().mockResolvedValue([]),
updateById: vi.fn(),
@@ -262,6 +264,7 @@ describe("CertificateV3Service", () => {
const mockTx = {};
return callback(mockTx);
});
+ vi.mocked(mockCertificateDAL.findByIdForUpdate).mockImplementation((id: string) => mockCertificateDAL.findById(id));
vi.mocked(mockCertificateDAL.getRequestEnrollmentTypeByCertId).mockResolvedValue(null);
vi.mocked(mockCertificateDAL.getOriginatingRequestByCertId).mockResolvedValue({
enrollmentType: null,
@@ -3133,6 +3136,28 @@ describe("CertificateV3Service", () => {
).rejects.toThrow("Certificate is revoked and cannot be renewed");
});
+ it("should reject renewal if certificate is deleted", async () => {
+ const deletedCert = {
+ ...mockOriginalCert,
+ deletedAt: new Date("2026-10-20T14:38:27.000Z")
+ };
+ vi.mocked(mockCertificateDAL.findById).mockResolvedValue(deletedCert);
+ vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
+ vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
+ vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);
+ vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(deletedCert);
+ vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) =>
+ callback({})
+ );
+
+ await expect(
+ service.renewCertificate({
+ certificateId: "cert-123",
+ ...mockActor
+ })
+ ).rejects.toThrow("was deleted on 2026-10-20T14:38:27.000Z and can no longer be renewed or changed");
+ });
+
it("should reject renewal if CA is inactive", async () => {
const inactiveCA = { ...mockCA, status: CaStatus.DISABLED };
vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert);
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index 89ce692f1a..c209e1e42d 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -37,6 +37,7 @@ import {
} 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 { assertCertificateNotDeleted } from "@app/services/certificate/certificate-fns";
import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
import { CertKeyAlgorithm, CertSignatureAlgorithm } from "@app/services/certificate/certificate-types";
import { validateAcmIssuanceInputs } from "@app/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns";
@@ -140,6 +141,7 @@ type TCertificateV3ServiceFactoryDep = {
TCertificateDALFactory,
| "findOne"
| "findById"
+ | "findByIdForUpdate"
| "updateById"
| "transaction"
| "create"
@@ -2322,6 +2324,8 @@ export const certificateV3ServiceFactory = ({
resourceMetadataDAL
});
+ assertCertificateNotDeleted(certificate);
+
if (metadata && projectPermission) {
assertCanEditCertificateResult({
projectPermission,
diff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.ts
index ae14d20a1d..b7e01f9113 100644
--- a/backend/src/services/certificate/certificate-dal.ts
+++ b/backend/src/services/certificate/certificate-dal.ts
@@ -1,7 +1,7 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
-import { TableName, TCertificates, TCertificatesInsert } from "@app/db/schemas";
+import { TableName, TCertificates, TCertificatesInsert, TCertificatesUpdate } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { sanitizeSqlLikeString } from "@app/lib/fn/string";
import { ormify, selectAllTableCols } from "@app/lib/knex";
@@ -20,6 +20,7 @@ import {
certificateHasWildcard
} from "@app/services/certificate-common/certificate-quota-key";
import { applyMetadataFilter } from "@app/services/resource-metadata/resource-metadata-fns";
+import { CertKeySource } from "@app/services/signer/signer-enums";
import { keySizeToAlgorithms } from "./certificate-fns";
import { CertKeyAlgorithm, CertStatus } from "./certificate-types";
@@ -83,12 +84,45 @@ export const certificateDALFactory = (db: TDbClient) => {
tx
);
+ const restoreDeleted = async (
+ id: string,
+ data: Omit<TCertificatesUpdate, "quotaKey" | "hasWildcard" | "status" | "revokedAt" | "revocationReason"> & {
+ commonName: string;
+ },
+ tx: Knex
+ ): Promise<TCertificates | undefined> => {
+ try {
+ const [restored] = (await tx(TableName.Certificate)
+ .where({ id })
+ .whereNotNull("deletedAt")
+ .update({
+ ...data,
+ quotaKey: buildCertificateQuotaKey({ commonName: data.commonName, altNames: data.altNames }),
+ hasWildcard: certificateHasWildcard({ commonName: data.commonName, altNames: data.altNames }),
+ keySource: CertKeySource.Infisical,
+ hsmConnectorId: null,
+ hsmKeyLabel: null,
+ hsmKeyId: null,
+ hsmPublicKeySpki: null,
+ deletedAt: null,
+ deletedByActorType: null,
+ deletedByActorId: null,
+ deletedVia: null
+ })
+ .returning("*")) as TCertificates[];
+ return restored;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Restore deleted certificate" });
+ }
+ };
+
const findLatestActiveCertForSubscriber = async ({ subscriberId }: { subscriberId: string }) => {
try {
const cert = await db
.replicaNode()(TableName.Certificate)
.where({ pkiSubscriberId: subscriberId, status: CertStatus.ACTIVE })
.where("notAfter", ">", new Date())
+ .whereNull("deletedAt")
.orderBy("notBefore", "desc")
.first();
@@ -104,6 +138,7 @@ export const certificateDALFactory = (db: TDbClient) => {
.replicaNode()(TableName.Certificate)
.where({ pkiSubscriberId: subscriberId, status: CertStatus.ACTIVE })
.where("notAfter", ">", new Date())
+ .whereNull("deletedAt")
.orderBy("notBefore", "desc");
return certs;
@@ -122,7 +157,7 @@ export const certificateDALFactory = (db: TDbClient) => {
.where({ caId, status: CertStatus.ACTIVE })
.whereRaw(`"externalMetadata"->>'type' = ?`, ["digicert"])
.whereRaw(`("externalMetadata"->>'orderId') IN (${placeholders})`, stringIds)
- .select("id", "commonName", "serialNumber", "projectId", "applicationId");
+ .select("id", "commonName", "serialNumber", "projectId", "applicationId", "deletedAt");
return certs;
} catch (error) {
@@ -152,6 +187,7 @@ export const certificateDALFactory = (db: TDbClient) => {
notBeforeTo?: Date;
applicationId?: string;
applicationIds?: string[];
+ includeDeleted?: boolean;
};
type TSyncEligibilityFilterParams = Omit<TInventoryFilterParams, "status">;
@@ -204,6 +240,10 @@ export const certificateDALFactory = (db: TDbClient) => {
});
}
+ if (!filters.status && !filters.includeDeleted) {
+ q = q.whereNull(`${TableName.Certificate}.deletedAt`);
+ }
+
if (filters.status) {
const now = new Date();
const statuses = Array.isArray(filters.status) ? filters.status : [filters.status];
@@ -212,28 +252,39 @@ export const certificateDALFactory = (db: TDbClient) => {
statuses.forEach((statusValue, index) => {
const whereMethod = index === 0 ? "where" : "orWhere";
- if (statusValue === CertStatus.ACTIVE) {
+ if (statusValue === CertStatus.DELETED) {
+ void qb[whereMethod]((innerQb: Knex.QueryBuilder) => {
+ void innerQb.whereNotNull(`${TableName.Certificate}.deletedAt`);
+ });
+ } else if (statusValue === CertStatus.ACTIVE) {
void qb[whereMethod]((innerQb: Knex.QueryBuilder) => {
void innerQb
.where(`${TableName.Certificate}.notAfter`, ">", now)
.andWhere(`${TableName.Certificate}.status`, "!=", CertStatus.REVOKED)
- .whereNull(`${TableName.Certificate}.renewedByCertificateId`);
+ .whereNull(`${TableName.Certificate}.renewedByCertificateId`)
+ .whereNull(`${TableName.Certificate}.deletedAt`);
});
} else if (statusValue === CertStatus.RENEWED) {
void qb[whereMethod]((innerQb: Knex.QueryBuilder) => {
void innerQb
.where(`${TableName.Certificate}.notAfter`, ">", now)
.andWhere(`${TableName.Certificate}.status`, "!=", CertStatus.REVOKED)
- .whereNotNull(`${TableName.Certificate}.renewedByCertificateId`);
+ .whereNotNull(`${TableName.Certificate}.renewedByCertificateId`)
+ .whereNull(`${TableName.Certificate}.deletedAt`);
});
} else if (statusValue === CertStatus.EXPIRED) {
void qb[whereMethod]((innerQb: Knex.QueryBuilder) => {
void innerQb
.where(`${TableName.Certificate}.notAfter`, "<=", now)
- .andWhere(`${TableName.Certificate}.status`, "!=", CertStatus.REVOKED);
+ .andWhere(`${TableName.Certificate}.status`, "!=", CertStatus.REVOKED)
+ .whereNull(`${TableName.Certificate}.deletedAt`);
});
} else {
- void qb[whereMethod](`${TableName.Certificate}.status`, statusValue);
+ void qb[whereMethod]((innerQb: Knex.QueryBuilder) => {
+ void innerQb
+ .where(`${TableName.Certificate}.status`, statusValue)
+ .whereNull(`${TableName.Certificate}.deletedAt`);
+ });
}
});
});
@@ -420,7 +471,8 @@ export const certificateDALFactory = (db: TDbClient) => {
.replicaNode()(TableName.Certificate)
.where("notAfter", ">=", yesterday)
.where("notAfter", "<", today)
- .whereNotNull("pkiSubscriberId");
+ .whereNotNull("pkiSubscriberId")
+ .whereNull("deletedAt");
return certs;
} catch (error) {
@@ -466,6 +518,7 @@ export const certificateDALFactory = (db: TDbClient) => {
.where({ status: CertStatus.ACTIVE })
.where("notAfter", ">", new Date())
.whereNull("renewedByCertificateId")
+ .whereNull("deletedAt")
.orderBy("notBefore", "desc")
.select("*");
@@ -479,7 +532,8 @@ export const certificateDALFactory = (db: TDbClient) => {
query
.where(`${TableName.Certificate}.status`, CertStatus.ACTIVE)
.where(`${TableName.Certificate}.notAfter`, ">", new Date())
- .whereNull(`${TableName.Certificate}.renewedByCertificateId`);
+ .whereNull(`${TableName.Certificate}.renewedByCertificateId`)
+ .whereNull(`${TableName.Certificate}.deletedAt`);
const findActiveCertificatesForSync = async (
filter: TSyncEligibilityFilterParams & { projectId: string },
@@ -631,8 +685,9 @@ export const certificateDALFactory = (db: TDbClient) => {
const rows = await query
.distinctOn(`${TableName.Certificate}.orderId`)
+ .orderBy(`${TableName.Certificate}.orderId`, "asc")
+ .orderByRaw(`"${TableName.Certificate}"."deletedAt" IS NOT NULL`)
.orderBy([
- { column: `${TableName.Certificate}.orderId`, order: "asc" },
{ column: `${TableName.Certificate}.notBefore`, order: "desc" },
{ column: `${TableName.Certificate}.createdAt`, order: "desc" }
])
@@ -732,6 +787,7 @@ export const certificateDALFactory = (db: TDbClient) => {
.innerJoin(TableName.CertificateSecret, `${TableName.Certificate}.id`, `${TableName.CertificateSecret}.certId`)
.where(`${TableName.Certificate}.status`, CertStatus.ACTIVE)
.whereNull(`${TableName.Certificate}.renewedByCertificateId`)
+ .whereNull(`${TableName.Certificate}.deletedAt`)
.whereNull(`${TableName.Certificate}.renewalError`)
.whereNull(`${TableName.Certificate}.revokedAt`)
.whereNotNull(`${TableName.Certificate}.profileId`)
@@ -877,6 +933,7 @@ export const certificateDALFactory = (db: TDbClient) => {
notBeforeFrom,
notBeforeTo,
applicationIds,
+ includeDeleted,
...regularFilters
} = filter;
@@ -908,7 +965,8 @@ export const certificateDALFactory = (db: TDbClient) => {
notAfterTo,
notBeforeFrom,
notBeforeTo,
- applicationIds
+ applicationIds,
+ includeDeleted
},
true
) as typeof query;
@@ -962,6 +1020,7 @@ export const certificateDALFactory = (db: TDbClient) => {
const newer = await (tx || db.replicaNode())(TableName.Certificate)
.where("orderId", anchor.orderId)
.whereNot("status", CertStatus.REVOKED)
+ .whereNull("deletedAt")
.where("notAfter", ">", db.raw("NOW()"))
.whereRaw(`("createdAt", "id") > (SELECT "createdAt", "id" FROM ?? WHERE "id" = ?)`, [
TableName.Certificate,
@@ -1075,6 +1134,7 @@ export const certificateDALFactory = (db: TDbClient) => {
const [totalsRow] = await db
.replicaNode()(TableName.Certificate)
.where(`${TableName.Certificate}.projectId`, projectId)
+ .whereNull(`${TableName.Certificate}.deletedAt`)
.select(
db.raw("COUNT(*)::int as total"),
db.raw(
@@ -1111,6 +1171,7 @@ export const certificateDALFactory = (db: TDbClient) => {
const byAlgorithm = await db
.replicaNode()(TableName.Certificate)
.where(`${TableName.Certificate}.projectId`, projectId)
+ .whereNull(`${TableName.Certificate}.deletedAt`)
.select(`${TableName.Certificate}.keyAlgorithm as label`)
.count("* as count")
.groupBy(`${TableName.Certificate}.keyAlgorithm`);
@@ -1134,6 +1195,7 @@ export const certificateDALFactory = (db: TDbClient) => {
`${TableName.CertificateAuthority}.id`
)
.where(`${TableName.Certificate}.projectId`, projectId)
+ .whereNull(`${TableName.Certificate}.deletedAt`)
.select(`${TableName.CertificateAuthority}.id as id`)
.select(`${TableName.CertificateAuthority}.name as label`)
.select(db.raw(`${isSelfSignedExpr} as "isSelfSigned"`))
@@ -1156,6 +1218,7 @@ export const certificateDALFactory = (db: TDbClient) => {
`${TableName.PkiCertificateProfile}.id`
)
.where(`${TableName.Certificate}.projectId`, projectId)
+ .whereNull(`${TableName.Certificate}.deletedAt`)
.select(
db.raw(
`COALESCE(
@@ -1184,6 +1247,7 @@ export const certificateDALFactory = (db: TDbClient) => {
const expirationBuckets = await db
.replicaNode()(TableName.Certificate)
.where(`${TableName.Certificate}.projectId`, projectId)
+ .whereNull(`${TableName.Certificate}.deletedAt`)
.where(`${TableName.Certificate}.status`, "!=", CertStatus.REVOKED)
.where((qb) => {
void qb
@@ -1209,6 +1273,7 @@ export const certificateDALFactory = (db: TDbClient) => {
const validityBuckets = await db
.replicaNode()(TableName.Certificate)
.where(`${TableName.Certificate}.projectId`, projectId)
+ .whereNull(`${TableName.Certificate}.deletedAt`)
.where(`${TableName.Certificate}.status`, "!=", CertStatus.REVOKED)
.whereNull(`${TableName.Certificate}.renewedByCertificateId`)
.where(`${TableName.Certificate}.notAfter`, ">", now)
@@ -1288,6 +1353,7 @@ export const certificateDALFactory = (db: TDbClient) => {
const issued = await db
.replicaNode()(TableName.Certificate)
.where(`${TableName.Certificate}.projectId`, projectId)
+ .whereNull(`${TableName.Certificate}.deletedAt`)
.where(`${TableName.Certificate}.notBefore`, ">=", startDate)
.where(`${TableName.Certificate}.notBefore`, "<=", now)
.select(periodExpr("notBefore"))
@@ -1298,6 +1364,7 @@ export const certificateDALFactory = (db: TDbClient) => {
const expired = await db
.replicaNode()(TableName.Certificate)
.where(`${TableName.Certificate}.projectId`, projectId)
+ .whereNull(`${TableName.Certificate}.deletedAt`)
.where(`${TableName.Certificate}.notAfter`, ">=", startDate)
.where(`${TableName.Certificate}.notAfter`, "<=", now)
.where(`${TableName.Certificate}.status`, "!=", CertStatus.REVOKED)
@@ -1309,6 +1376,7 @@ export const certificateDALFactory = (db: TDbClient) => {
const revoked = await db
.replicaNode()(TableName.Certificate)
.where(`${TableName.Certificate}.projectId`, projectId)
+ .whereNull(`${TableName.Certificate}.deletedAt`)
.where(`${TableName.Certificate}.status`, CertStatus.REVOKED)
.where(`${TableName.Certificate}.revokedAt`, ">=", startDate)
.where(`${TableName.Certificate}.revokedAt`, "<=", now)
@@ -1320,6 +1388,7 @@ export const certificateDALFactory = (db: TDbClient) => {
const renewed = await db
.replicaNode()(TableName.Certificate)
.where(`${TableName.Certificate}.projectId`, projectId)
+ .whereNull(`${TableName.Certificate}.deletedAt`)
.whereNotNull(`${TableName.Certificate}.renewedFromCertificateId`)
.where(`${TableName.Certificate}.notBefore`, ">=", startDate)
.where(`${TableName.Certificate}.notBefore`, "<=", now)
@@ -1399,6 +1468,7 @@ export const certificateDALFactory = (db: TDbClient) => {
const rows = await db
.replicaNode()(TableName.Certificate)
.where(`${TableName.Certificate}.projectId`, projectId)
+ .whereNull(`${TableName.Certificate}.deletedAt`)
.where(`${TableName.Certificate}.notBefore`, ">=", startDate)
.where(`${TableName.Certificate}.notBefore`, "<=", now)
.select(
@@ -1451,11 +1521,38 @@ export const certificateDALFactory = (db: TDbClient) => {
}
};
+ const findByIdForShare = async (id: string, tx: Knex): Promise<TCertificates | undefined> => {
+ try {
+ return (await tx(TableName.Certificate).where({ id }).forShare().first()) as TCertificates | undefined;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find certificate by id for share" });
+ }
+ };
+
+ const findLiveIdsForShare = async (ids: string[], tx: Knex): Promise<string[]> => {
+ if (ids.length === 0) return [];
+ try {
+ const rows = (await tx(TableName.Certificate)
+ .whereIn("id", ids)
+ .whereNull("deletedAt")
+ .orderBy("id")
+ .forShare()
+ .select("id")) as Array<{ id: string }>;
+ return rows.map(({ id }) => id);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find live certificate ids for share" });
+ }
+ };
+
const primaryNode = () => db.primaryNode();
return {
primaryNode,
...certificateOrm,
+ findByIdForUpdate,
+ findByIdForShare,
+ findLiveIdsForShare,
+ restoreDeleted,
create,
countCertificatesInProject,
countActiveCertificatesForSync,
@@ -1477,7 +1574,6 @@ export const certificateDALFactory = (db: TDbClient) => {
findWithPrivateKeyInfo,
findWithFullDetails,
findLatestRenewalOf,
- findByIdForUpdate,
getDashboardStats,
getActivityTrend,
getPqcTrend
diff --git a/backend/src/services/certificate/certificate-fns.test.ts b/backend/src/services/certificate/certificate-fns.test.ts
index bb2dde4088..fa459292a7 100644
--- a/backend/src/services/certificate/certificate-fns.test.ts
+++ b/backend/src/services/certificate/certificate-fns.test.ts
@@ -2,19 +2,28 @@ import { createPrivateKey, generateKeyPairSync, webcrypto } from "node:crypto";
import * as x509 from "@peculiar/x509";
+import { TCertificates } from "@app/db/schemas";
import { CertificateSource } from "@app/ee/services/pki-discovery/pki-discovery-types";
import { BadRequestError } from "@app/lib/errors";
import {
+ assertCertificateMaterialAvailable,
+ assertCertificateNotDeleted,
buildCertificateBundle,
+ buildRestoredImportData,
+ canRestoreDeletedCertificate,
CertificateThumbprintAlgorithm,
extractCertificateFields,
extractExternallyIssuedCertificateFields,
+ getCertificateDisplayName,
+ linkRenewedCertificate,
+ lockRenewalOriginalCertificate,
normalizePemText,
normalizeThumbprint,
parseCertificateBody,
parsePemCertificateChain,
- resolveCertificateDeletionEligibility
+ resolveCertificateDeletionEligibility,
+ resolveCertificateStatus
} from "./certificate-fns";
import { CertExtendedKeyUsage, CertificateDeletionEligibility, CertKeyUsage, CertStatus } from "./certificate-types";
@@ -280,6 +289,22 @@ describe("extractExternallyIssuedCertificateFields", () => {
});
});
+describe("resolveCertificateStatus", () => {
+ const future = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
+ const past = new Date(Date.now() - 24 * 60 * 60 * 1000);
+
+ it("derives revoked > expired > renewed > active from the stored columns", () => {
+ expect(resolveCertificateStatus({ status: CertStatus.REVOKED, notAfter: past })).toBe(CertStatus.REVOKED);
+ expect(
+ resolveCertificateStatus({ status: CertStatus.ACTIVE, notAfter: past, renewedByCertificateId: "next" })
+ ).toBe(CertStatus.EXPIRED);
+ expect(
+ resolveCertificateStatus({ status: CertStatus.ACTIVE, notAfter: future, renewedByCertificateId: "next" })
+ ).toBe(CertStatus.RENEWED);
+ expect(resolveCertificateStatus({ status: CertStatus.ACTIVE, notAfter: future })).toBe(CertStatus.ACTIVE);
+ });
+});
+
describe("resolveCertificateDeletionEligibility", () => {
const future = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
const past = new Date(Date.now() - 24 * 60 * 60 * 1000);
@@ -353,6 +378,69 @@ describe("resolveCertificateDeletionEligibility", () => {
});
});
+describe("deleted certificate guards", () => {
+ const deletedAt = new Date("2026-10-20T14:38:27.000Z");
+ const certificate = { friendlyName: "web", commonName: "web.example.com", serialNumber: "0a1b2c" };
+
+ it("lets a certificate that was never deleted through", () => {
+ expect(() => assertCertificateMaterialAvailable(certificate)).not.toThrow();
+ expect(() => assertCertificateNotDeleted({ ...certificate, deletedAt: null })).not.toThrow();
+ });
+
+ it("refuses the certificate and private key of a deleted certificate, naming it and the date", () => {
+ expect(() => assertCertificateMaterialAvailable({ ...certificate, deletedAt })).toThrow(
+ new BadRequestError({
+ message:
+ "Certificate 'web' was deleted on 2026-10-20T14:38:27.000Z. Its certificate and private key are no longer available."
+ })
+ );
+ });
+
+ it("refuses to act on a deleted certificate", () => {
+ expect(() => assertCertificateNotDeleted({ ...certificate, deletedAt })).toThrow(BadRequestError);
+ expect(() => assertCertificateNotDeleted({ ...certificate, deletedAt })).toThrow(
+ "Certificate 'web' was deleted on 2026-10-20T14:38:27.000Z and can no longer be renewed or changed."
+ );
+ });
+
+ it("falls back to the common name and then the serial number when the name is empty", () => {
+ expect(getCertificateDisplayName({ ...certificate, friendlyName: "" })).toBe("web.example.com");
+ expect(getCertificateDisplayName({ ...certificate, friendlyName: "", commonName: "" })).toBe("0a1b2c");
+ });
+});
+
+describe("renewal link", () => {
+ const tx = {} as Parameters<typeof linkRenewedCertificate>[3];
+
+ it("points the locked original at its successor and carries the order over", async () => {
+ const dal = { updateById: vi.fn().mockResolvedValue({}) };
+
+ await linkRenewedCertificate(dal, { id: "cert-old", orderId: "order-1" }, "cert-new", tx);
+
+ expect(dal.updateById).toHaveBeenCalledWith("cert-new", { orderId: "order-1" }, tx);
+ expect(dal.updateById).toHaveBeenCalledWith("cert-old", { renewedByCertificateId: "cert-new" }, tx);
+ });
+
+ it("refuses to lock a certificate deleted while the renewal was in flight", async () => {
+ const dal = {
+ findByIdForUpdate: vi.fn().mockResolvedValue({
+ id: "cert-old",
+ commonName: "web.example.com",
+ serialNumber: "01",
+ deletedAt: new Date("2026-10-20T14:38:27.000Z")
+ })
+ };
+
+ await expect(lockRenewalOriginalCertificate(dal, "cert-old", tx)).rejects.toThrow(
+ "Certificate 'web.example.com' was deleted on 2026-10-20T14:38:27.000Z and can no longer be renewed or changed."
+ );
+ expect(dal.findByIdForUpdate).toHaveBeenCalledWith("cert-old", tx);
+ await expect(lockRenewalOriginalCertificate(dal, "cert-old", tx, "7f02")).rejects.toThrow(
+ "The certificate authority already issued the renewed certificate with serial number '7f02'."
+ );
+ });
+});
+
describe("normalizePemText", () => {
const { privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
const pkcs8Pem = privateKey.export({ type: "pkcs8", format: "pem" }).toString().trim();
@@ -434,3 +522,74 @@ describe("parsePemCertificateChain", () => {
expect(parsePemCertificateChain(`${await makeCertPem("Intermediate")}\n${rootLines.join("\n")}`)).toBeNull();
});
});
+
+describe("buildRestoredImportData", () => {
+ const deleted = {
+ id: "cert-1",
+ friendlyName: "web",
+ commonName: "web.example.com",
+ serialNumber: "0a1b",
+ fingerprintSha256: "AA:BB",
+ projectId: "project-1",
+ applicationId: null,
+ caId: "ca-1",
+ profileId: "profile-1",
+ externalMetadata: null,
+ source: null
+ } as unknown as TCertificates;
+ const imported: {
+ projectId: string;
+ applicationId: string | null;
+ caId: string | null;
+ profileId: string | null;
+ externalMetadata: unknown;
+ source: string;
+ fingerprintSha256: string;
+ altNames: string;
+ renewBeforeDays?: number;
+ } = {
+ projectId: "project-1",
+ applicationId: null,
+ caId: null,
+ profileId: null,
+ externalMetadata: null,
+ source: CertificateSource.Imported,
+ fingerprintSha256: "AA:BB",
+ altNames: "web.example.com"
+ };
+
+ it("keeps the deleted row's issuer link and clears stale state", () => {
+ const restored = buildRestoredImportData(deleted, imported);
+
+ expect(restored.caId).toBe("ca-1");
+ expect(restored.profileId).toBe("profile-1");
+ expect(restored.source).toBeNull();
+ expect(restored.renewalError).toBeNull();
+ expect(restored.renewBeforeDays).toBeNull();
+ });
+
+ it("marks a restored discovered certificate as imported", () => {
+ const restored = buildRestoredImportData(
+ { ...deleted, caId: null, profileId: null, source: CertificateSource.Discovered },
+ imported
+ );
+
+ expect(restored.source).toBe(CertificateSource.Imported);
+ });
+
+ it("restores only into the same project, Application, profile and certificate authority", () => {
+ const deletedRow = { ...deleted, deletedAt: new Date("2026-10-20T14:38:27.000Z") };
+ expect(canRestoreDeletedCertificate(deletedRow, imported)).toBe(false);
+ expect(canRestoreDeletedCertificate(deletedRow, { ...imported, profileId: "profile-1", caId: "ca-1" })).toBe(true);
+ expect(canRestoreDeletedCertificate(deletedRow, { ...imported, profileId: "profile-1" })).toBe(true);
+ expect(canRestoreDeletedCertificate({ ...deletedRow, profileId: null, caId: null }, imported)).toBe(true);
+ expect(canRestoreDeletedCertificate({ ...deletedRow, profileId: null }, imported)).toBe(false);
+ expect(canRestoreDeletedCertificate(deletedRow, { ...imported, applicationId: "app-2" })).toBe(false);
+ expect(canRestoreDeletedCertificate(deletedRow, { ...imported, profileId: "profile-2" })).toBe(false);
+ expect(canRestoreDeletedCertificate(deletedRow, { ...imported, caId: "ca-2" })).toBe(false);
+ expect(
+ canRestoreDeletedCertificate(deletedRow, { ...imported, projectId: "project-2", profileId: "profile-1" })
+ ).toBe(false);
+ expect(canRestoreDeletedCertificate(deleted, imported)).toBe(false);
+ });
+});
diff --git a/backend/src/services/certificate/certificate-fns.ts b/backend/src/services/certificate/certificate-fns.ts
index 29c9b54249..b2ca417773 100644
--- a/backend/src/services/certificate/certificate-fns.ts
+++ b/backend/src/services/certificate/certificate-fns.ts
@@ -3,6 +3,7 @@ import { Knex } from "knex";
import forge from "node-forge";
import RE2 from "re2";
+import { TCertificates } from "@app/db/schemas";
import { CertificateSource } from "@app/ee/services/pki-discovery/pki-discovery-types";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
@@ -530,19 +531,15 @@ export const extractExternallyIssuedCertificateFields = (
};
};
-export const linkRenewedCertificate = async (
- certificateDAL: Pick<TCertificateDALFactory, "findById" | "updateById">,
- originalCertificateId: string,
- renewedCertificateId: string,
- tx?: Knex
-) => {
- const originalCertificate = await certificateDAL.findById(originalCertificateId, tx);
-
- if (originalCertificate?.orderId) {
- await certificateDAL.updateById(renewedCertificateId, { orderId: originalCertificate.orderId }, tx);
- }
-
- await certificateDAL.updateById(originalCertificateId, { renewedByCertificateId: renewedCertificateId }, tx);
+export const resolveCertificateStatus = (certificate: {
+ status: string;
+ notAfter: Date;
+ renewedByCertificateId?: string | null;
+}): CertStatus => {
+ if (certificate.status === CertStatus.REVOKED) return CertStatus.REVOKED;
+ if (new Date(certificate.notAfter).getTime() <= Date.now()) return CertStatus.EXPIRED;
+ if (certificate.renewedByCertificateId) return CertStatus.RENEWED;
+ return CertStatus.ACTIVE;
};
export const resolveCertificateDeletionEligibility = (certificate: {
@@ -560,3 +557,111 @@ export const resolveCertificateDeletionEligibility = (certificate: {
return null;
};
+
+type TDeletableCertificate = {
+ friendlyName?: string | null;
+ commonName?: string | null;
+ serialNumber: string;
+ deletedAt?: Date | null;
+};
+
+export const getCertificateDisplayName = (certificate: Omit<TDeletableCertificate, "deletedAt">) =>
+ certificate.friendlyName || certificate.commonName || certificate.serialNumber;
+
+export const assertCertificateMaterialAvailable = (certificate: TDeletableCertificate) => {
+ if (!certificate.deletedAt) return;
+
+ throw new BadRequestError({
+ message: `Certificate '${getCertificateDisplayName(certificate)}' was deleted on ${new Date(certificate.deletedAt).toISOString()}. Its certificate and private key are no longer available.`
+ });
+};
+
+export const getCertificateDeletedMessage = (
+ certificate: TDeletableCertificate & { deletedAt: Date },
+ blockedAction = "be renewed or changed"
+) =>
+ `Certificate '${getCertificateDisplayName(certificate)}' was deleted on ${new Date(certificate.deletedAt).toISOString()} and can no longer ${blockedAction}.`;
+
+export const assertCertificateNotDeleted = (certificate: TDeletableCertificate, blockedAction?: string) => {
+ if (!certificate.deletedAt) return;
+
+ throw new BadRequestError({
+ message: getCertificateDeletedMessage({ ...certificate, deletedAt: certificate.deletedAt }, blockedAction)
+ });
+};
+
+export const lockRenewalOriginalCertificate = async (
+ certificateDAL: Pick<TCertificateDALFactory, "findByIdForUpdate">,
+ originalCertificateId: string,
+ tx: Knex,
+ issuedSerialNumber?: string
+) => {
+ const originalCertificate = await certificateDAL.findByIdForUpdate(originalCertificateId, tx);
+ if (originalCertificate?.deletedAt) {
+ const deletedMessage = getCertificateDeletedMessage({
+ ...originalCertificate,
+ deletedAt: originalCertificate.deletedAt
+ });
+ throw new BadRequestError({
+ message: issuedSerialNumber
+ ? `${deletedMessage} The certificate authority already issued the renewed certificate with serial number '${issuedSerialNumber}'. Revoke it at the certificate authority if you don't need it.`
+ : deletedMessage
+ });
+ }
+ return originalCertificate;
+};
+
+export const linkRenewedCertificate = async (
+ certificateDAL: Pick<TCertificateDALFactory, "updateById">,
+ lockedOriginalCertificate: Pick<TCertificates, "id" | "orderId">,
+ renewedCertificateId: string,
+ tx: Knex
+) => {
+ if (lockedOriginalCertificate.orderId) {
+ await certificateDAL.updateById(renewedCertificateId, { orderId: lockedOriginalCertificate.orderId }, tx);
+ }
+
+ await certificateDAL.updateById(lockedOriginalCertificate.id, { renewedByCertificateId: renewedCertificateId }, tx);
+};
+
+type TRestorableImportData = {
+ applicationId: string | null;
+ caId: string | null;
+ profileId: string | null;
+ externalMetadata: unknown;
+ source: string;
+ altNames?: string;
+ renewBeforeDays?: number;
+};
+
+export const canRestoreDeletedCertificate = (
+ deletedCertificate: Pick<TCertificates, "deletedAt" | "projectId" | "applicationId" | "profileId" | "caId">,
+ target: Pick<TRestorableImportData, "applicationId" | "profileId" | "caId"> & { projectId: string }
+) =>
+ Boolean(deletedCertificate.deletedAt) &&
+ deletedCertificate.projectId === target.projectId &&
+ (deletedCertificate.applicationId ?? null) === target.applicationId &&
+ (deletedCertificate.profileId ?? null) === target.profileId &&
+ (target.profileId
+ ? !(deletedCertificate.caId && target.caId && deletedCertificate.caId !== target.caId)
+ : !deletedCertificate.caId);
+
+export const buildRestoredImportData = <T extends TRestorableImportData>(
+ deletedCertificate: TCertificates,
+ importedData: T
+) => {
+ return {
+ ...importedData,
+ caId: deletedCertificate.caId ?? importedData.caId,
+ profileId: deletedCertificate.profileId ?? importedData.profileId,
+ externalMetadata: deletedCertificate.externalMetadata ?? importedData.externalMetadata,
+ source:
+ deletedCertificate.source === CertificateSource.Discovered
+ ? importedData.source
+ : (deletedCertificate.source ?? null),
+ altNames: importedData.altNames ?? null,
+ renewBeforeDays: importedData.renewBeforeDays ?? null,
+ renewalError: null,
+ discoveryMetadata: null
+ };
+};
diff --git a/backend/src/services/certificate/certificate-service.test.ts b/backend/src/services/certificate/certificate-service.test.ts
new file mode 100644
index 0000000000..97b6c1963d
--- /dev/null
+++ b/backend/src/services/certificate/certificate-service.test.ts
@@ -0,0 +1,142 @@
+import { createMongoAbility } from "@casl/ability";
+import { Knex } from "knex";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
+import { ActorType } from "@app/services/auth/auth-type";
+
+import { certificateServiceFactory } from "./certificate-service";
+import { CertStatus } from "./certificate-types";
+
+type TDeps = Parameters<typeof certificateServiceFactory>[0];
+
+const tx = {} as Knex;
+const deletedAt = new Date("2026-10-21T12:00:00.000Z");
+
+const liveCertificate = {
+ id: "cert-1",
+ projectId: "project-1",
+ applicationId: null,
+ commonName: "web.example.com",
+ friendlyName: "web",
+ serialNumber: "0a1b",
+ status: CertStatus.ACTIVE,
+ notBefore: new Date("2026-01-01T00:00:00.000Z"),
+ notAfter: new Date("2099-01-01T00:00:00.000Z"),
+ fingerprintSha256: "AA:BB",
+ source: null,
+ deletedAt: null
+};
+
+const actor = {
+ actor: ActorType.USER,
+ actorId: "user-1",
+ actorAuthMethod: null,
+ actorOrgId: "org-1"
+} as const;
+
+const buildService = () => {
+ const certificateDAL = {
+ findById: vi.fn().mockResolvedValue(liveCertificate),
+ findByIdForUpdate: vi.fn().mockResolvedValue(liveCertificate),
+ update: vi
+ .fn()
+ .mockImplementation(async (_filter: unknown, data: Record<string, unknown>) => [{ ...liveCertificate, ...data }]),
+ transaction: vi.fn().mockImplementation(async (run: (trx: Knex) => Promise<unknown>) => run(tx))
+ };
+ const certificateBodyDAL = { delete: vi.fn().mockResolvedValue([]) };
+ const certificateSecretDAL = { delete: vi.fn().mockResolvedValue([]) };
+ const pkiCollectionItemDAL = { delete: vi.fn().mockResolvedValue([]) };
+ const certificateSyncDAL = { delete: vi.fn().mockResolvedValue([]) };
+ const signerDAL = { findOne: vi.fn().mockResolvedValue(undefined) };
+
+ const deps = {
+ certificateDAL,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ pkiCollectionItemDAL,
+ certificateSyncDAL,
+ signerDAL,
+ resourceMetadataDAL: { find: vi.fn().mockResolvedValue([]) },
+ permissionService: {
+ getProjectPermission: vi
+ .fn()
+ .mockResolvedValue({ permission: createMongoAbility([{ action: "manage", subject: "all" }]) })
+ },
+ pkiApplicationDAL: { findById: vi.fn() },
+ pkiSyncDAL: { find: vi.fn().mockResolvedValue([]) },
+ pkiSyncQueue: {},
+ auditLogService: { createAuditLog: vi.fn() },
+ usageMeteringService: { emitForProject: vi.fn() }
+ } as unknown as TDeps;
+
+ return {
+ service: certificateServiceFactory(deps),
+ certificateDAL,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ pkiCollectionItemDAL,
+ certificateSyncDAL,
+ signerDAL
+ };
+};
+
+describe("certificateService.deleteCert", () => {
+ let ctx: ReturnType<typeof buildService>;
+
+ beforeEach(() => {
+ ctx = buildService();
+ });
+
+ it("keeps the row, stamps who deleted it, and removes its material, collection items and sync links", async () => {
+ ctx.certificateSyncDAL.delete.mockResolvedValue([{ pkiSyncId: "sync-1" }, { pkiSyncId: "sync-1" }]);
+
+ const result = await ctx.service.deleteCert({
+ id: "cert-1",
+ ...actor,
+ auditLogInfo: { userAgentType: UserAgentType.TERRAFORM } as never
+ });
+
+ expect(ctx.certificateDAL.update).toHaveBeenCalledWith(
+ { id: "cert-1" },
+ expect.objectContaining({
+ deletedByActorType: ActorType.USER,
+ deletedByActorId: "user-1",
+ deletedVia: UserAgentType.TERRAFORM,
+ deletedAt: expect.any(Date) as Date
+ }),
+ tx
+ );
+ expect(ctx.certificateBodyDAL.delete).toHaveBeenCalledWith({ certId: "cert-1" }, tx);
+ expect(ctx.certificateSecretDAL.delete).toHaveBeenCalledWith({ certId: "cert-1" }, tx);
+ expect(ctx.pkiCollectionItemDAL.delete).toHaveBeenCalledWith({ certId: "cert-1" }, tx);
+ expect(ctx.certificateSyncDAL.delete).toHaveBeenCalledWith({ certificateId: "cert-1" }, tx);
+ expect(result.statusAtDeletion).toBe(CertStatus.ACTIVE);
+ });
+
+ it("refuses a second delete with the date of the first one", async () => {
+ ctx.certificateDAL.findById.mockResolvedValue({ ...liveCertificate, deletedAt });
+
+ await expect(ctx.service.deleteCert({ id: "cert-1", ...actor })).rejects.toThrow(
+ "Certificate 'web' was already deleted on 2026-10-21T12:00:00.000Z."
+ );
+ expect(ctx.certificateDAL.update).not.toHaveBeenCalled();
+ });
+
+ it("refuses when a concurrent delete committed first", async () => {
+ ctx.certificateDAL.findByIdForUpdate.mockResolvedValue({ ...liveCertificate, deletedAt });
+
+ await expect(ctx.service.deleteCert({ id: "cert-1", ...actor })).rejects.toThrow("was already deleted");
+ expect(ctx.certificateDAL.update).not.toHaveBeenCalled();
+ expect(ctx.certificateBodyDAL.delete).not.toHaveBeenCalled();
+ });
+
+ it("refuses to delete a certificate a code signing signer uses", async () => {
+ ctx.signerDAL.findOne.mockResolvedValue({ id: "signer-1" });
+
+ await expect(ctx.service.deleteCert({ id: "cert-1", ...actor })).rejects.toThrow(
+ "Cannot delete certificate because it is currently in use by a code signing signer"
+ );
+ expect(ctx.certificateDAL.update).not.toHaveBeenCalled();
+ });
+});
diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.ts
index afd88e8bd6..4f32e9f5f1 100644
--- a/backend/src/services/certificate/certificate-service.ts
+++ b/backend/src/services/certificate/certificate-service.ts
@@ -1,9 +1,10 @@
/* eslint-disable no-await-in-loop */
import { ForbiddenError, subject } from "@casl/ability";
import * as x509 from "@peculiar/x509";
+import { Knex } from "knex";
import { ActionProjectType, ProjectMembershipRole, ResourceType } from "@app/db/schemas";
-import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
+import { TAuditLogServiceFactory, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
import { TCertificateAuthorityCrlDALFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-dal";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
@@ -19,9 +20,10 @@ import {
import { CertificateSource } from "@app/ee/services/pki-discovery/pki-discovery-types";
import { TKeyStoreFactory } from "@app/keystore/keystore";
import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { Pkcs12PasswordSchema } from "@app/lib/validator/password-policy";
+import { ActorType } from "@app/services/auth/auth-type";
import {
CertificateApplicationAlertEvent,
TCertificateAlertEventEmitter
@@ -50,6 +52,7 @@ import { TCertificateProfileDALFactory } from "@app/services/certificate-profile
import { IssuerType } from "@app/services/certificate-profile/certificate-profile-types";
import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";
import { TApiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-enrollment-config-dal";
+import { TIdentityDALFactory } from "@app/services/identity/identity-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { ActiveCerts, WildcardCerts } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
@@ -63,7 +66,6 @@ import { TPkiCollectionItemDALFactory } from "@app/services/pki-collection/pki-c
import { TPkiSyncDALFactory } from "@app/services/pki-sync/pki-sync-dal";
import { TPkiSyncQueueFactory } from "@app/services/pki-sync/pki-sync-queue";
import {
- findPkiSyncIdsHoldingCertificate,
queueCertificateFilterReconcile,
triggerAutoSyncForCertificate,
triggerSyncsForDeletedCertificate
@@ -71,6 +73,8 @@ import {
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
import { TResourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";
+import { TSignerDALFactory } from "@app/services/signer/signer-dal";
+import { TUserDALFactory } from "@app/services/user/user-dal";
import {
expandInternalCa,
@@ -89,16 +93,22 @@ import { validatePqcLicense } from "../certificate-common/certificate-utils";
import { certificateSpanToTtl } from "../certificate-v3/certificate-renewal-fns";
import { parseExtendedKeyUsages, parseKeyUsages } from "../certificate-v3/certificate-v3-fns";
import {
+ assertCertificateMaterialAvailable,
+ assertCertificateNotDeleted,
+ buildRestoredImportData,
+ canRestoreDeletedCertificate,
CertificateThumbprintAlgorithm,
extractCertificateAlgorithms,
extractCertificateFields,
generatePkcs12FromCertificate,
getCertificateCredentials,
+ getCertificateDisplayName,
normalizePemText,
normalizeThumbprint,
parseCertificateBody,
parsePemCertificateChain,
resolveCertificateDeletionEligibility,
+ resolveCertificateStatus,
revocationReasonToCrlCode
} from "./certificate-fns";
import { TCertificateSecretDALFactory } from "./certificate-secret-dal";
@@ -125,7 +135,6 @@ type TCertificateServiceFactoryDep = {
certificateDAL: Pick<
TCertificateDALFactory,
| "findOne"
- | "deleteById"
| "update"
| "find"
| "findByThumbprintInOrg"
@@ -135,25 +144,30 @@ type TCertificateServiceFactoryDep = {
| "findWithFullDetails"
| "findLatestRenewalOf"
| "updateById"
+ | "findByIdForUpdate"
+ | "restoreDeleted"
>;
pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;
- certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs">;
+ certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs" | "findById">;
pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory, "findOneByApplicationAndProfile">;
apiEnrollmentConfigDAL: Pick<TApiEnrollmentConfigDALFactory, "findById">;
digicertFns: Pick<ReturnType<typeof DigiCertCertificateAuthorityFns>, "assertOrderMatchesCertificate">;
certificatePolicyService: Pick<TCertificatePolicyServiceFactory, "validateCertificateRequest">;
- certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create">;
- certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne" | "create">;
+ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create" | "delete">;
+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne" | "create" | "delete">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;
certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findById" | "find">;
certificateAuthorityCrlDAL: Pick<TCertificateAuthorityCrlDALFactory, "update">;
certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
pkiCollectionDAL: Pick<TPkiCollectionDALFactory, "findById">;
- pkiCollectionItemDAL: Pick<TPkiCollectionItemDALFactory, "create">;
+ pkiCollectionItemDAL: Pick<TPkiCollectionItemDALFactory, "create" | "delete">;
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "findById" | "transaction" | "findProjectBySlug">;
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
- certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findPkiSyncIdsByCertificateId" | "primaryNode">;
+ certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findPkiSyncIdsByCertificateId" | "delete">;
+ signerDAL: Pick<TSignerDALFactory, "findOne">;
+ userDAL: Pick<TUserDALFactory, "findById">;
+ identityDAL: Pick<TIdentityDALFactory, "findById">;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;
pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById" | "queuePkiSyncLinkMatchingCertificates">;
@@ -206,7 +220,10 @@ export const certificateServiceFactory = ({
keyStore,
usageMeteringService,
caKeySourceService,
- internalCertificateAuthorityDAL
+ internalCertificateAuthorityDAL,
+ signerDAL,
+ userDAL,
+ identityDAL
}: TCertificateServiceFactoryDep) => {
const $canActOnCertViaApplication = async (
cert: { applicationId?: string | null; projectId: string },
@@ -239,7 +256,84 @@ export const certificateServiceFactory = ({
return application?.name ?? null;
};
- const getCert = async ({ id, serialNumber, actorId, actorAuthMethod, actor, actorOrgId }: TGetCertDTO) => {
+ const $describeImportRestoreTarget = async (
+ deletedCertificate: { applicationId?: string | null; profileId?: string | null; caId?: string | null },
+ importApplicationId: string | undefined,
+ tx: Knex
+ ) => {
+ if (importApplicationId && deletedCertificate.applicationId !== importApplicationId) {
+ return "It belongs to a different Application, so importing it here can't restore it.";
+ }
+ if (!deletedCertificate.profileId && deletedCertificate.caId) {
+ return "It was issued by a certificate authority, so importing it can't restore it.";
+ }
+
+ const application = deletedCertificate.applicationId
+ ? await pkiApplicationDAL.findById(deletedCertificate.applicationId, tx)
+ : undefined;
+ const profile = deletedCertificate.profileId
+ ? await certificateProfileDAL.findById(deletedCertificate.profileId, tx)
+ : undefined;
+ if (deletedCertificate.profileId && !profile) {
+ return "Its certificate profile no longer exists, so importing it can't restore it.";
+ }
+
+ if (application && profile) {
+ return `To restore it, import it into Application '${application.name}' with certificate profile '${profile.slug}'.`;
+ }
+ if (application) {
+ return `To restore it, import it into Application '${application.name}' without a certificate profile.`;
+ }
+ if (profile) {
+ return `To restore it, import it with certificate profile '${profile.slug}' and no Application.`;
+ }
+ return "To restore it, import it with no Application and no certificate profile.";
+ };
+
+ const $resolveDeletedByActorName = async (cert: {
+ deletedByActorType?: string | null;
+ deletedByActorId?: string | null;
+ }) => {
+ if (!cert.deletedByActorId) return null;
+
+ if (cert.deletedByActorType === ActorType.USER) {
+ const user = await userDAL.findById(cert.deletedByActorId);
+ if (!user) return null;
+ return [user.firstName, user.lastName].filter(Boolean).join(" ") || user.email || user.username;
+ }
+
+ if (cert.deletedByActorType === ActorType.IDENTITY) {
+ const identity = await identityDAL.findById(cert.deletedByActorId);
+ return identity?.name ?? null;
+ }
+
+ return null;
+ };
+
+ const $parseStoredCertificateBody = async (cert: { id: string; projectId: string }) => {
+ const certBody = await certificateBodyDAL.findOne({ certId: cert.id });
+ if (!certBody?.encryptedCertificate) return undefined;
+
+ const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
+ projectId: cert.projectId,
+ projectDAL,
+ kmsService
+ });
+ const kmsDecryptor = await kmsService.decryptWithKmsKey({ kmsId: certificateManagerKeyId });
+ const decryptedCert = await kmsDecryptor({ cipherTextBlob: certBody.encryptedCertificate });
+
+ return parseCertificateBody(decryptedCert);
+ };
+
+ const getCert = async ({
+ id,
+ serialNumber,
+ includeDeleted = false,
+ actorId,
+ actorAuthMethod,
+ actor,
+ actorOrgId
+ }: TGetCertDTO) => {
// Validation: require either id or serialNumber
if (!id && !serialNumber) {
throw new BadRequestError({ message: "Either id or serialNumber must be provided" });
@@ -248,7 +342,7 @@ export const certificateServiceFactory = ({
// Unified lookup - consistent response for both id and serialNumber
const certWithDetails = await certificateDAL.findWithFullDetails(id ? { id } : { serialNumber: serialNumber! });
- if (!certWithDetails) {
+ if (!certWithDetails || (certWithDetails.deletedAt && !includeDeleted)) {
throw new NotFoundError({ message: "Certificate not found" });
}
@@ -324,29 +418,16 @@ export const certificateServiceFactory = ({
// BACKWARD COMPATIBILITY: Fallback to on-demand parsing for old certificates
if (!hasParsedData) {
- const certBody = await certificateBodyDAL.findOne({ certId: cert.id });
- if (certBody?.encryptedCertificate) {
- const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
- projectId: cert.projectId,
- projectDAL,
- kmsService
- });
-
- const kmsDecryptor = await kmsService.decryptWithKmsKey({
- kmsId: certificateManagerKeyId
- });
-
- const decryptedCert = await kmsDecryptor({
- cipherTextBlob: certBody.encryptedCertificate
- });
-
- const parsed = parseCertificateBody(decryptedCert);
+ const parsed = await $parseStoredCertificateBody(cert);
+ if (parsed) {
certSubject = parsed.subject;
fingerprints = parsed.fingerprints;
basicConstraints = parsed.basicConstraints;
}
}
+ const deletedByActorName = await $resolveDeletedByActorName(cert);
+
const resolvedRenewalId = await certificateDAL.findLatestRenewalOf(cert);
let latestRenewalCertificateId: string | null = null;
@@ -385,6 +466,9 @@ export const certificateServiceFactory = ({
profileName,
applicationName,
latestRenewalCertificateId,
+ deletedByActorType: cert.deletedByActorType as ActorType | null | undefined,
+ deletedVia: cert.deletedVia as UserAgentType | null | undefined,
+ deletedByActorName,
metadata: certMetadata
}
};
@@ -436,6 +520,8 @@ export const certificateServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCertificateActions.ReadPrivateKey, certSubject);
}
+ assertCertificateMaterialAvailable(cert);
+
const { certPrivateKey } = await getCertificateCredentials({
certId: cert.id,
projectId: cert.projectId,
@@ -451,13 +537,6 @@ export const certificateServiceFactory = ({
};
};
- const $canRevokeThroughIssuer = async (caId: string) => {
- const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId).catch(() => null);
- if (!ca) return false;
-
- return caSupportsCapability((ca.externalCa?.type as CaType) ?? CaType.INTERNAL, CaCapability.REVOKE_CERTIFICATES);
- };
-
/**
* Delete certificate with serial number [serialNumber]
*/
@@ -517,58 +596,61 @@ export const certificateServiceFactory = ({
);
}
- const deletionEligibility = resolveCertificateDeletionEligibility(cert);
- if (!deletionEligibility) {
- const certName = cert.friendlyName || cert.commonName || cert.serialNumber;
- const expiresAt = cert.notAfter.toISOString();
-
- let message = `Certificate '${certName}' is still valid until ${expiresAt} and cannot be deleted. Delete it once it has expired.`;
- if (cert.status === CertStatus.REVOKED) {
- message = `Certificate '${certName}' was revoked but does not expire until ${expiresAt}. Delete it once it has expired.`;
- } else if (cert.caId && (await $canRevokeThroughIssuer(cert.caId))) {
- message = `Certificate '${certName}' is still valid until ${expiresAt} and cannot be deleted. Revoke it to retire it early, then delete it once it has expired.`;
- }
-
- throw new BadRequestError({ message });
+ if (cert.deletedAt) {
+ throw new BadRequestError({
+ message: `Certificate '${getCertificateDisplayName(cert)}' was already deleted on ${cert.deletedAt.toISOString()}.`
+ });
}
- const pkiSyncIdsHoldingCertificate = await findPkiSyncIdsHoldingCertificate(cert.id, { certificateSyncDAL });
-
- let deletedCert;
- try {
- deletedCert = await certificateDAL.transaction(async (tx) => {
- const successors = await certificateDAL.find({ renewedFromCertificateId: cert.id }, { tx });
-
- await certificateDAL.update(
- { renewedFromCertificateId: cert.id },
- { renewedFromCertificateId: cert.renewedFromCertificateId ?? null },
- tx
- );
+ const missingFingerprints = cert.fingerprintSha256
+ ? undefined
+ : await $parseStoredCertificateBody(cert)
+ .then((parsed) => parsed?.fingerprints)
+ .catch((error: unknown) => {
+ logger.warn(error, `Could not read fingerprints before deleting certificate [certificateId=${cert.id}]`);
+ return undefined;
+ });
- if (cert.renewedFromCertificateId && successors.length > 0) {
- await certificateDAL.updateById(
- cert.renewedFromCertificateId,
- { renewedByCertificateId: successors[0].id },
- tx
- );
- }
+ const { deletedCert, pkiSyncIdsHoldingCertificate } = await certificateDAL.transaction(async (tx) => {
+ const lockedCert = await certificateDAL.findByIdForUpdate(cert.id, tx);
+ if (!lockedCert || lockedCert.deletedAt) {
+ throw new BadRequestError({
+ message: `Certificate '${getCertificateDisplayName(cert)}' was already deleted${lockedCert?.deletedAt ? ` on ${new Date(lockedCert.deletedAt).toISOString()}` : ""}.`
+ });
+ }
- return certificateDAL.deleteById(cert.id, tx);
- });
- } catch (err) {
- const innerError = err instanceof DatabaseError ? (err.error as { code?: string; constraint?: string }) : null;
- if (innerError?.code === "23503") {
- if (innerError.constraint === "pki_signers_certificateid_foreign") {
- throw new BadRequestError({
- message: "Cannot delete certificate because it is currently in use by a code signing signer"
- });
- }
+ const signer = await signerDAL.findOne({ certificateId: cert.id }, tx);
+ if (signer) {
throw new BadRequestError({
- message: "Cannot delete certificate because it is referenced by another resource"
+ message: "Cannot delete certificate because it is currently in use by a code signing signer"
});
}
- throw err;
- }
+
+ const [softDeleted] = await certificateDAL.update(
+ { id: cert.id },
+ {
+ deletedAt: new Date(),
+ deletedByActorType: actor,
+ deletedByActorId: actorId,
+ deletedVia: auditLogInfo?.userAgentType ?? null,
+ ...(missingFingerprints?.sha256 && {
+ fingerprintSha256: missingFingerprints.sha256,
+ fingerprintSha1: missingFingerprints.sha1 ?? null
+ })
+ },
+ tx
+ );
+
+ await certificateBodyDAL.delete({ certId: cert.id }, tx);
+ await certificateSecretDAL.delete({ certId: cert.id }, tx);
+ await pkiCollectionItemDAL.delete({ certId: cert.id }, tx);
+ const removedSyncLinks = await certificateSyncDAL.delete({ certificateId: cert.id }, tx);
+
+ return {
+ deletedCert: softDeleted,
+ pkiSyncIdsHoldingCertificate: [...new Set(removedSyncLinks.map((link) => link.pkiSyncId))]
+ };
+ });
await triggerSyncsForDeletedCertificate(
cert.id,
@@ -583,7 +665,8 @@ export const certificateServiceFactory = ({
return {
deletedCert,
- deletionEligibility,
+ statusAtDeletion: resolveCertificateStatus(deletedCert),
+ deletionAllowedReason: resolveCertificateDeletionEligibility(deletedCert) ?? undefined,
applicationName: await $resolveApplicationName(deletedCert.applicationId)
};
};
@@ -712,9 +795,17 @@ export const certificateServiceFactory = ({
);
}
- if (cert.status === CertStatus.REVOKED) throw new Error("Certificate already revoked");
+ if (cert.status === CertStatus.REVOKED) {
+ throw new BadRequestError({ message: `Certificate '${getCertificateDisplayName(cert)}' is already revoked.` });
+ }
if (ca.internalCa?.id && cert.profileId && cert.source === CertificateSource.Imported) {
+ if (cert.deletedAt) {
+ throw new BadRequestError({
+ message: `Certificate '${getCertificateDisplayName(cert)}' can't be revoked because it was imported and then deleted on ${cert.deletedAt.toISOString()}.`
+ });
+ }
+
const certBody = await certificateBodyDAL.findOne({ certId: cert.id });
if (!certBody) {
throw new NotFoundError({ message: "Certificate body not found" });
@@ -773,13 +864,15 @@ export const certificateServiceFactory = ({
}
});
- await certificateAlertEventEmitter.notify({
- certificateId: revokedCertId,
- projectId: ca.projectId,
- orgId: actorOrgId,
- eventType: CertificateApplicationAlertEvent.Revocation,
- applicationId: revokedCertApplicationId
- });
+ if (!cert.deletedAt) {
+ await certificateAlertEventEmitter.notify({
+ certificateId: revokedCertId,
+ projectId: ca.projectId,
+ orgId: actorOrgId,
+ eventType: CertificateApplicationAlertEvent.Revocation,
+ applicationId: revokedCertApplicationId
+ });
+ }
usageMeteringService.emitForProject(ca.projectId, ActiveCerts.key);
usageMeteringService.emitForProject(ca.projectId, WildcardCerts.key);
@@ -791,7 +884,7 @@ export const certificateServiceFactory = ({
pkiSyncQueue
});
- if (cert.applicationId) {
+ if (cert.applicationId && !cert.deletedAt) {
await queueCertificateFilterReconcile(cert.id, cert.applicationId, pkiSyncQueue);
}
@@ -810,15 +903,17 @@ export const certificateServiceFactory = ({
});
}
- try {
- await pkiAlertV2Queue?.queueCertificateEvent({
- certificateId: cert.id,
- projectId: ca.projectId,
- eventType: PkiAlertEventType.REVOCATION,
- applicationId: cert.applicationId ?? null
- });
- } catch {
- logger.debug("Failed to queue PKI revocation alert event");
+ if (!cert.deletedAt) {
+ try {
+ await pkiAlertV2Queue?.queueCertificateEvent({
+ certificateId: cert.id,
+ projectId: ca.projectId,
+ eventType: PkiAlertEventType.REVOCATION,
+ applicationId: cert.applicationId ?? null
+ });
+ } catch {
+ logger.debug("Failed to queue PKI revocation alert event");
+ }
}
// Return appropriate CA format based on CA type
@@ -877,6 +972,8 @@ export const certificateServiceFactory = ({
}
}
+ assertCertificateMaterialAvailable(cert);
+
const certBody = await certificateBodyDAL.findOne({ certId: cert.id });
if (!certBody) {
@@ -1395,34 +1492,54 @@ export const certificateServiceFactory = ({
renewBeforeDays = calculateFinalRenewBeforeDays({ apiConfig: effectiveApiConfig }, `${validityDays}d`, notAfter);
}
- const cert = await certificateDAL.transaction(async (tx) => {
+ const importedCertificateData = {
+ friendlyName: friendlyName || commonName,
+ commonName,
+ altNames,
+ serialNumber,
+ notBefore,
+ notAfter,
+ projectId,
+ applicationId: applicationId ?? null,
+ profileId: profileId ?? null,
+ caId: linkage?.caId ?? null,
+ externalMetadata: linkage?.externalMetadata ?? null,
+ source: CertificateSource.Imported,
+ renewBeforeDays,
+ keyUsages,
+ extendedKeyUsages,
+ ...certificateFields,
+ // Issuance records these from what it was asked to produce. An imported certificate has
+ // no such request, so they come from the certificate itself.
+ ...certificateAlgorithms,
+ customExtensions: importedCustomExtensions.length ? JSON.stringify(importedCustomExtensions) : null
+ };
+
+ const { cert, restoredFromDeletion } = await certificateDAL.transaction(async (tx) => {
try {
- const txCert = await certificateDAL.create(
- {
- status: CertStatus.ACTIVE,
- friendlyName: friendlyName || commonName,
- commonName,
- altNames,
- serialNumber,
- notBefore,
- notAfter,
- projectId,
- applicationId: applicationId ?? null,
- profileId: profileId ?? null,
- caId: linkage?.caId ?? null,
- externalMetadata: linkage?.externalMetadata ?? null,
- source: CertificateSource.Imported,
- renewBeforeDays,
- keyUsages,
- extendedKeyUsages,
- ...certificateFields,
- // Issuance records these from what it was asked to produce. An imported certificate has
- // no such request, so they come from the certificate itself.
- ...certificateAlgorithms,
- customExtensions: importedCustomExtensions.length ? JSON.stringify(importedCustomExtensions) : null
- },
- tx
+ const matchingCertificates = await certificateDAL.find(
+ { serialNumber, projectId, fingerprintSha256: certificateFields.fingerprintSha256 },
+ { tx }
+ );
+ const deletedMatch = matchingCertificates.find((match) =>
+ canRestoreDeletedCertificate(match, importedCertificateData)
);
+ const unrestorableDeletedMatch = matchingCertificates.find((match) => match.deletedAt);
+ if (!deletedMatch && unrestorableDeletedMatch?.deletedAt) {
+ throw new BadRequestError({
+ message: `Certificate '${getCertificateDisplayName(unrestorableDeletedMatch)}' was deleted on ${new Date(unrestorableDeletedMatch.deletedAt).toISOString()}. ${await $describeImportRestoreTarget(unrestorableDeletedMatch, applicationId, tx)}`
+ });
+ }
+ const txCert = deletedMatch
+ ? await certificateDAL.restoreDeleted(
+ deletedMatch.id,
+ buildRestoredImportData(deletedMatch, importedCertificateData),
+ tx
+ )
+ : await certificateDAL.create({ status: CertStatus.ACTIVE, ...importedCertificateData }, tx);
+ if (!txCert) {
+ throw new BadRequestError({ message: "A certificate with this serial number already exists" });
+ }
await certificateBodyDAL.create(
{
@@ -1453,7 +1570,7 @@ export const certificateServiceFactory = ({
);
}
- return txCert;
+ return { cert: txCert, restoredFromDeletion: Boolean(deletedMatch) };
} catch (error) {
// @ts-expect-error We're expecting a database error
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
@@ -1481,7 +1598,8 @@ export const certificateServiceFactory = ({
cert,
applicationName: await $resolveApplicationName(cert.applicationId),
profileName: linkage?.profileName ?? null,
- caName: linkage?.caName ?? null
+ caName: linkage?.caName ?? null,
+ restoredFromDeletion
};
};
@@ -1548,6 +1666,8 @@ export const certificateServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCertificateActions.ReadPrivateKey, certSubject);
}
+ assertCertificateMaterialAvailable(cert);
+
const certBody = await certificateBodyDAL.findOne({ certId: cert.id });
if (!certBody) {
@@ -1679,6 +1799,8 @@ export const certificateServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCertificateActions.ReadPrivateKey, certSubject);
}
+ assertCertificateMaterialAvailable(cert);
+
// Get certificate bundle (certificate, chain, private key)
const { certificate, certificateChain, privateKey } = await getCertBundle({
id: cert.id,
@@ -1745,6 +1867,8 @@ export const certificateServiceFactory = ({
});
}
+ assertCertificateNotDeleted(cert);
+
const [updatedCert] = await certificateDAL.update({ id: cert.id }, { applicationId });
await queueCertificateFilterReconcile(cert.id, applicationId, pkiSyncQueue);
diff --git a/backend/src/services/certificate/certificate-types.ts b/backend/src/services/certificate/certificate-types.ts
index dc641281c4..c687396e45 100644
--- a/backend/src/services/certificate/certificate-types.ts
+++ b/backend/src/services/certificate/certificate-types.ts
@@ -17,7 +17,8 @@ export enum CertStatus {
ACTIVE = "active",
EXPIRED = "expired",
REVOKED = "revoked",
- RENEWED = "renewed"
+ RENEWED = "renewed",
+ DELETED = "deleted"
}
export enum CertificateDeletionEligibility {
@@ -26,6 +27,11 @@ export enum CertificateDeletionEligibility {
Imported = "imported"
}
+export enum CertificateRestoreSource {
+ Import = "import",
+ Discovery = "discovery"
+}
+
export enum CertKeyAlgorithm {
RSA_2048 = "RSA_2048",
RSA_3072 = "RSA_3072",
@@ -124,6 +130,7 @@ export enum CrlReason {
export type TGetCertDTO = {
id?: string;
serialNumber?: string;
+ includeDeleted?: boolean;
} & Omit<TProjectPermission, "projectId">;
export type TDeleteCertDTO = {
diff --git a/backend/src/services/hsm-connector/hsm-connector-dal.ts b/backend/src/services/hsm-connector/hsm-connector-dal.ts
index 039ac12137..970b7733da 100644
--- a/backend/src/services/hsm-connector/hsm-connector-dal.ts
+++ b/backend/src/services/hsm-connector/hsm-connector-dal.ts
@@ -15,6 +15,7 @@ export const hsmConnectorDALFactory = (db: TDbClient) => {
try {
const result = await (tx || db)(TableName.Certificate)
.where("hsmConnectorId", connectorId)
+ .whereNull("deletedAt")
.count<{ count: string }[]>("id as count")
.first();
return Number(result?.count ?? 0);
@@ -23,6 +24,17 @@ export const hsmConnectorDALFactory = (db: TDbClient) => {
}
};
+ const detachDeletedCertificates = async (connectorId: string, tx: Knex) => {
+ try {
+ await tx(TableName.Certificate)
+ .where("hsmConnectorId", connectorId)
+ .whereNotNull("deletedAt")
+ .update({ hsmConnectorId: null });
+ } catch (error) {
+ throw new DatabaseError({ error, name: "HsmConnectorDAL.detachDeletedCertificates" });
+ }
+ };
+
const countReferencingCertificateAuthorities = async (connectorId: string, tx?: Knex): Promise<number> => {
try {
const result = await (tx || db)(TableName.CertificateAuthoritySecret)
@@ -56,7 +68,10 @@ export const hsmConnectorDALFactory = (db: TDbClient) => {
}: { offset: number; limit: number; includeCertificateAuthorities: boolean }
) => {
try {
- const baseQuery = db.replicaNode()(TableName.Certificate).where("hsmConnectorId", connectorId);
+ const baseQuery = db
+ .replicaNode()(TableName.Certificate)
+ .where("hsmConnectorId", connectorId)
+ .whereNull("deletedAt");
const [rows, totalCountResult] = await Promise.all([
baseQuery
@@ -123,6 +138,7 @@ export const hsmConnectorDALFactory = (db: TDbClient) => {
...hsmConnectorOrm,
countReferencingCertificates,
countReferencingCertificateAuthorities,
+ detachDeletedCertificates,
findByProjectId,
listLinkedResources
};
diff --git a/backend/src/services/hsm-connector/hsm-connector-service.ts b/backend/src/services/hsm-connector/hsm-connector-service.ts
index 8c1be0a1a0..2ec8fe8baa 100644
--- a/backend/src/services/hsm-connector/hsm-connector-service.ts
+++ b/backend/src/services/hsm-connector/hsm-connector-service.ts
@@ -346,6 +346,7 @@ export const hsmConnectorServiceFactory = ({
message: `HSM Connector is in use by ${caCount} certificate authority(ies). Delete or migrate those CAs before removing this connector.`
});
}
+ await hsmConnectorDAL.detachDeletedCertificates(row.id, tx);
try {
await hsmConnectorDAL.deleteById(row.id, tx);
} catch (err) {
diff --git a/backend/src/services/license-client/usage/usage-counter-dal.ts b/backend/src/services/license-client/usage/usage-counter-dal.ts
index 4b04c51744..a153262115 100644
--- a/backend/src/services/license-client/usage/usage-counter-dal.ts
+++ b/backend/src/services/license-client/usage/usage-counter-dal.ts
@@ -2,6 +2,7 @@ import { Knex } from "knex";
import { TDbClient } from "@app/db";
import { AccessScope, ProjectType, TableName } from "@app/db/schemas";
+import { CertificateSource } from "@app/ee/services/pki-discovery/pki-discovery-types";
import { DatabaseError } from "@app/lib/errors";
import { orgTreeIds } from "@app/lib/knex";
import { CertStatus } from "@app/services/certificate/certificate-types";
@@ -87,7 +88,13 @@ export const usageCounterDALFactory = (db: TDbClient) => {
.join(TableName.Project, `${TableName.Certificate}.projectId`, `${TableName.Project}.id`)
.whereNull(`${TableName.Project}.deleteAfter`)
.where(`${TableName.Certificate}.notAfter`, ">", new Date())
- .whereNot(`${TableName.Certificate}.status`, CertStatus.REVOKED);
+ .whereNot(`${TableName.Certificate}.status`, CertStatus.REVOKED)
+ .where((liveOrIssued) => {
+ void liveOrIssued
+ .whereNull(`${TableName.Certificate}.deletedAt`)
+ .orWhereNull(`${TableName.Certificate}.source`)
+ .orWhereNotIn(`${TableName.Certificate}.source`, [CertificateSource.Imported, CertificateSource.Discovered]);
+ });
if (orgId) void qb.whereIn(`${TableName.Project}.orgId`, orgTreeIds(db.replicaNode(), orgId));
diff --git a/backend/src/services/org-product-stats/org-product-stats-dal.ts b/backend/src/services/org-product-stats/org-product-stats-dal.ts
index 3e45815456..557ca766fc 100644
--- a/backend/src/services/org-product-stats/org-product-stats-dal.ts
+++ b/backend/src/services/org-product-stats/org-product-stats-dal.ts
@@ -33,6 +33,7 @@ export const orgProductStatsDALFactory = (db: TDbClient) => {
.where(`${TableName.Project}.orgId`, orgId)
.whereNull(`${TableName.Project}.deleteAfter`)
.where(`${TableName.Project}.type`, ProjectType.CertificateManager)
+ .whereNull(`${TableName.Certificate}.deletedAt`)
.count(`${TableName.Certificate}.id as count`)
.first()) as { count: string } | undefined;
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-dal.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-dal.ts
index f2db606aa8..f7876e685d 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-v2-dal.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-dal.ts
@@ -466,7 +466,9 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
}
}
- certCountQuery = certCountQuery.whereNull(`${TableName.Certificate}.renewedByCertificateId`);
+ certCountQuery = certCountQuery
+ .whereNull(`${TableName.Certificate}.renewedByCertificateId`)
+ .whereNull(`${TableName.Certificate}.deletedAt`);
if (options?.excludeAlerted && options?.alertId) {
certCountQuery = certCountQuery.whereNotExists(
@@ -548,7 +550,9 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
}
}
- certificateQuery = certificateQuery.whereNull(`${TableName.Certificate}.renewedByCertificateId`);
+ certificateQuery = certificateQuery
+ .whereNull(`${TableName.Certificate}.renewedByCertificateId`)
+ .whereNull(`${TableName.Certificate}.deletedAt`);
if (options?.excludeAlerted && options?.alertId) {
certificateQuery = certificateQuery.whereNotExists(
diff --git a/backend/src/services/pki-alert/pki-alert-dal.ts b/backend/src/services/pki-alert/pki-alert-dal.ts
index 2183f6a410..acde6721a2 100644
--- a/backend/src/services/pki-alert/pki-alert-dal.ts
+++ b/backend/src/services/pki-alert/pki-alert-dal.ts
@@ -50,7 +50,8 @@ export const pkiAlertDALFactory = (db: TDbClient) => {
"pci.pkiCollectionId"
)
.from(`${TableName.Certificate} as ${PkiItemType.CERTIFICATE}`)
- .join(`${TableName.PkiCollectionItem} as pci`, `${PkiItemType.CERTIFICATE}.id`, "pci.certId");
+ .join(`${TableName.PkiCollectionItem} as pci`, `${PkiItemType.CERTIFICATE}.id`, "pci.certId")
+ .whereNull(`${PkiItemType.CERTIFICATE}.deletedAt`);
});
/**
diff --git a/backend/src/services/pki-application/pki-application-dal.ts b/backend/src/services/pki-application/pki-application-dal.ts
index d94d37e23d..6edb129d03 100644
--- a/backend/src/services/pki-application/pki-application-dal.ts
+++ b/backend/src/services/pki-application/pki-application-dal.ts
@@ -54,6 +54,7 @@ export const pkiApplicationDALFactory = (db: TDbClient) => {
const certCountSub = knex(TableName.Certificate)
.select("applicationId")
.whereNotNull("applicationId")
+ .whereNull("deletedAt")
.count<{ applicationId: string; count: string }[]>("* as count")
.groupBy("applicationId")
.as("cc");
diff --git a/backend/src/services/pki-collection/pki-collection-service.ts b/backend/src/services/pki-collection/pki-collection-service.ts
index 0f3c265565..3975ad5d1e 100644
--- a/backend/src/services/pki-collection/pki-collection-service.ts
+++ b/backend/src/services/pki-collection/pki-collection-service.ts
@@ -5,6 +5,7 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissio
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
+import { assertCertificateNotDeleted } from "@app/services/certificate/certificate-fns";
import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";
import { TPkiCollectionDALFactory } from "./pki-collection-dal";
@@ -262,6 +263,7 @@ export const pkiCollectionServiceFactory = ({
id: itemId
});
if (!certificate) throw new NotFoundError({ message: `Certificate with ID '${itemId}' not found` });
+ assertCertificateNotDeleted(certificate, "be added to a collection");
pkiCollectionItem = await pkiCollectionItemDAL.create({
pkiCollectionId: collectionId,
diff --git a/backend/src/services/pki-sync/pki-sync-dal.ts b/backend/src/services/pki-sync/pki-sync-dal.ts
index 9903f45d9e..9d5fc285d4 100644
--- a/backend/src/services/pki-sync/pki-sync-dal.ts
+++ b/backend/src/services/pki-sync/pki-sync-dal.ts
@@ -344,6 +344,7 @@ export const pkiSyncDALFactory = (db: TDbClient) => {
.where(`${TableName.Certificate}.notAfter`, ">=", yesterday)
.where(`${TableName.Certificate}.notAfter`, "<", today)
.whereNotNull(`${TableName.Certificate}.pkiSubscriberId`)
+ .whereNull(`${TableName.Certificate}.deletedAt`)
.whereNotNull(`${TableName.PkiSync}.subscriberId`)
.groupBy(`${TableName.PkiSync}.id`, `${TableName.PkiSync}.subscriberId`)) as Array<{
id: string;
diff --git a/backend/src/services/pki-sync/pki-sync-filter-reconcile-fns.ts b/backend/src/services/pki-sync/pki-sync-filter-reconcile-fns.ts
index 4c41aba33f..0cd74785b4 100644
--- a/backend/src/services/pki-sync/pki-sync-filter-reconcile-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-filter-reconcile-fns.ts
@@ -33,7 +33,7 @@ export type TPkiSyncReconcileTarget = {
};
type TPkiSyncFilterReconcileDeps = {
- certificateDAL: Pick<TCertificateDALFactory, "findCertificatesMatchingSyncFilters" | "find">;
+ certificateDAL: Pick<TCertificateDALFactory, "findCertificatesMatchingSyncFilters" | "find" | "findLiveIdsForShare">;
certificateSyncDAL: Pick<
TCertificateSyncDALFactory,
| "findCertificateIdsByPkiSyncId"
@@ -193,8 +193,9 @@ export const applyPkiSyncCertificateDiff = async (
writeFilters?: (tx: Knex) => Promise<void>,
removalOptions?: TPkiSyncRemovalOptions
): Promise<{ linked: TPkiSyncCertificateRef[]; unlinked: TPkiSyncCertificateRef[] }> => {
- const { certificateSyncDAL, pkiSyncQueue, auditLogService, pkiApplicationDAL } = deps;
- const { toLink, toUnlink } = diff;
+ const { certificateDAL, certificateSyncDAL, pkiSyncQueue, auditLogService, pkiApplicationDAL } = deps;
+ const { toUnlink } = diff;
+ let { toLink } = diff;
const unlinkIds = new Set(toUnlink.map((certificate) => certificate.id));
const canRemoveCertificates = Boolean(
@@ -210,6 +211,14 @@ export const applyPkiSyncCertificateDiff = async (
await certificateSyncDAL.transaction(async (tx) => {
if (writeFilters) await writeFilters(tx);
+ const liveIds = new Set(
+ await certificateDAL.findLiveIdsForShare(
+ toLink.map((certificate) => certificate.id),
+ tx
+ )
+ );
+ toLink = toLink.filter((certificate) => liveIds.has(certificate.id));
+
if (toLink.length > 0) {
await certificateSyncDAL.addCertificates(
pkiSync.id,
diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.ts
index 07f773b3c2..46d1065cb6 100644
--- a/backend/src/services/pki-sync/pki-sync-service.ts
+++ b/backend/src/services/pki-sync/pki-sync-service.ts
@@ -29,6 +29,7 @@ import { TPkiApplicationProfileDALFactory } from "@app/services/pki-application/
import { TPkiSubscriberDALFactory } from "@app/services/pki-subscriber/pki-subscriber-dal";
import { TCertificateDALFactory } from "../certificate/certificate-dal";
+import { getCertificateDisplayName } from "../certificate/certificate-fns";
import { CertStatus } from "../certificate/certificate-types";
import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";
import { CertificateSyncStatus } from "../certificate-sync/certificate-sync-enums";
@@ -125,6 +126,7 @@ type TPkiSyncServiceFactoryDep = {
TCertificateDALFactory,
| "find"
| "findCertificatesMatchingSyncFilters"
+ | "findLiveIdsForShare"
| "countCertificatesMatchingSyncFilters"
| "findReadableCertificateIds"
| "findLatestCertificatesByOrderIds"
@@ -539,6 +541,15 @@ export const pkiSyncServiceFactory = ({
const orderIds = [...new Set(certificates.map((cert) => cert.orderId))];
+ if (requireSyncable) {
+ const deleted = certificates.filter((cert) => cert.deletedAt);
+ if (deleted.length > 0) {
+ throw new BadRequestError({
+ message: `Deleted certificates can't be synced: ${deleted.map((cert) => `'${getCertificateDisplayName(cert)}'`).join(", ")}. Remove them and try again.`
+ });
+ }
+ }
+
if (requireSyncable && expectedApplicationId) {
const syncable = await certificateDAL.findCertificatesMatchingSyncFilters(
{ certificateOrderIds: orderIds },
@@ -576,9 +587,14 @@ export const pkiSyncServiceFactory = ({
const now = new Date();
const ineligibleReasons = certificates
.filter(
- (cert) => cert.status !== CertStatus.ACTIVE || cert.notAfter <= now || Boolean(cert.renewedByCertificateId)
+ (cert) =>
+ Boolean(cert.deletedAt) ||
+ cert.status !== CertStatus.ACTIVE ||
+ cert.notAfter <= now ||
+ Boolean(cert.renewedByCertificateId)
)
.map((cert) => {
+ if (cert.deletedAt) return `'${cert.commonName}' was deleted`;
if (cert.status === CertStatus.REVOKED) return `'${cert.commonName}' is revoked`;
if (cert.renewedByCertificateId)
return `'${cert.commonName}' has been renewed, so link the certificate that replaced it instead`;
diff --git a/backend/src/services/pki-sync/pki-sync-utils.ts b/backend/src/services/pki-sync/pki-sync-utils.ts
index dd4518c849..b54031b0df 100644
--- a/backend/src/services/pki-sync/pki-sync-utils.ts
+++ b/backend/src/services/pki-sync/pki-sync-utils.ts
@@ -101,23 +101,6 @@ export const queueCertificateFilterReconcile = async (
}
};
-export const findPkiSyncIdsHoldingCertificate = async (
- certificateId: string,
- dependencies: {
- certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findPkiSyncIdsByCertificateId" | "primaryNode">;
- }
-) => {
- try {
- return await dependencies.certificateSyncDAL.findPkiSyncIdsByCertificateId(
- certificateId,
- dependencies.certificateSyncDAL.primaryNode()
- );
- } catch (error) {
- logger.error(error, `Failed to read PKI sync links for certificate ${certificateId}`);
- return [];
- }
-};
-
export const triggerSyncsForDeletedCertificate = async (
certificateId: string,
pkiSyncIds: string[],
@@ -225,7 +208,11 @@ export const addRenewedCertificateToSyncs = async (
type TReconcileCertificateAgainstSyncsDeps = {
certificateDAL: Pick<
TCertificateDALFactory,
- "findActiveCertificatesByIds" | "findCertificatesMatchingSyncFilters" | "find" | "primaryNode"
+ | "findActiveCertificatesByIds"
+ | "findCertificatesMatchingSyncFilters"
+ | "find"
+ | "primaryNode"
+ | "findLiveIdsForShare"
>;
certificateSyncDAL: Pick<
TCertificateSyncDALFactory,
diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.ts
index bccf3e83b6..c024c6adda 100644
--- a/backend/src/services/project/project-service.ts
+++ b/backend/src/services/project/project-service.ts
@@ -1406,6 +1406,7 @@ export const projectServiceFactory = ({
notBeforeTo,
applicationId,
applicationIds,
+ includeDeleted,
sortBy,
sortOrder,
actorId,
@@ -1477,7 +1478,8 @@ export const projectServiceFactory = ({
...(notBeforeFrom && { notBeforeFrom }),
...(notBeforeTo && { notBeforeTo }),
...(applicationId && { applicationId }),
- ...(applicationIds && applicationIds.length > 0 && { applicationIds })
+ ...(applicationIds && applicationIds.length > 0 && { applicationIds }),
+ ...(includeDeleted && { includeDeleted })
};
const permissionFilters =
allowedByResource || !projectPermission
diff --git a/backend/src/services/project/project-types.ts b/backend/src/services/project/project-types.ts
index 7aed061308..e2a9d3be2b 100644
--- a/backend/src/services/project/project-types.ts
+++ b/backend/src/services/project/project-types.ts
@@ -163,6 +163,7 @@ export type TListProjectCertsDTO = {
notBeforeTo?: Date;
applicationId?: string;
applicationIds?: string[];
+ includeDeleted?: boolean;
sortBy?: string;
sortOrder?: "asc" | "desc";
} & Omit<TProjectPermission, "projectId">;
diff --git a/backend/src/services/signer/signer-service.ts b/backend/src/services/signer/signer-service.ts
index ffa73b9cda..aa98dbf0cc 100644
--- a/backend/src/services/signer/signer-service.ts
+++ b/backend/src/services/signer/signer-service.ts
@@ -65,7 +65,11 @@ import {
import { ActorType } from "../auth/auth-type";
import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";
import { TCertificateDALFactory } from "../certificate/certificate-dal";
-import { extractCertificateAlgorithms, getCertificateCredentials } from "../certificate/certificate-fns";
+import {
+ assertCertificateNotDeleted,
+ extractCertificateAlgorithms,
+ getCertificateCredentials
+} from "../certificate/certificate-fns";
import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-dal";
import { CertExtendedKeyUsage, CertKeyAlgorithm, CertStatus, CrlReason } from "../certificate/certificate-types";
import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";
@@ -169,7 +173,7 @@ type TSignerServiceFactoryDep = {
THsmConnectorServiceFactory,
"sign" | "signWithKeyId" | "generateKeyPair" | "getPublicKey" | "assertAttachPermission"
>;
- certificateDAL: Pick<TCertificateDALFactory, "findById" | "updateById" | "findByIdForUpdate">;
+ certificateDAL: Pick<TCertificateDALFactory, "findById" | "updateById" | "findByIdForUpdate" | "findByIdForShare">;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;
@@ -661,6 +665,7 @@ export const signerServiceFactory = ({
if (certificate.projectId !== dto.projectId) {
throw new BadRequestError({ message: "Certificate must belong to the same organization" });
}
+ assertCertificateNotDeleted(certificate, "be used by a signer");
if (certificate.status === CertStatus.REVOKED) {
throw new BadRequestError({ message: "Certificate has been revoked" });
}
@@ -785,6 +790,14 @@ export const signerServiceFactory = ({
try {
const result = await signerDAL.transaction(async (tx) => {
+ if (usingExistingCert) {
+ const lockedCertificate = await certificateDAL.findByIdForShare(dto.certificateId as string, tx);
+ if (!lockedCertificate) {
+ throw new NotFoundError({ message: `Certificate with ID '${dto.certificateId}' not found` });
+ }
+ assertCertificateNotDeleted(lockedCertificate, "be used by a signer");
+ }
+
const importedCertificateId = importedCertificate
? await $attachImportedCertificate(importedCertificate, undefined, tx)
: null;
diff --git a/backend/src/services/telemetry/telemetry-dal.ts b/backend/src/services/telemetry/telemetry-dal.ts
index bf497a4281..2dea72d65b 100644
--- a/backend/src/services/telemetry/telemetry-dal.ts
+++ b/backend/src/services/telemetry/telemetry-dal.ts
@@ -98,7 +98,10 @@ export const telemetryDALFactory = (db: TDbClient) => {
countTable(db, TableName.AppConnection),
countTable(db, TableName.Integration),
countTable(db, TableName.CertificateAuthority),
- countTable(db, TableName.Certificate),
+ (async () => {
+ const result = (await db(TableName.Certificate).whereNull("deletedAt").count().first())?.count as string;
+ return parseInt(result || "0", 10);
+ })(),
countTable(db, TableName.PkiCertificatePolicy),
countTable(db, TableName.PkiCertificateProfile),
countTable(db, TableName.PkiApplication),
diff --git a/docs/documentation/platform/pki/applications/certificates.mdx b/docs/documentation/platform/pki/applications/certificates.mdx
index 87a987acf9..8a7b297e2d 100644
--- a/docs/documentation/platform/pki/applications/certificates.mdx
+++ b/docs/documentation/platform/pki/applications/certificates.mdx
@@ -37,7 +37,9 @@ From the certificate details page, use the **Options** menu:
| **Renew Now** | [Renew the certificate](/documentation/platform/pki/applications/certificate-renewal), optionally changing its subject, names, validity, or key pair |
| **Manage Syncs** | Push to cloud destinations (ACM, Key Vault, etc.) |
| **Revoke** | Revoke with a reason code; certificate appears in CRL |
-| **Delete** | Remove from inventory |
+| **Delete** | Remove the certificate and its private key. It stays in the inventory as **Deleted** |
+
+Deleting a certificate doesn't revoke it. Revoke it first if clients should stop trusting it.
## Issuing certificates
diff --git a/docs/documentation/platform/pki/concepts/certificate-lifecycle.mdx b/docs/documentation/platform/pki/concepts/certificate-lifecycle.mdx
index 4ae0a3136d..340f621eaa 100644
--- a/docs/documentation/platform/pki/concepts/certificate-lifecycle.mdx
+++ b/docs/documentation/platform/pki/concepts/certificate-lifecycle.mdx
@@ -43,6 +43,6 @@ Invalidate a certificate when it's compromised, misconfigured, or no longer need
## Retirement
-Remove a certificate from the inventory once it has expired. Discovered and imported certificates can be removed at any time. Certificate Cleanup can automate the removal of expired certificates to keep your inventory clean.
+Deleting a certificate removes it and its private key, and it stays in the inventory as **Deleted**. A deleted certificate can't be renewed, and deleting doesn't revoke it. To restore it, import the same certificate into its original Application and certificate profile. Certificate Cleanup permanently removes expired certificates.
[Learn more about Certificate Cleanup →](/documentation/platform/pki/settings/certificate-cleanup)
diff --git a/docs/documentation/platform/pki/discovery/linux-server.mdx b/docs/documentation/platform/pki/discovery/linux-server.mdx
index 2face8e231..e8765b3eb0 100644
--- a/docs/documentation/platform/pki/discovery/linux-server.mdx
+++ b/docs/documentation/platform/pki/discovery/linux-server.mdx
@@ -87,7 +87,7 @@ If a folder still can't be read, the scan completes and the job shows which fold
Files larger than 512 KB are skipped and listed in the scan results. To raise that limit, set `maxFileSizeKb` on the job through the [API](/api-reference/endpoints/pki-discovery/update).
</Step>
<Step>
- Enter a **Name** and an optional **Description**. To run the job on a schedule, turn on **Scan on a Schedule** and pick a **Scan Interval**.
+ Enter a **Name** and an optional **Description**. To run the job on a schedule, turn on **Scan on a Schedule** and pick a **Scan Interval**. To restore a deleted certificate when a scan finds it again, turn on **Restore Deleted Certificates**. Certificates in an Application, or issued from a certificate profile or certificate authority, are never restored.
</Step>
<Step>
Review the job and select **Create Job**.
diff --git a/docs/documentation/platform/pki/discovery/network.mdx b/docs/documentation/platform/pki/discovery/network.mdx
index 7db694ed16..9007ecfc32 100644
--- a/docs/documentation/platform/pki/discovery/network.mdx
+++ b/docs/documentation/platform/pki/discovery/network.mdx
@@ -27,7 +27,7 @@ Network discovery scans network endpoints over TLS to discover certificates serv
</Note>
</Step>
<Step>
- Enter a **Name** and an optional **Description**. To run the job on a schedule, turn on **Scan on a Schedule** and pick a **Scan Interval**.
+ Enter a **Name** and an optional **Description**. To run the job on a schedule, turn on **Scan on a Schedule** and pick a **Scan Interval**. To restore a deleted certificate when a scan finds it again, turn on **Restore Deleted Certificates**. Certificates in an Application, or issued from a certificate profile or certificate authority, are never restored.
</Step>
<Step>
Review the job and select **Create Job**.
diff --git a/docs/documentation/platform/pki/discovery/overview.mdx b/docs/documentation/platform/pki/discovery/overview.mdx
index 64429f523c..0e39ed0a4b 100644
--- a/docs/documentation/platform/pki/discovery/overview.mdx
+++ b/docs/documentation/platform/pki/discovery/overview.mdx
@@ -32,6 +32,8 @@ An installation represents a unique location where a certificate was discovered
Discovered certificates are matched to your existing inventory by fingerprint. If a discovered certificate matches one in your Infisical organization, the installation is linked to that certificate — giving you a unified view of where your certificates are deployed.
+If a scan finds a certificate you deleted, it stays deleted and you can still see where it's deployed. To restore it instead, turn on **Restore Deleted Certificates** for the discovery job. Certificates in an Application, or issued from a certificate profile or certificate authority, are never restored.
+
## FAQ
<AccordionGroup>
diff --git a/docs/documentation/platform/pki/monitoring/certificate-inventory.mdx b/docs/documentation/platform/pki/monitoring/certificate-inventory.mdx
index 9336e4e13c..c04b02d5c2 100644
--- a/docs/documentation/platform/pki/monitoring/certificate-inventory.mdx
+++ b/docs/documentation/platform/pki/monitoring/certificate-inventory.mdx
@@ -39,7 +39,7 @@ To filter the inventory:
| Filter | What it matches |
| --- | --- |
-| **Status** | Active, Renewed, Expired, or Revoked |
+| **Status** | Active, Renewed, Expired, Revoked, or Deleted |
| **Expiration Date** | Certificates that expire before or after a date |
| **Issued Date** | Certificates whose validity starts before or after a date |
| **Enrollment Method** | The [enrollment method](/documentation/platform/pki/applications/enrollment-methods/overview) used to request the certificate: ACME, API, EST, or SCEP |
@@ -69,12 +69,13 @@ Infisical reopens the last view you used in this browser.
| View | Shows |
| --- | --- |
-| **All Certificates** | Every certificate |
+| **All Certificates** | Every certificate, including deleted certificates |
| **Expiring in 7 days** | Active certificates that expire in the next 7 days |
| **Expiring in 30 days** | Active certificates that expire in the next 30 days |
| **Renewed** | Certificates that a [renewal](/documentation/platform/pki/applications/certificate-renewal) replaced with a new certificate |
| **Expired** | Certificates past their expiration date |
| **Revoked** | Certificates that were revoked |
+| **Deleted** | Certificates that were [deleted](/documentation/platform/pki/concepts/certificate-lifecycle#retirement) |
| **Post-Quantum (PQC)** | Certificates with an ML-DSA key |
| **Classical (Non-PQC)** | Certificates with an RSA or ECDSA key |
diff --git a/docs/documentation/platform/pki/settings/certificate-cleanup.mdx b/docs/documentation/platform/pki/settings/certificate-cleanup.mdx
index 3e4e4175cf..6458fa7bc4 100644
--- a/docs/documentation/platform/pki/settings/certificate-cleanup.mdx
+++ b/docs/documentation/platform/pki/settings/certificate-cleanup.mdx
@@ -4,7 +4,7 @@ sidebarTitle: "Certificate cleanup"
description: "Automatically remove expired certificates to keep your inventory organized."
---
-Automatically remove expired certificates from your Certificate Manager. Cleanup runs daily and deletes certificates that have been expired for a configurable number of days.
+Automatically remove expired certificates from your Certificate Manager. Cleanup runs daily and permanently removes certificates that have been expired for a configurable number of days. If you delete a certificate yourself instead, its details stay in the inventory.
<Info>
This setting is managed by product admins and applies to all certificates in the Certificate Manager.
@@ -24,9 +24,9 @@ Automatically remove expired certificates from your Certificate Manager. Cleanup
| Value | Behavior |
|-------|----------|
- | `3` | Certificates are deleted 3 days after expiration |
- | `7` | Certificates are deleted 7 days after expiration |
- | `30` | Certificates are deleted 30 days after expiration |
+ | `3` | Certificates are permanently removed 3 days after expiration |
+ | `7` | Certificates are permanently removed 7 days after expiration |
+ | `30` | Certificates are permanently removed 30 days after expiration |
<Note>
Values must be between 1 and 30 days.
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index 55ef8a81e8..93fa4d9053 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -82,6 +82,7 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.IMPORT_CERT]: "Import certificate",
[EventType.GET_CERT]: "Get certificate",
[EventType.DELETE_CERT]: "Delete certificate",
+ [EventType.RESTORE_CERT]: "Restore certificate",
[EventType.REVOKE_CERT]: "Revoke certificate",
[EventType.ASSIGN_CERT_TO_APPLICATION]: "Assign certificate to Application",
[EventType.CREATE_PKI_APPLICATION]: "Create Application",
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index 14486c3bd5..96238790f8 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -98,6 +98,7 @@ export enum EventType {
IMPORT_CERT = "import-cert",
GET_CERT = "get-cert",
DELETE_CERT = "delete-cert",
+ RESTORE_CERT = "restore-cert",
REVOKE_CERT = "revoke-cert",
ASSIGN_CERT_TO_APPLICATION = "assign-cert-to-application",
CREATE_PKI_APPLICATION = "create-pki-application",
diff --git a/frontend/src/hooks/api/auditLogs/types.tsx b/frontend/src/hooks/api/auditLogs/types.tsx
index 9ef11adaae..b5c94268da 100644
--- a/frontend/src/hooks/api/auditLogs/types.tsx
+++ b/frontend/src/hooks/api/auditLogs/types.tsx
@@ -1,6 +1,6 @@
import { AuditLogEventClass } from "../auditLogSettings/types";
import { CaStatus } from "../ca";
-import { CrlReason } from "../certificates/enums";
+import { CertificateRestoreSource, CertStatus, CrlReason } from "../certificates/enums";
import { IdentityTrustedIp } from "../identities/types";
import { PkiItemType } from "../pkiCollections/constants";
import { WorkflowIntegration } from "../workflowIntegrations/types";
@@ -684,6 +684,24 @@ interface ImportCert {
};
}
+interface RestoreCert {
+ type: EventType.RESTORE_CERT;
+ metadata: {
+ certId: string;
+ cn: string;
+ serialNumber: string;
+ restoredVia: CertificateRestoreSource;
+ applicationId?: string | null;
+ applicationName?: string | null;
+ certificateProfileId?: string;
+ profileName?: string;
+ caId?: string;
+ caName?: string;
+ discoveryId?: string;
+ discoveryName?: string;
+ };
+}
+
interface GetCert {
type: EventType.GET_CERT;
metadata: {
@@ -702,7 +720,8 @@ interface DeleteCert {
serialNumber: string;
notAfter: string;
source: string;
- deletionAllowedReason: string;
+ statusAtDeletion?: CertStatus;
+ deletionAllowedReason?: string;
applicationId?: string | null;
applicationName?: string | null;
};
@@ -1089,6 +1108,7 @@ export type Event =
| ImportCert
| GetCert
| DeleteCert
+ | RestoreCert
| RevokeCert
| GetCertBody
| GetCertPrivateKey
diff --git a/frontend/src/hooks/api/certificates/enums.tsx b/frontend/src/hooks/api/certificates/enums.tsx
index e3074128b5..5758ee3f84 100644
--- a/frontend/src/hooks/api/certificates/enums.tsx
+++ b/frontend/src/hooks/api/certificates/enums.tsx
@@ -2,7 +2,8 @@ export enum CertStatus {
ACTIVE = "active",
RENEWED = "renewed",
EXPIRED = "expired",
- REVOKED = "revoked"
+ REVOKED = "revoked",
+ DELETED = "deleted"
}
export enum CertKeyAlgorithm {
@@ -59,6 +60,11 @@ export enum CertificateRenewalKeySource {
Csr = "csr"
}
+export enum CertificateRestoreSource {
+ Import = "import",
+ Discovery = "discovery"
+}
+
export enum CertSource {
Issued = "issued",
Discovered = "discovered",
diff --git a/frontend/src/hooks/api/certificates/queries.tsx b/frontend/src/hooks/api/certificates/queries.tsx
index 22ea6e813f..76ac68153f 100644
--- a/frontend/src/hooks/api/certificates/queries.tsx
+++ b/frontend/src/hooks/api/certificates/queries.tsx
@@ -107,7 +107,8 @@ export const useGetCertificateById = (certificateId: string) => {
queryKey: certKeys.getCertificateById(certificateId),
queryFn: async () => {
const { data } = await apiRequest.get<TCertificateByIdResponse>(
- `/api/v1/cert-manager/certificates/${certificateId}`
+ `/api/v1/cert-manager/certificates/${certificateId}`,
+ { params: { includeDeleted: true } }
);
return data;
},
diff --git a/frontend/src/hooks/api/certificates/types.ts b/frontend/src/hooks/api/certificates/types.ts
index 6c410c0bf2..bf47a1896e 100644
--- a/frontend/src/hooks/api/certificates/types.ts
+++ b/frontend/src/hooks/api/certificates/types.ts
@@ -1,4 +1,5 @@
import type { TPkcs12Entry } from "@app/helpers/pkcs12";
+import { ActorType, UserAgentType } from "@app/hooks/api/auditLogs/enums";
import { CaType } from "@app/hooks/api/ca/enums";
import {
@@ -81,6 +82,11 @@ export type TCertificate = {
[key: string]: unknown;
} | null;
metadata?: Array<{ key: string; value: string }>;
+ deletedAt?: string | null;
+ deletedByActorType?: ActorType | null;
+ deletedByActorId?: string | null;
+ deletedByActorName?: string | null;
+ deletedVia?: UserAgentType | null;
};
export type TCertificateByIdResponse = {
diff --git a/frontend/src/hooks/api/pkiDiscovery/types.ts b/frontend/src/hooks/api/pkiDiscovery/types.ts
index b34a3d9993..d018e72836 100644
--- a/frontend/src/hooks/api/pkiDiscovery/types.ts
+++ b/frontend/src/hooks/api/pkiDiscovery/types.ts
@@ -71,6 +71,7 @@ export type TPkiDiscovery = {
discoveryType: PkiDiscoveryType;
targetConfig: TPkiDiscoveryTargetConfig;
isAutoScanEnabled: boolean;
+ restoreDeletedCertificates: boolean;
scanIntervalDays: number | null;
gatewayId: string | null;
gatewayPoolId: string | null;
@@ -138,6 +139,7 @@ export type TPkiInstallationCert = {
notBefore?: string | null;
notAfter?: string | null;
status?: string | null;
+ deletedAt?: string | null;
friendlyName?: string | null;
fingerprintSha256?: string | null;
};
@@ -180,6 +182,7 @@ export type TCreatePkiDiscoveryDTO = {
discoveryType?: PkiDiscoveryType;
targetConfig: TPkiDiscoveryTargetConfig;
isAutoScanEnabled?: boolean;
+ restoreDeletedCertificates?: boolean;
scanIntervalDays?: number;
gatewayId?: string;
gatewayPoolId?: string;
@@ -191,6 +194,7 @@ export type TUpdatePkiDiscoveryDTO = {
description?: string | null;
targetConfig?: TPkiDiscoveryTargetConfig;
isAutoScanEnabled?: boolean;
+ restoreDeletedCertificates?: boolean;
scanIntervalDays?: number | null;
gatewayId?: string | null;
gatewayPoolId?: string | null;
diff --git a/frontend/src/hooks/api/projects/queries.tsx b/frontend/src/hooks/api/projects/queries.tsx
index 7e9447673c..a34b628696 100644
--- a/frontend/src/hooks/api/projects/queries.tsx
+++ b/frontend/src/hooks/api/projects/queries.tsx
@@ -634,6 +634,7 @@ export const useListWorkspaceCertificates = ({
notBeforeTo,
applicationId,
applicationIds,
+ includeDeleted,
sortBy,
sortOrder
}: {
@@ -662,6 +663,7 @@ export const useListWorkspaceCertificates = ({
notBeforeTo?: Date;
applicationId?: string;
applicationIds?: string[];
+ includeDeleted?: boolean;
sortBy?: string;
sortOrder?: "asc" | "desc";
}) => {
@@ -692,6 +694,7 @@ export const useListWorkspaceCertificates = ({
notBeforeTo,
applicationId,
applicationIds,
+ includeDeleted,
sortBy,
sortOrder
}),
@@ -725,6 +728,7 @@ export const useListWorkspaceCertificates = ({
...(notBeforeTo && { notBeforeTo: notBeforeTo.toISOString() }),
...(applicationId && { applicationId }),
...(applicationIds && applicationIds.length > 0 && { applicationIds }),
+ ...(includeDeleted && { includeDeleted }),
...(sortBy && { sortBy }),
...(sortOrder && { sortOrder })
}
diff --git a/frontend/src/hooks/api/projects/query-keys.tsx b/frontend/src/hooks/api/projects/query-keys.tsx
index d72f0058b3..d4fc1acf58 100644
--- a/frontend/src/hooks/api/projects/query-keys.tsx
+++ b/frontend/src/hooks/api/projects/query-keys.tsx
@@ -92,6 +92,7 @@ export const projectKeys = {
notBeforeTo,
applicationId,
applicationIds,
+ includeDeleted,
sortBy,
sortOrder
}: {
@@ -120,6 +121,7 @@ export const projectKeys = {
notBeforeTo?: Date;
applicationId?: string;
applicationIds?: string[];
+ includeDeleted?: boolean;
sortBy?: string;
sortOrder?: "asc" | "desc";
}) =>
@@ -150,6 +152,7 @@ export const projectKeys = {
notBeforeTo,
applicationId,
applicationIds,
+ includeDeleted,
sortBy,
sortOrder
}
diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
index f33e3c173f..accd10a75b 100644
--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
@@ -1,6 +1,6 @@
import { Helmet } from "react-helmet";
import { subject } from "@casl/ability";
-import { Link, useNavigate, useParams, useSearch } from "@tanstack/react-router";
+import { Link, useParams, useSearch } from "@tanstack/react-router";
import { ChevronLeftIcon, EllipsisIcon } from "lucide-react";
import { createNotification } from "@app/components/notifications";
@@ -60,11 +60,13 @@ import { CertificateManageRenewalModal } from "../CertificatesPage/components/Ce
import { CertificateRenewalModal } from "../CertificatesPage/components/CertificateRenewalModal";
import { CertificateRevocationModal } from "../CertificatesPage/components/CertificateRevocationModal";
import {
- getCertificateDeletionBlockReason,
+ canRevokeAfterDeletion,
+ getCertificateDeletionWarning,
isExpiringWithinOneDay,
isManagedCertificate,
RENEWAL_UNAVAILABLE_NO_PROFILE
} from "../CertificatesPage/components/CertificatesTable.utils";
+import { useCertificateHoldingSyncs } from "../CertificatesPage/components/useCertificateHoldingSyncs";
import {
CertificateDetailsSection,
CertificateInstallationsSection,
@@ -74,7 +76,6 @@ import {
const Page = () => {
const { currentProject } = useProject();
const { currentOrg } = useOrganization();
- const navigate = useNavigate();
const params = useParams({
from: ROUTE_PATHS.CertManager.CertificateDetailsByIDPage.id
});
@@ -108,6 +109,12 @@ const Page = () => {
certificate?.applicationId ?? ""
);
+ const { holdingSyncs, isLoadingHoldingSyncs } = useCertificateHoldingSyncs({
+ certificateId: certificate?.id,
+ applicationId: certificate?.applicationId,
+ isEnabled: popUp.deleteCertificate.isOpen
+ });
+
if (isLoading) {
return <PageLoader />;
}
@@ -125,23 +132,6 @@ const Page = () => {
});
handlePopUpClose("deleteCertificate");
- if (fromApplication) {
- navigate({
- to: "/organizations/$orgId/cert-manager/applications/$applicationName",
- params: {
- orgId: currentOrg.id,
- applicationName: fromApplication
- },
- search: { selectedTab: ApplicationTab.Certificates }
- });
- } else {
- navigate({
- to: "/organizations/$orgId/cert-manager/inventory",
- params: {
- orgId: currentOrg.id
- }
- });
- }
};
const handleCertificateExport = async (
@@ -206,6 +196,16 @@ const Page = () => {
Boolean(certificate?.caId) &&
(!caType || caSupportsCapability(caType, CaCapability.REVOKE_CERTIFICATES));
+ const isDeleted = Boolean(certificate?.deletedAt);
+ const isRevocableAfterDeletion = certificate
+ ? canRevokeAfterDeletion(certificate, certificate.caType ?? caType)
+ : true;
+ const canOfferRevoke =
+ supportsRevocation &&
+ !isRevoked &&
+ (!isDeleted || isRevocableAfterDeletion) &&
+ !(isInventoryView && certificate?.applicationId);
+
const handleDisableAutoRenewal = async () => {
if (!certificate) return;
@@ -331,164 +331,123 @@ const Page = () => {
description="View certificate details"
title={displayName}
>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="outline">
- Options
- <EllipsisIcon />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem
- isDisabled={!canReadCertificate}
- onClick={() =>
- handlePopUpOpen("certificateExport", {
- certificateId: certificate.id,
- serialNumber: certificate.serialNumber
- })
- }
- >
- Export Certificate
- </DropdownMenuItem>
- {!isInventoryView &&
- certificate.profileId &&
- certificate.hasPrivateKey !== false &&
- !certificate.renewedByCertificateId &&
- !isRevoked &&
- !isExpired &&
- !hasFailed &&
- !isExpiringWithinDay && (
+ {isDeleted && !canOfferRevoke ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button variant="outline" isDisabled>
+ Options
+ <EllipsisIcon />
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>No actions are available for a deleted certificate.</TooltipContent>
+ </Tooltip>
+ ) : (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline">
+ Options
+ <EllipsisIcon />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {!isDeleted && (
<DropdownMenuItem
- isDisabled={!canEditCertificate}
- onClick={() => {
- const notAfterDate = new Date(certificate.notAfter);
- const notBeforeDate = certificate.notBefore
- ? new Date(certificate.notBefore)
- : new Date(notAfterDate.getTime() - 365 * 24 * 60 * 60 * 1000);
- const ttlDays = Math.max(
- 1,
- Math.ceil(
- (notAfterDate.getTime() - notBeforeDate.getTime()) / (24 * 60 * 60 * 1000)
- )
- );
- handlePopUpOpen("manageRenewal", {
+ isDisabled={!canReadCertificate}
+ onClick={() =>
+ handlePopUpOpen("certificateExport", {
certificateId: certificate.id,
- commonName: displayName,
- profileId: certificate.profileId,
- renewBeforeDays: certificate.renewBeforeDays,
- ttlDays,
- notAfter: certificate.notAfter,
- renewalError: certificate.renewalError,
- renewedFromCertificateId: certificate.renewedFromCertificateId,
- renewedByCertificateId: certificate.renewedByCertificateId
- });
- }}
- >
- {isAutoRenewalEnabled ? "Manage Auto-Renewal" : "Enable Auto-Renewal"}
- </DropdownMenuItem>
- )}
- {!isInventoryView &&
- certificate.profileId &&
- certificate.hasPrivateKey !== false &&
- !certificate.renewedByCertificateId &&
- !isRevoked &&
- !isExpired &&
- !isExpiringWithinDay &&
- isAutoRenewalEnabled && (
- <DropdownMenuItem
- isDisabled={!canEditCertificate}
- onClick={handleDisableAutoRenewal}
+ serialNumber: certificate.serialNumber
+ })
+ }
>
- Disable Auto-Renewal
+ Export Certificate
</DropdownMenuItem>
)}
- {(() => {
- const isRenewable =
- !isInventoryView &&
+ {!isInventoryView &&
+ !isDeleted &&
+ certificate.profileId &&
+ certificate.hasPrivateKey !== false &&
!certificate.renewedByCertificateId &&
!isRevoked &&
- !isExpired;
-
- if (!isRenewable) return null;
+ !isExpired &&
+ !hasFailed &&
+ !isExpiringWithinDay && (
+ <DropdownMenuItem
+ isDisabled={!canEditCertificate}
+ onClick={() => {
+ const notAfterDate = new Date(certificate.notAfter);
+ const notBeforeDate = certificate.notBefore
+ ? new Date(certificate.notBefore)
+ : new Date(notAfterDate.getTime() - 365 * 24 * 60 * 60 * 1000);
+ const ttlDays = Math.max(
+ 1,
+ Math.ceil(
+ (notAfterDate.getTime() - notBeforeDate.getTime()) /
+ (24 * 60 * 60 * 1000)
+ )
+ );
+ handlePopUpOpen("manageRenewal", {
+ certificateId: certificate.id,
+ commonName: displayName,
+ profileId: certificate.profileId,
+ renewBeforeDays: certificate.renewBeforeDays,
+ ttlDays,
+ notAfter: certificate.notAfter,
+ renewalError: certificate.renewalError,
+ renewedFromCertificateId: certificate.renewedFromCertificateId,
+ renewedByCertificateId: certificate.renewedByCertificateId
+ });
+ }}
+ >
+ {isAutoRenewalEnabled ? "Manage Auto-Renewal" : "Enable Auto-Renewal"}
+ </DropdownMenuItem>
+ )}
+ {!isInventoryView &&
+ !isDeleted &&
+ certificate.profileId &&
+ certificate.hasPrivateKey !== false &&
+ !certificate.renewedByCertificateId &&
+ !isRevoked &&
+ !isExpired &&
+ !isExpiringWithinDay &&
+ isAutoRenewalEnabled && (
+ <DropdownMenuItem
+ isDisabled={!canEditCertificate}
+ onClick={handleDisableAutoRenewal}
+ >
+ Disable Auto-Renewal
+ </DropdownMenuItem>
+ )}
+ {(() => {
+ const isRenewable =
+ !isInventoryView &&
+ !isDeleted &&
+ !certificate.renewedByCertificateId &&
+ !isRevoked &&
+ !isExpired;
- const profileMissing = !certificate.profileId;
- if (profileMissing && !isManagedCertificate(certificate)) return null;
+ if (!isRenewable) return null;
- const item = (
- <DropdownMenuItem
- isDisabled={!canEditCertificate || profileMissing}
- onClick={() =>
- handlePopUpOpen("renewCertificate", {
- certificateId: certificate.id,
- commonName: displayName
- })
- }
- >
- Renew Now
- </DropdownMenuItem>
- );
-
- if (!profileMissing) return item;
-
- return (
- <Tooltip>
- <TooltipTrigger asChild>
- <div>{item}</div>
- </TooltipTrigger>
- <TooltipContent side="left" sideOffset={20} className="max-w-72">
- {RENEWAL_UNAVAILABLE_NO_PROFILE}
- </TooltipContent>
- </Tooltip>
- );
- })()}
- {!isInventoryView &&
- certificate.status === CertStatus.ACTIVE &&
- !certificate.renewedByCertificateId &&
- certificate.source === CertSource.Issued && (
- <DropdownMenuItem
- isDisabled={!canEditPkiSyncs}
- onClick={() =>
- handlePopUpOpen("managePkiSyncs", {
- certificateId: certificate.id,
- commonName: displayName
- })
- }
- >
- Manage PKI Syncs
- </DropdownMenuItem>
- )}
- {supportsRevocation &&
- !isRevoked &&
- !(isInventoryView && certificate.applicationId) && (
- <DropdownMenuItem
- isDisabled={!canDeleteCertificate}
- onClick={() =>
- handlePopUpOpen("revokeCertificate", {
- certificateId: certificate.id
- })
- }
- >
- Revoke Certificate
- </DropdownMenuItem>
- )}
- {!(isInventoryView && certificate.applicationId) &&
- (() => {
- const deletionBlockReason = getCertificateDeletionBlockReason(
- certificate,
- supportsRevocation
- );
+ const profileMissing = !certificate.profileId;
+ if (profileMissing && !isManagedCertificate(certificate)) return null;
const item = (
<DropdownMenuItem
- variant="danger"
- isDisabled={!canDeleteCertificate || Boolean(deletionBlockReason)}
- onClick={() => handlePopUpOpen("deleteCertificate")}
+ isDisabled={!canEditCertificate || profileMissing}
+ onClick={() =>
+ handlePopUpOpen("renewCertificate", {
+ certificateId: certificate.id,
+ commonName: displayName
+ })
+ }
>
- Delete Certificate
+ Renew Now
</DropdownMenuItem>
);
- if (!deletionBlockReason) return item;
+ if (!profileMissing) return item;
return (
<Tooltip>
@@ -496,13 +455,52 @@ const Page = () => {
<div>{item}</div>
</TooltipTrigger>
<TooltipContent side="left" sideOffset={20} className="max-w-72">
- {deletionBlockReason}
+ {RENEWAL_UNAVAILABLE_NO_PROFILE}
</TooltipContent>
</Tooltip>
);
})()}
- </DropdownMenuContent>
- </DropdownMenu>
+ {!isInventoryView &&
+ !isDeleted &&
+ certificate.status === CertStatus.ACTIVE &&
+ !certificate.renewedByCertificateId &&
+ certificate.source === CertSource.Issued && (
+ <DropdownMenuItem
+ isDisabled={!canEditPkiSyncs}
+ onClick={() =>
+ handlePopUpOpen("managePkiSyncs", {
+ certificateId: certificate.id,
+ commonName: displayName
+ })
+ }
+ >
+ Manage PKI Syncs
+ </DropdownMenuItem>
+ )}
+ {canOfferRevoke && (
+ <DropdownMenuItem
+ isDisabled={!canDeleteCertificate}
+ onClick={() =>
+ handlePopUpOpen("revokeCertificate", {
+ certificateId: certificate.id
+ })
+ }
+ >
+ Revoke Certificate
+ </DropdownMenuItem>
+ )}
+ {!isDeleted && !(isInventoryView && certificate.applicationId) && (
+ <DropdownMenuItem
+ variant="danger"
+ isDisabled={!canDeleteCertificate}
+ onClick={() => handlePopUpOpen("deleteCertificate")}
+ >
+ Delete Certificate
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
</PageHeader>
<div className="flex flex-col gap-5 lg:flex-row">
<CertificateOverviewSection certificateId={certificate.id} />
@@ -542,9 +540,15 @@ const Page = () => {
/>
<ConfirmationAlertDialog
isOpen={popUp.deleteCertificate.isOpen}
- title="Are you sure you want to delete this certificate?"
- description="This action cannot be undone. The certificate will be permanently deleted."
+ title={`Delete certificate ${displayName}?`}
+ description={getCertificateDeletionWarning(
+ certificate,
+ supportsRevocation,
+ isRevocableAfterDeletion,
+ holdingSyncs
+ )}
onOpenChange={(isOpen) => handlePopUpToggle("deleteCertificate", isOpen)}
+ isPending={isLoadingHoldingSyncs}
confirmKey="confirm"
onConfirm={onDeleteCertificateSubmit}
/>
diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateMetadataSection.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateMetadataSection.tsx
index a3c643b74d..d8bb78c6e6 100644
--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateMetadataSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateMetadataSection.tsx
@@ -152,20 +152,22 @@ export const CertificateMetadataSection = ({ certificateId }: Props) => {
<CardHeader className="border-b">
<CardTitle>Metadata</CardTitle>
<CardDescription>Custom key-value pairs attached to this certificate</CardDescription>
- <CardAction>
- <IconButton
- aria-label="Edit certificate metadata"
- variant="outline"
- size="xs"
- onClick={() => {
- reset({ metadata: metadata.length > 0 ? metadata : [] });
- setIsModalOpen(true);
- }}
- isDisabled={!canEditMetadata}
- >
- <PencilIcon />
- </IconButton>
- </CardAction>
+ {!certificate?.deletedAt && (
+ <CardAction>
+ <IconButton
+ aria-label="Edit certificate metadata"
+ variant="outline"
+ size="xs"
+ onClick={() => {
+ reset({ metadata: metadata.length > 0 ? metadata : [] });
+ setIsModalOpen(true);
+ }}
+ isDisabled={!canEditMetadata}
+ >
+ <PencilIcon />
+ </IconButton>
+ </CardAction>
+ )}
</CardHeader>
<CardContent>
{metadata.length > 0 ? (
diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsx
index 81139eae93..c3e9a84a76 100644
--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateOverviewSection.tsx
@@ -23,6 +23,7 @@ import { CaType } from "@app/hooks/api/ca/enums";
import { TCertificateExternalMetadata } from "@app/hooks/api/certificates/types";
import {
+ getCertificateDeletedBySummary,
getCertificateDisplayStatus,
getCertSourceLabel,
getCertValidUntilBadgeDetails
@@ -130,13 +131,30 @@ export const CertificateOverviewSection = ({ certificateId }: Props) => {
<Detail>
<DetailLabel>Status</DetailLabel>
<DetailValue>
- {displayStatus.status === CertStatus.ACTIVE ? (
- <Badge variant={expiryVariant}>{expiryLabel}</Badge>
- ) : (
- <Badge variant={displayStatus.variant}>{displayStatus.label}</Badge>
- )}
+ <div className="flex items-center gap-1">
+ {displayStatus.status === CertStatus.ACTIVE ? (
+ <Badge variant={expiryVariant}>{expiryLabel}</Badge>
+ ) : (
+ <Badge variant={displayStatus.variant}>{displayStatus.label}</Badge>
+ )}
+ {certificate.deletedAt && certificate.status === CertStatus.REVOKED && (
+ <Badge variant="danger">Revoked</Badge>
+ )}
+ </div>
</DetailValue>
</Detail>
+ {certificate.deletedAt && (
+ <>
+ <Detail>
+ <DetailLabel>Deleted By</DetailLabel>
+ <DetailValue>{getCertificateDeletedBySummary(certificate)}</DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Deleted At</DetailLabel>
+ <DetailValue>{formatDateUTC(certificate.deletedAt)}</DetailValue>
+ </Detail>
+ </>
+ )}
<Detail>
<DetailLabel>Serial Number</DetailLabel>
<DetailValue className="flex items-center gap-2 font-mono text-xs">
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx
index ce8386b291..4bf3b3ca18 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx
@@ -35,7 +35,9 @@ import { CertificateManageRenewalModal } from "./CertificateManageRenewalModal";
import { CertificateRenewalModal } from "./CertificateRenewalModal";
import { CertificateRevocationModal } from "./CertificateRevocationModal";
import { CertificatesTable } from "./CertificatesTable";
+import { getCertificateDeletionWarning } from "./CertificatesTable.utils";
import type { FilterRule } from "./inventory-types";
+import { useCertificateHoldingSyncs } from "./useCertificateHoldingSyncs";
type CertificatesSectionProps = {
externalFilter?: {
@@ -136,6 +138,24 @@ export const CertificatesSection = ({
}
};
+ const deleteCertificateData = popUp?.deleteCertificate?.data as
+ | {
+ status: string;
+ notAfter: string;
+ hasPrivateKey?: boolean;
+ canRevoke?: boolean;
+ isRevocableAfterDeletion?: boolean;
+ certificateId?: string;
+ applicationId?: string | null;
+ }
+ | undefined;
+
+ const { holdingSyncs, isLoadingHoldingSyncs } = useCertificateHoldingSyncs({
+ certificateId: deleteCertificateData?.certificateId,
+ applicationId: deleteCertificateData?.applicationId ?? applicationId,
+ isEnabled: popUp.deleteCertificate.isOpen
+ });
+
return (
<Card className="mb-6">
<CardHeader>
@@ -214,11 +234,17 @@ export const CertificatesSection = ({
/>
<ConfirmationAlertDialog
isOpen={popUp.deleteCertificate.isOpen}
- title={`Are you sure you want to remove the certificate ${
+ title={`Delete certificate ${
(popUp?.deleteCertificate?.data as { commonName: string })?.commonName || ""
}?`}
- description="This action cannot be undone."
+ description={getCertificateDeletionWarning(
+ deleteCertificateData,
+ deleteCertificateData?.canRevoke,
+ deleteCertificateData?.isRevocableAfterDeletion,
+ holdingSyncs
+ )}
onOpenChange={(isOpen) => handlePopUpToggle("deleteCertificate", isOpen)}
+ isPending={isLoadingHoldingSyncs}
confirmKey="confirm"
onConfirm={() =>
onRemoveCertificateSubmit(
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx
index b4aa523b97..2995e43ed5 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx
@@ -95,12 +95,13 @@ import { UsePopUpState } from "@app/hooks/usePopUp";
import { ActiveFilterChips } from "./ActiveFilterChips";
import { AssignCertificateToApplicationModal } from "./AssignCertificateToApplicationModal";
import {
- getCertificateDeletionBlockReason,
+ canRevokeAfterDeletion,
getCertificateDisplayStatus,
getCertSourceLabel,
getCertValidUntilBadgeDetails,
isExpiringWithinOneDay,
isManagedCertificate,
+ liveCertificateStatusFilter,
RENEWAL_UNAVAILABLE_NO_PROFILE
} from "./CertificatesTable.utils";
import { ColumnVisibilityToggle, getDefaultVisibleColumns } from "./ColumnVisibilityToggle";
@@ -135,6 +136,11 @@ type Props = {
renewalError?: string;
renewedFromCertificateId?: string;
renewedByCertificateId?: string;
+ status?: string;
+ hasPrivateKey?: boolean;
+ canRevoke?: boolean;
+ isRevocableAfterDeletion?: boolean;
+ applicationId?: string | null;
}
) => void;
externalFilter?: {
@@ -220,7 +226,8 @@ export const CertificatesTable = ({
const getFiltersForSystemViewId = (viewId: string | undefined): FilterRule[] => {
if (viewId === "system-pqc") {
return [
- { id: "sv-pqc", field: "keyAlgorithm", operator: "in", value: [...PQC_KEY_ALGORITHMS] }
+ { id: "sv-pqc", field: "keyAlgorithm", operator: "in", value: [...PQC_KEY_ALGORITHMS] },
+ liveCertificateStatusFilter("sv-pqc-status")
];
}
if (viewId === "system-non-pqc") {
@@ -230,7 +237,8 @@ export const CertificatesTable = ({
field: "keyAlgorithm",
operator: "in",
value: [...NON_PQC_KEY_ALGORITHMS]
- }
+ },
+ liveCertificateStatusFilter("sv-non-pqc-status")
];
}
return [];
@@ -402,6 +410,7 @@ export const CertificatesTable = ({
metadataFilter: filterSearchParams.metadata,
applicationId,
applicationIds: filterSearchParams.applicationIds,
+ includeDeleted: true,
sortBy,
sortOrder
});
@@ -530,6 +539,10 @@ export const CertificatesTable = ({
setAppliedFilters([
{ id: "sv-status", field: "status", operator: "in", value: [CertStatus.REVOKED] }
]);
+ } else if (viewId === "system-deleted") {
+ setAppliedFilters([
+ { id: "sv-status", field: "status", operator: "in", value: [CertStatus.DELETED] }
+ ]);
} else if (viewId === "system-pqc") {
setAppliedFilters([
{
@@ -895,6 +908,7 @@ export const CertificatesTable = ({
const { variant, label } = getCertValidUntilBadgeDetails(certificate.notAfter);
const displayStatus = getCertificateDisplayStatus(certificate);
const isRevoked = certificate.status === CertStatus.REVOKED;
+ const isDeleted = Boolean(certificate.deletedAt);
const isExpired = new Date(certificate.notAfter) < new Date();
const isExpiringWithinDay = isExpiringWithinOneDay(certificate.notAfter);
const hasFailed = Boolean(certificate.renewalError);
@@ -923,6 +937,16 @@ export const CertificatesTable = ({
Boolean(certificate.caId) &&
(!certificateCaType ||
caSupportsCapability(certificateCaType, CaCapability.REVOKE_CERTIFICATES));
+ const isRevocableAfterDeletion = canRevokeAfterDeletion(
+ certificate,
+ certificateCaType
+ );
+ const canOfferRevoke =
+ canRevokeCertificate &&
+ !isRevoked &&
+ certificate.source !== CertSource.Discovered &&
+ (!isDeleted || isRevocableAfterDeletion) &&
+ !(isInventoryView && certificate.applicationId);
const canEditPkiSyncs =
permission.can(
ProjectPermissionPkiSyncActions.Edit,
@@ -930,6 +954,7 @@ export const CertificatesTable = ({
) || canEditPkiSyncsAtApplication;
const canShowAutoRenewalIcon = Boolean(
!isInventoryView &&
+ !isDeleted &&
certificate.profileId &&
certificate.hasPrivateKey !== false &&
!certificate.renewedByCertificateId &&
@@ -979,16 +1004,17 @@ export const CertificatesTable = ({
)}
{visibleColumns.has("status") && (
<TableCell>
- <Badge variant={displayStatus.variant}>{displayStatus.label}</Badge>
+ <div className="flex items-center gap-1">
+ <Badge variant={displayStatus.variant}>{displayStatus.label}</Badge>
+ {isDeleted && isRevoked && <Badge variant="danger">Revoked</Badge>}
+ </div>
</TableCell>
)}
{visibleColumns.has("health") && (
<TableCell>
- {isRevoked ? (
- <Badge variant="danger">Critical</Badge>
- ) : (
- <Badge variant={variant}>{label}</Badge>
- )}
+ {isDeleted && <EmptyCell />}
+ {!isDeleted && isRevoked && <Badge variant="danger">Critical</Badge>}
+ {!isDeleted && !isRevoked && <Badge variant={variant}>{label}</Badge>}
</TableCell>
)}
{visibleColumns.has("issuedAt") && (
@@ -1112,40 +1138,46 @@ export const CertificatesTable = ({
<IconButton
variant="ghost"
size="xs"
+ isDisabled={isDeleted && !canOfferRevoke}
onClick={(e) => e.stopPropagation()}
>
<MoreHorizontalIcon />
</IconButton>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" sideOffset={2}>
- <DropdownMenuItem
- isDisabled={!canReadCertificate}
- onClick={(e) => {
- e.stopPropagation();
- handlePopUpOpen("certificateExport", {
- certificateId: certificate.id,
- serialNumber: certificate.serialNumber
- });
- }}
- >
- <FileOutputIcon />
- Export Certificate
- </DropdownMenuItem>
- <DropdownMenuItem
- isDisabled={!canReadCertificate}
- onClick={(e) => {
- e.stopPropagation();
- handlePopUpOpen("certificateCert", {
- serialNumber: certificate.serialNumber
- });
- }}
- >
- <EyeIcon />
- View Details
- </DropdownMenuItem>
+ {!isDeleted && (
+ <DropdownMenuItem
+ isDisabled={!canReadCertificate}
+ onClick={(e) => {
+ e.stopPropagation();
+ handlePopUpOpen("certificateExport", {
+ certificateId: certificate.id,
+ serialNumber: certificate.serialNumber
+ });
+ }}
+ >
+ <FileOutputIcon />
+ Export Certificate
+ </DropdownMenuItem>
+ )}
+ {!isDeleted && (
+ <DropdownMenuItem
+ isDisabled={!canReadCertificate}
+ onClick={(e) => {
+ e.stopPropagation();
+ handlePopUpOpen("certificateCert", {
+ serialNumber: certificate.serialNumber
+ });
+ }}
+ >
+ <EyeIcon />
+ View Details
+ </DropdownMenuItem>
+ )}
{(() => {
const canManageRenewal =
!isInventoryView &&
+ !isDeleted &&
certificate.profileId &&
certificate.hasPrivateKey !== false &&
!certificate.renewedByCertificateId &&
@@ -1196,6 +1228,7 @@ export const CertificatesTable = ({
{(() => {
const canDisableRenewal =
!isInventoryView &&
+ !isDeleted &&
certificate.profileId &&
certificate.hasPrivateKey !== false &&
!certificate.renewedByCertificateId &&
@@ -1225,6 +1258,7 @@ export const CertificatesTable = ({
{(() => {
const isRenewable =
!isInventoryView &&
+ !isDeleted &&
!certificate.renewedByCertificateId &&
!isRevoked &&
!isExpired;
@@ -1269,6 +1303,7 @@ export const CertificatesTable = ({
);
})()}
{!isInventoryView &&
+ !isDeleted &&
certificate.status === CertStatus.ACTIVE &&
!certificate.renewedByCertificateId &&
certificate.source !== CertSource.Discovered && (
@@ -1286,26 +1321,21 @@ export const CertificatesTable = ({
Manage PKI Syncs
</DropdownMenuItem>
)}
- {hasProjectRole("admin") && !certificate.applicationId && (
- <DropdownMenuItem
- onClick={(e) => {
- e.stopPropagation();
- setAssignTargetId(certificate.id);
- }}
- >
- <BoxIcon />
- Assign to Application
- </DropdownMenuItem>
- )}
+ {hasProjectRole("admin") &&
+ !isDeleted &&
+ !certificate.applicationId && (
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ setAssignTargetId(certificate.id);
+ }}
+ >
+ <BoxIcon />
+ Assign to Application
+ </DropdownMenuItem>
+ )}
{(() => {
- if (
- !canRevokeCertificate ||
- isRevoked ||
- certificate.source === CertSource.Discovered ||
- (isInventoryView && certificate.applicationId)
- ) {
- return null;
- }
+ if (!canOfferRevoke) return null;
return (
<DropdownMenuItem
@@ -1323,49 +1353,28 @@ export const CertificatesTable = ({
</DropdownMenuItem>
);
})()}
- {!(isInventoryView && certificate.applicationId) &&
- (() => {
- const deletionBlockReason = getCertificateDeletionBlockReason(
- certificate,
- canRevokeCertificate
- );
-
- const item = (
- <DropdownMenuItem
- variant="danger"
- isDisabled={
- !canDeleteCertificate || Boolean(deletionBlockReason)
- }
- onClick={(e) => {
- e.stopPropagation();
- handlePopUpOpen("deleteCertificate", {
- certificateId: certificate.id,
- commonName: certificate.commonName
- });
- }}
- >
- <Trash2Icon />
- Delete Certificate
- </DropdownMenuItem>
- );
-
- if (!deletionBlockReason) return item;
-
- return (
- <Tooltip>
- <TooltipTrigger asChild>
- <div>{item}</div>
- </TooltipTrigger>
- <TooltipContent
- side="left"
- sideOffset={20}
- className="max-w-72"
- >
- {deletionBlockReason}
- </TooltipContent>
- </Tooltip>
- );
- })()}
+ {!isDeleted && !(isInventoryView && certificate.applicationId) && (
+ <DropdownMenuItem
+ variant="danger"
+ isDisabled={!canDeleteCertificate}
+ onClick={(e) => {
+ e.stopPropagation();
+ handlePopUpOpen("deleteCertificate", {
+ certificateId: certificate.id,
+ applicationId: certificate.applicationId,
+ commonName: certificate.commonName,
+ status: certificate.status,
+ notAfter: certificate.notAfter,
+ hasPrivateKey: certificate.hasPrivateKey,
+ canRevoke: canRevokeCertificate,
+ isRevocableAfterDeletion
+ });
+ }}
+ >
+ <Trash2Icon />
+ Delete Certificate
+ </DropdownMenuItem>
+ )}
</DropdownMenuContent>
</DropdownMenu>
</div>
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.test.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.test.ts
new file mode 100644
index 0000000000..fb71f7f38b
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.test.ts
@@ -0,0 +1,167 @@
+import { describe, expect, it } from "vitest";
+
+import { ActorType, UserAgentType } from "@app/hooks/api/auditLogs/enums";
+import { CertStatus } from "@app/hooks/api/certificates/enums";
+
+import {
+ getCertificateDeletedBySummary,
+ getCertificateDeletionWarning,
+ getCertificateDisplayStatus
+} from "./CertificatesTable.utils";
+
+const future = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString();
+const past = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
+const deletedAt = "2026-10-20T14:38:27.000Z";
+
+describe("getCertificateDisplayStatus", () => {
+ it("reports a deleted certificate as deleted ahead of every other state", () => {
+ expect(
+ getCertificateDisplayStatus({ status: CertStatus.ACTIVE, notAfter: future, deletedAt }).status
+ ).toBe(CertStatus.DELETED);
+ expect(
+ getCertificateDisplayStatus({ status: CertStatus.REVOKED, notAfter: future, deletedAt })
+ .status
+ ).toBe(CertStatus.DELETED);
+ expect(
+ getCertificateDisplayStatus({ status: CertStatus.ACTIVE, notAfter: past, deletedAt }).status
+ ).toBe(CertStatus.DELETED);
+ expect(
+ getCertificateDisplayStatus({
+ status: CertStatus.ACTIVE,
+ notAfter: future,
+ renewedByCertificateId: "next",
+ deletedAt
+ }).status
+ ).toBe(CertStatus.DELETED);
+ });
+
+ it("keeps revoked > expired > renewed > active for certificates that were not deleted", () => {
+ expect(getCertificateDisplayStatus({ status: CertStatus.REVOKED, notAfter: past }).status).toBe(
+ CertStatus.REVOKED
+ );
+ expect(
+ getCertificateDisplayStatus({
+ status: CertStatus.ACTIVE,
+ notAfter: past,
+ renewedByCertificateId: "next"
+ }).status
+ ).toBe(CertStatus.EXPIRED);
+ expect(
+ getCertificateDisplayStatus({
+ status: CertStatus.ACTIVE,
+ notAfter: future,
+ renewedByCertificateId: "next",
+ deletedAt: null
+ }).status
+ ).toBe(CertStatus.RENEWED);
+ expect(
+ getCertificateDisplayStatus({ status: CertStatus.ACTIVE, notAfter: future }).status
+ ).toBe(CertStatus.ACTIVE);
+ });
+});
+
+describe("getCertificateDeletionWarning", () => {
+ it("warns that an active certificate stays trusted unless it is revoked", () => {
+ expect(
+ getCertificateDeletionWarning(
+ { status: CertStatus.ACTIVE, notAfter: future, hasPrivateKey: true },
+ true
+ )
+ ).toContain("It stays trusted until");
+ });
+
+ it("tells the user to revoke first when the certificate cannot be revoked after deletion", () => {
+ expect(
+ getCertificateDeletionWarning({ status: CertStatus.ACTIVE, notAfter: future }, true, false)
+ ).toContain("It can't be revoked once deleted, so revoke it first");
+ });
+
+ it("does not offer revocation when the issuer cannot revoke", () => {
+ const warning = getCertificateDeletionWarning(
+ { status: CertStatus.ACTIVE, notAfter: future },
+ false
+ );
+ expect(warning).toContain("It stays valid until");
+ expect(warning).not.toContain("revoke");
+ });
+
+ it("does not claim a private key is deleted when none is held", () => {
+ expect(
+ getCertificateDeletionWarning({
+ status: CertStatus.ACTIVE,
+ notAfter: past,
+ hasPrivateKey: false
+ })
+ ).toBe("This removes the certificate.");
+ });
+
+ it("says nothing about trust for a revoked or expired certificate", () => {
+ expect(
+ getCertificateDeletionWarning({ status: CertStatus.REVOKED, notAfter: future }, true)
+ ).not.toContain("trusted");
+ expect(
+ getCertificateDeletionWarning({ status: CertStatus.ACTIVE, notAfter: past }, true)
+ ).not.toContain("trusted");
+ });
+});
+
+describe("getCertificateDeletionWarning sync removal", () => {
+ const expired = { status: CertStatus.ACTIVE, notAfter: past, hasPrivateKey: false };
+ const holdingSync = { id: "sync-1" };
+
+ it("says nothing about syncs when the certificate is in none", () => {
+ expect(getCertificateDeletionWarning(expired, false, true, [])).not.toContain("sync");
+ });
+
+ it("says the certificate is removed from the sync that holds it", () => {
+ expect(getCertificateDeletionWarning(expired, false, true, [holdingSync])).toContain(
+ "It's also removed from 1 certificate sync."
+ );
+ });
+
+ it("counts every sync that holds the certificate", () => {
+ expect(
+ getCertificateDeletionWarning(expired, false, true, [holdingSync, holdingSync, holdingSync])
+ ).toContain("It's also removed from 3 certificate syncs.");
+ });
+});
+
+describe("getCertificateDeletedBySummary", () => {
+ it("names the actor and says UI for deletions from the web app", () => {
+ expect(
+ getCertificateDeletedBySummary({
+ deletedByActorType: ActorType.USER,
+ deletedByActorName: "John Smith",
+ deletedVia: UserAgentType.WEB
+ })
+ ).toBe("John Smith via UI");
+ });
+
+ it("names the client for other callers and falls back when the actor is gone", () => {
+ expect(
+ getCertificateDeletedBySummary({
+ deletedByActorType: ActorType.IDENTITY,
+ deletedByActorName: null,
+ deletedVia: UserAgentType.TERRAFORM
+ })
+ ).toBe("A machine identity via Terraform");
+ expect(
+ getCertificateDeletedBySummary({
+ deletedByActorType: ActorType.USER,
+ deletedVia: UserAgentType.CLI
+ })
+ ).toBe("A user via CLI");
+ });
+
+ it("says API when the client is unknown", () => {
+ expect(
+ getCertificateDeletedBySummary({
+ deletedByActorType: ActorType.USER,
+ deletedVia: UserAgentType.OTHER
+ })
+ ).toBe("A user via API");
+ expect(
+ getCertificateDeletedBySummary({ deletedByActorType: ActorType.USER, deletedVia: null })
+ ).toBe("A user via API");
+ });
+});
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.ts
index e51973e836..64acad6daa 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.ts
@@ -1,5 +1,9 @@
+import { format } from "date-fns";
import ms from "ms";
+import { userAgentTypeToNameMap } from "@app/hooks/api/auditLogs/constants";
+import { ActorType, UserAgentType } from "@app/hooks/api/auditLogs/enums";
+import { CaType } from "@app/hooks/api/ca/enums";
import { CertSource, CertStatus } from "@app/hooks/api/certificates/enums";
import { TCertificateSource } from "@app/hooks/api/certificates/types";
@@ -30,9 +34,28 @@ type TCertificateStatusSource = {
status?: string | null;
notAfter: string;
renewedByCertificateId?: string | null;
+ deletedAt?: string | null;
};
+export const LIVE_CERTIFICATE_STATUSES = [
+ CertStatus.ACTIVE,
+ CertStatus.RENEWED,
+ CertStatus.EXPIRED,
+ CertStatus.REVOKED
+];
+
+export const liveCertificateStatusFilter = (id: string) => ({
+ id,
+ field: "status" as const,
+ operator: "in" as const,
+ value: [...LIVE_CERTIFICATE_STATUSES]
+});
+
export const getCertificateDisplayStatus = (certificate: TCertificateStatusSource) => {
+ if (certificate.deletedAt) {
+ return { status: CertStatus.DELETED, label: "Deleted", variant: "neutral" as const };
+ }
+
if (certificate.status === CertStatus.REVOKED) {
return { status: CertStatus.REVOKED, label: "Revoked", variant: "danger" as const };
}
@@ -48,33 +71,80 @@ export const getCertificateDisplayStatus = (certificate: TCertificateStatusSourc
return { status: CertStatus.ACTIVE, label: "Active", variant: "success" as const };
};
-const DELETION_BLOCKED_NOT_EXPIRED =
- "This certificate has not expired yet. Revoke it to retire it early, then delete it once it has expired.";
+type TCertificateDeletedBySource = {
+ deletedByActorType?: ActorType | null;
+ deletedByActorName?: string | null;
+ deletedVia?: UserAgentType | null;
+};
+
+export const getCertificateDeletedBySummary = (certificate: TCertificateDeletedBySource) => {
+ const fallbackActor =
+ certificate.deletedByActorType === ActorType.IDENTITY ? "A machine identity" : "A user";
+ const client = certificate.deletedVia;
+ let channel = "API";
+ if (client === UserAgentType.WEB) channel = "UI";
+ else if (client && client !== UserAgentType.OTHER && userAgentTypeToNameMap[client]) {
+ channel = userAgentTypeToNameMap[client];
+ }
-const DELETION_BLOCKED_NOT_EXPIRED_NO_ISSUER =
- "This certificate has not expired yet. Delete it once it has expired.";
+ return `${certificate.deletedByActorName || fallbackActor} via ${channel}`;
+};
-const DELETION_BLOCKED_REVOKED_NOT_EXPIRED =
- "This certificate was revoked but has not expired yet. Delete it once it has expired.";
+export const canRevokeAfterDeletion = (
+ certificate: { source?: string | null; profileId?: string | null },
+ caType?: string | null
+) =>
+ !(
+ certificate.source === CertSource.Imported &&
+ Boolean(certificate.profileId) &&
+ caType === CaType.INTERNAL
+ );
type TCertificateDeletionSource = {
status?: string | null;
notAfter: string;
- source?: string | null;
+ hasPrivateKey?: boolean;
+};
+
+const getCertificateSyncRemovalWarning = (holdingSyncs: unknown[]) => {
+ if (holdingSyncs.length === 0) return "";
+
+ return holdingSyncs.length === 1
+ ? " It's also removed from 1 certificate sync."
+ : ` It's also removed from ${holdingSyncs.length} certificate syncs.`;
};
-export const getCertificateDeletionBlockReason = (
- certificate: TCertificateDeletionSource,
- canRevoke: boolean
+const getCertificateTrustWarning = (
+ certificate: TCertificateDeletionSource | undefined,
+ canRevoke: boolean,
+ isRevocableAfterDeletion: boolean
) => {
- const source = certificate.source ?? CertSource.Issued;
- const hasExpired = new Date(certificate.notAfter) <= new Date();
+ if (
+ !certificate ||
+ certificate.status === CertStatus.REVOKED ||
+ new Date(certificate.notAfter) <= new Date()
+ ) {
+ return "";
+ }
+
+ const expiresOn = format(new Date(certificate.notAfter), "yyyy-MM-dd");
+ if (!canRevoke) return ` It stays valid until ${expiresOn}.`;
+ if (isRevocableAfterDeletion) return ` It stays trusted until ${expiresOn} unless you revoke it.`;
+ return " It can't be revoked once deleted, so revoke it first if clients should stop trusting it.";
+};
- if (hasExpired) return null;
- if (certificate.status === CertStatus.REVOKED) return DELETION_BLOCKED_REVOKED_NOT_EXPIRED;
- if (source === CertSource.Discovered || source === CertSource.Imported) return null;
+export const getCertificateDeletionWarning = (
+ certificate?: TCertificateDeletionSource,
+ canRevoke = false,
+ isRevocableAfterDeletion = true,
+ holdingSyncs: unknown[] = []
+) => {
+ const removed =
+ certificate?.hasPrivateKey === false
+ ? "This removes the certificate."
+ : "This removes the certificate and its private key.";
- return canRevoke ? DELETION_BLOCKED_NOT_EXPIRED : DELETION_BLOCKED_NOT_EXPIRED_NO_ISSUER;
+ return `${removed}${getCertificateTrustWarning(certificate, canRevoke, isRevocableAfterDeletion)}${getCertificateSyncRemovalWarning(holdingSyncs)}`;
};
export const isExpiringWithinOneDay = (notAfter: string): boolean => {
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/inventory-types.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/inventory-types.ts
index c7cc23f564..51e01ac0cd 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/inventory-types.ts
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/inventory-types.ts
@@ -26,7 +26,8 @@ export const FILTER_FIELDS: FilterFieldDefinition[] = [
{ value: CertStatus.ACTIVE, label: "Active" },
{ value: CertStatus.RENEWED, label: "Renewed" },
{ value: CertStatus.EXPIRED, label: "Expired" },
- { value: CertStatus.REVOKED, label: "Revoked" }
+ { value: CertStatus.REVOKED, label: "Revoked" },
+ { value: CertStatus.DELETED, label: "Deleted" }
]
},
{
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificateHoldingSyncs.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificateHoldingSyncs.ts
new file mode 100644
index 0000000000..24dd8578dd
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificateHoldingSyncs.ts
@@ -0,0 +1,53 @@
+import { useQuery } from "@tanstack/react-query";
+
+import { useProject, useProjectPermission } from "@app/context";
+import {
+ ProjectPermissionPkiSyncActions,
+ ProjectPermissionSub
+} from "@app/context/ProjectPermissionContext/types";
+import { useGetPkiApplicationPermissions } from "@app/hooks/api/pkiApplications/queries";
+import {
+ PkiApplicationResourceActions,
+ PkiApplicationResourceSub
+} from "@app/hooks/api/pkiApplications/types";
+import { fetchPkiSyncsByProjectId, pkiSyncKeys } from "@app/hooks/api/pkiSyncs/queries";
+
+export const useCertificateHoldingSyncs = ({
+ certificateId,
+ applicationId,
+ isEnabled
+}: {
+ certificateId?: string;
+ applicationId?: string | null;
+ isEnabled: boolean;
+}) => {
+ const { currentProject } = useProject();
+ const { permission } = useProjectPermission();
+ const { data: appPermissionData } = useGetPkiApplicationPermissions(applicationId ?? "");
+
+ const canReadSyncs =
+ permission.can(ProjectPermissionPkiSyncActions.Read, ProjectPermissionSub.PkiSyncs) ||
+ Boolean(
+ applicationId &&
+ appPermissionData?.permission?.can(
+ PkiApplicationResourceActions.Read,
+ PkiApplicationResourceSub.PkiSyncs
+ )
+ );
+
+ const projectId = currentProject?.id || "";
+ const isQueryEnabled = isEnabled && Boolean(projectId) && Boolean(certificateId) && canReadSyncs;
+ const { data: syncs = [], isPending } = useQuery({
+ queryKey: [
+ ...pkiSyncKeys.listWithCertificate(projectId, certificateId || ""),
+ applicationId ?? null
+ ],
+ queryFn: () => fetchPkiSyncsByProjectId(projectId, certificateId, applicationId ?? undefined),
+ enabled: isQueryEnabled
+ });
+
+ return {
+ holdingSyncs: syncs.filter((sync) => sync.hasCertificate),
+ isLoadingHoldingSyncs: isQueryEnabled && isPending
+ };
+};
diff --git a/frontend/src/pages/cert-manager/DashboardPage/components/KpiCards.tsx b/frontend/src/pages/cert-manager/DashboardPage/components/KpiCards.tsx
index d541f94dec..e207277d20 100644
--- a/frontend/src/pages/cert-manager/DashboardPage/components/KpiCards.tsx
+++ b/frontend/src/pages/cert-manager/DashboardPage/components/KpiCards.tsx
@@ -2,6 +2,7 @@ import { AlertTriangle, FileCheck, FileClock, FileKey, FileX } from "lucide-reac
import { Badge, Card, CardContent } from "@app/components/v3";
import type { TDashboardStats } from "@app/hooks/api/certificates";
+import { LIVE_CERTIFICATE_STATUSES } from "@app/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils";
import { formatShare } from "./chart-theme";
@@ -18,7 +19,7 @@ const cards = [
icon: FileKey,
iconClass: "text-org",
iconBg: "bg-org/10 border-org/20",
- filters: {} as Record<string, string>
+ filters: { filterStatus: LIVE_CERTIFICATE_STATUSES.join(",") } as Record<string, string>
},
{
key: "active" as const,
diff --git a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsx b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsx
index dd55032c70..c4dddb95aa 100644
--- a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsx
@@ -97,6 +97,16 @@ export const DiscoveryDetailsSection = ({ discovery }: Props) => {
</DetailValue>
</Detail>
)}
+ <Detail>
+ <DetailLabel>Restore Deleted Certificates</DetailLabel>
+ <DetailValue>
+ {discovery.restoreDeletedCertificates ? (
+ <Badge variant="success">Enabled</Badge>
+ ) : (
+ <Badge variant="neutral">Disabled</Badge>
+ )}
+ </DetailValue>
+ </Detail>
</DetailGroup>
</CardContent>
</Card>
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryDetailsFields.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryDetailsFields.tsx
index b045de01f4..e72c759ee4 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryDetailsFields.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryDetailsFields.tsx
@@ -114,6 +114,27 @@ export const DiscoveryDetailsFields = () => {
)}
/>
)}
+ <Controller
+ control={control}
+ name="restoreDeletedCertificates"
+ render={({ field: { value, onChange } }) => (
+ <Field orientation="horizontal" className="mb-4">
+ <FieldContent>
+ <Label htmlFor="restore-deleted-certificates">Restore Deleted Certificates</Label>
+ <FieldDescription>
+ Restore a deleted certificate when a scan finds it again, unless it&apos;s in an
+ Application or was issued from a certificate profile or CA.
+ </FieldDescription>
+ </FieldContent>
+ <Toggle
+ id="restore-deleted-certificates"
+ variant="project"
+ checked={value}
+ onCheckedChange={onChange}
+ />
+ </Field>
+ )}
+ />
</>
);
};
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobForm.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobForm.tsx
index d1afb4c6e1..6561e8a4c3 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobForm.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobForm.tsx
@@ -100,7 +100,13 @@ const STEP_FIELDS: Record<DiscoveryJobStep, FieldPath<TDiscoveryJobForm>[]> = {
[DiscoveryJobStep.Hosts]: ["connections"],
[DiscoveryJobStep.Folders]: ["searchFolderPaths", "skipFolderPaths"],
[DiscoveryJobStep.Options]: ["maxFolderDepth", "importStandaloneCaCertificates"],
- [DiscoveryJobStep.Details]: ["name", "description", "isAutoScanEnabled", "scanIntervalDays"],
+ [DiscoveryJobStep.Details]: [
+ "name",
+ "description",
+ "isAutoScanEnabled",
+ "scanIntervalDays",
+ "restoreDeletedCertificates"
+ ],
[DiscoveryJobStep.Review]: []
};
@@ -183,7 +189,8 @@ export const DiscoveryJobForm = ({
const payload = {
name: form.name,
targetConfig: buildTargetConfig(form),
- isAutoScanEnabled: form.isAutoScanEnabled
+ isAutoScanEnabled: form.isAutoScanEnabled,
+ restoreDeletedCertificates: form.restoreDeletedCertificates
};
if (discovery) {
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryReviewFields.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryReviewFields.tsx
index b5aaf607ba..5c5f4d518e 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryReviewFields.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryReviewFields.tsx
@@ -117,6 +117,11 @@ export const DiscoveryReviewFields = () => {
</ReviewDetail>
<ReviewDetail label="Name">{values.name}</ReviewDetail>
<ReviewDetail label="Schedule">{scheduleLabel}</ReviewDetail>
+ <ReviewDetail label="Restore Deleted Certificates">
+ <Badge variant={values.restoreDeletedCertificates ? "success" : "neutral"}>
+ {values.restoreDeletedCertificates ? "Enabled" : "Disabled"}
+ </Badge>
+ </ReviewDetail>
<ReviewDetail label="Description">{values.description}</ReviewDetail>
</ReviewGroup>
</div>
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/discovery-job-form-schema.ts b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/discovery-job-form-schema.ts
index 9424648f05..94b3d2724a 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/discovery-job-form-schema.ts
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/discovery-job-form-schema.ts
@@ -107,6 +107,7 @@ const BaseSchema = z.object({
name: slugSchema({ field: "Name", max: 100 }),
description: z.string().trim().max(255, "Description can be at most 255 characters").optional(),
isAutoScanEnabled: z.boolean(),
+ restoreDeletedCertificates: z.boolean(),
scanIntervalDays: z
.number()
.min(1, "Enter an interval between 1 and 365 days")
@@ -170,6 +171,7 @@ export const getDefaultFormValues = (
name: discovery?.name ?? "",
description: discovery?.description ?? "",
isAutoScanEnabled: discovery?.isAutoScanEnabled ?? false,
+ restoreDeletedCertificates: discovery?.restoreDeletedCertificates ?? false,
scanIntervalDays: discovery?.scanIntervalDays ?? 7
};
diff --git a/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationCertificatesSection.tsx b/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationCertificatesSection.tsx
index aac6751181..ea125448b9 100644
--- a/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationCertificatesSection.tsx
+++ b/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationCertificatesSection.tsx
@@ -85,9 +85,11 @@ export const InstallationCertificatesSection = ({ certificates, emptyState }: Pr
>
<TableCell>{cert.commonName || "N/A"}</TableCell>
<TableCell>
- {expiryDetails ? (
+ {cert.deletedAt && <Badge variant="neutral">Deleted</Badge>}
+ {!cert.deletedAt && expiryDetails && (
<Badge variant={expiryDetails.variant}>{expiryDetails.label}</Badge>
- ) : (
+ )}
+ {!cert.deletedAt && !expiryDetails && (
<Badge variant="neutral">Unknown</Badge>
)}
</TableCell>
diff --git a/frontend/src/pages/cert-manager/InventoryPage/InventoryPage.tsx b/frontend/src/pages/cert-manager/InventoryPage/InventoryPage.tsx
index b7acb86a63..49f0fa7d50 100644
--- a/frontend/src/pages/cert-manager/InventoryPage/InventoryPage.tsx
+++ b/frontend/src/pages/cert-manager/InventoryPage/InventoryPage.tsx
@@ -12,6 +12,7 @@ import {
import { ProjectType } from "@app/hooks/api/projects/types";
import { CertManagerAdminOnly } from "@app/pages/cert-manager/components/CertManagerAdminOnly";
+import { liveCertificateStatusFilter } from "../CertificatesPage/components/CertificatesTable.utils";
import type { FilterRule } from "../CertificatesPage/components/inventory-types";
import { CertificatesTab } from "../PoliciesPage/components/CertificatesTab";
@@ -30,7 +31,7 @@ export const InventoryPage = () => {
id: "dash-status",
field: "status",
operator: "in",
- value: [searchParams.filterStatus]
+ value: searchParams.filterStatus.split(",")
});
}
if (searchParams.filterEnrollmentType) {
@@ -79,6 +80,9 @@ export const InventoryPage = () => {
value: afterDate.toISOString().split("T")[0]
});
}
+ if (filters.length > 0 && !filters.some((filter) => filter.field === "status")) {
+ filters.push(liveCertificateStatusFilter("dash-status"));
+ }
return filters;
}, [searchParams]);