Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Address PR comments
Carlos Monastyrski99093f965829
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 270d7e9e24..0a14c8fbf1 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -945,10 +945,10 @@ Note that `logger.ts` also has a `redactedKeys` list applied to structured-objec### 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:+Deleting a certificate stamps `deletedAt`, `deletedByActorType` and `deletedByActorId` 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@@ -965,26 +965,20 @@ pointing at something. Things that rely on that:- **CRL and OCSP keep deleted certificates.** Deletion is not revocation, so a revoked certificate stays onthe 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 and the issuance queue, and EST re-enroll and SCEP renewal refuse a deleted client- certificate. A renewal the CA already accepted before the delete still completes and links to the deleted- original, because the CA has issued that certificate and discarding it would lose it.-- **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. If the body can't be read, the delete fails and nothing is removed.+ entry points and the first attempt of the issuance job, and EST re-enroll and SCEP renewal refuse a deleted+ client certificate. A renewal the CA already accepted before the delete (an ACM renewal still polling, a+ DigiCert or GoDaddy order) still completes and links to the deleted original, because the CA has issued+ that certificate and discarding it would lose it.+- **A sync can still write a link for a certificate deleted mid-run.** `certificate_syncs` inserts are not+ filtered on `deletedAt`, so a provider that uploads and then records the link leaves a tracking row, and the+ sync the delete queued removes that copy from the destination through it.+- **Deleted certificates are not restored.** Serial numbers stay globally unique+ (`certificates_serialnumber_unique`), so re-importing a deleted certificate into the same project fails with+ the deleted message (any other project gets the generic serial conflict, so nothing about it leaks), and+ rediscovery links the installation to the deleted row instead of creating a new one.- **A deleted certificate keeps its HSM key reference** (`keySource`, connector, key label and id), so therecord stays true for audits. Deleting the connector detaches deleted rows (`hsmConnectorId` set to null),- which is why the key source CHECK requires only a key label for `hsm`, not a connector. The rollback leaves- that CHECK in place.-- **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.+ which is why the key source CHECK requires a connector only while `deletedAt` is null.### Certificate revocation: CRL and OCSPdiff --git a/backend/src/db/migrations/20261020143827_add-soft-delete-to-certificates.ts b/backend/src/db/migrations/20261020143827_add-soft-delete-to-certificates.tsindex 4d59f35d94..861c6279c5 100644--- a/backend/src/db/migrations/20261020143827_add-soft-delete-to-certificates.ts+++ b/backend/src/db/migrations/20261020143827_add-soft-delete-to-certificates.ts@@ -1,80 +1,40 @@import { Knex } from "knex";import { TableName } from "../schemas";+import { createIndexConcurrently, withMigrationConnection } from "./utils/concurrent-index";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 KEY_SOURCE_CHECK = `("keySource" = 'infisical') OR ("keySource" = 'hsm' AND "hsmKeyLabel" IS NOT NULL)`;+const LIVE_KEY_SOURCE_CHECK = `("keySource" = 'infisical') OR ("keySource" = 'hsm' AND "hsmConnectorId" IS NOT NULL AND "hsmKeyLabel" IS NOT NULL)`;+const SOFT_DELETE_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) => {- 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 (${KEY_SOURCE_CHECK}) 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}"`);- });+const replaceKeySourceCheck = async (tx: Knex, checkExpression: string) => {+ 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+ ]);};export async function up(knex: Knex): Promise<void> {+ const hasDeletedAt = await knex.schema.hasColumn(TableName.Certificate, "deletedAt");+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]- );+ if (!hasDeletedAt) {+ await tx.schema.alterTable(TableName.Certificate, (t) => {+ t.datetime("deletedAt", { useTz: true }).nullable();+ t.string("deletedByActorType").nullable();+ t.uuid("deletedByActorId").nullable();+ });+ }+ await replaceKeySourceCheck(tx, SOFT_DELETE_KEY_SOURCE_CHECK);});- await replaceKeySourceCheck(knex);-const hasQuotaKey = await knex.schema.hasColumn(TableName.Certificate, "quotaKey");await withMigrationConnection(knex, async (raw) => {await createIndexConcurrently(@@ -110,13 +70,19 @@ export async function down(knex: Knex): Promise<void> {await raw(`DROP INDEX CONCURRENTLY IF EXISTS "${DELETED_INDEX_NAME}"`);});+ const hasDeletedAt = await knex.schema.hasColumn(TableName.Certificate, "deletedAt");+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]);+ await tx.raw(`ALTER TABLE ?? DROP CONSTRAINT IF EXISTS ??`, [TableName.Certificate, KEY_SOURCE_CHECK_NAME]);+ if (hasDeletedAt) {+ await tx.schema.alterTable(TableName.Certificate, (t) => {+ t.dropColumn("deletedAt");+ t.dropColumn("deletedByActorType");+ t.dropColumn("deletedByActorId");+ });+ }+ await replaceKeySourceCheck(tx, LIVE_KEY_SOURCE_CHECK);});}diff --git a/backend/src/db/migrations/utils/concurrent-index.ts b/backend/src/db/migrations/utils/concurrent-index.tsnew file mode 100644index 0000000000..a42ef155f1--- /dev/null+++ b/backend/src/db/migrations/utils/concurrent-index.ts@@ -0,0 +1,39 @@+import { Knex } from "knex";++const MIGRATION_STATEMENT_TIMEOUT = 60 * 60 * 1000;+const MIGRATION_LOCK_TIMEOUT = 30 * 1000;++export type TMigrationRaw = (sql: string) => Knex.Raw;++export const withMigrationConnection = async (knex: Knex, run: (raw: TMigrationRaw) => Promise<void>) => {+ const connection = await knex.client.acquireConnection();+ const raw: TMigrationRaw = (sql) => 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_STATEMENT_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);+ }+};++export const createIndexConcurrently = async (raw: TMigrationRaw, 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}`);+};diff --git a/backend/src/db/schemas/certificates.ts b/backend/src/db/schemas/certificates.tsindex 7c711e3ae8..5cb7f95683 100644--- a/backend/src/db/schemas/certificates.ts+++ b/backend/src/db/schemas/certificates.ts@@ -61,8 +61,7 @@ export const CertificatesSchema = z.object({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()+ deletedByActorId: z.string().uuid().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.tsindex fa2da13f14..1f8a93b7c1 100644--- a/backend/src/db/schemas/pki-discovery-configs.ts+++ b/backend/src/db/schemas/pki-discovery-configs.ts@@ -24,8 +24,7 @@ export const PkiDiscoveryConfigsSchema = z.object({lastScannedAt: z.date().nullable().optional(),createdAt: z.date(),updatedAt: z.date(),- gatewayPoolId: z.string().uuid().nullable().optional(),- restoreDeletedCertificates: z.boolean().default(false)+ gatewayPoolId: z.string().uuid().nullable().optional()});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.tsindex 793bc8f2a6..95a765e61a 100644--- a/backend/src/ee/routes/v1/pki-discovery-router.ts+++ b/backend/src/ee/routes/v1/pki-discovery-router.ts@@ -25,9 +25,6 @@ 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",@@ -88,12 +85,7 @@ 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"),- restoreDeletedCertificates: z- .boolean()- .optional()- .default(false)- .describe(RESTORE_DELETED_CERTIFICATES_DESCRIPTION)+ gatewayPoolId: z.string().uuid().optional().describe("Gateway pool ID for scanning private networks")}).superRefine((data, ctx) => {if (data.gatewayId && data.gatewayPoolId) {@@ -121,7 +113,6 @@ 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,@@ -135,8 +126,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>type: EventType.CREATE_PKI_DISCOVERY,metadata: {discoveryId: discovery.id,- name: discovery.name,- restoreDeletedCertificates: discovery.restoreDeletedCertificates+ name: discovery.name}}});@@ -302,8 +292,7 @@ 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"),- restoreDeletedCertificates: z.boolean().optional().describe(RESTORE_DELETED_CERTIFICATES_DESCRIPTION)+ isActive: z.boolean().optional().describe("Whether the discovery configuration is active")}).superRefine((data, ctx) => {if (data.gatewayId && data.gatewayPoolId) {@@ -330,7 +319,6 @@ 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,@@ -344,8 +332,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>type: EventType.UPDATE_PKI_DISCOVERY,metadata: {discoveryId: discovery.id,- name: discovery.name,- restoreDeletedCertificates: discovery.restoreDeletedCertificates+ name: discovery.name}}});diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 36e927c646..2d820459a8 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -41,8 +41,6 @@ import { TApprovalRequestSubjectMetadata } from "@app/services/approval-policy/aimport { ActorType } from "@app/services/auth/auth-type";import {CertExtendedKeyUsage,- CertificateDeletionEligibility,- CertificateRestoreSource,CertKeyAlgorithm,CertKeyUsage,CertStatus,@@ -444,7 +442,6 @@ 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",@@ -3240,24 +3237,6 @@ 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: {@@ -3296,7 +3275,6 @@ interface DeleteCert {notAfter: string;source: CertificateSource;statusAtDeletion: CertStatus;- deletionAllowedReason: CertificateDeletionEligibility;applicationId?: string | null;applicationName?: string | null;};@@ -4974,7 +4952,6 @@ interface CreatePkiDiscoveryEvent {metadata: {discoveryId: string;name: string;- restoreDeletedCertificates?: boolean;};}@@ -4983,7 +4960,6 @@ interface UpdatePkiDiscoveryEvent {metadata: {discoveryId: string;name: string;- restoreDeletedCertificates?: boolean;};}@@ -8296,7 +8272,6 @@ export type Event =| GetCaCertificateTemplates| GetCert| DeleteCert- | RestoreCert| RevokeCert| AssignCertToApplication| GetCertBodydiff --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.tsindex 60e4926651..de92071e00 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,7 +3,6 @@ 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";@@ -50,12 +49,7 @@ import {TCertificateScanResponse} from "./pki-discovery-host-fns";import { TPkiDiscoveryInstallationDALFactory } from "./pki-discovery-installation-dal";-import {- buildDeletedCertificatePolicy,- processDiscoveredCertificate,- TDeletedCertificatePolicy,- TKmsEncryptor-} from "./pki-discovery-scan-fns";+import { processDiscoveredCertificate, TKmsEncryptor } from "./pki-discovery-scan-fns";import { TPkiDiscoveryScanHistoryDALFactory } from "./pki-discovery-scan-history-dal";import {discardScanRunIfDeleted,@@ -97,7 +91,6 @@ export type THostScanDeps = {gatewayPoolService: Pick<TGatewayPoolServiceFactory, "selectGatewayFromPool">;keyStore: Pick<TKeyStoreFactory, "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete">;telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;- auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;};type TResolvedHost = {@@ -318,7 +311,6 @@ type TWriteContext = {scanTime: Date;importStandaloneCaCertificates: boolean;kmsEncryptor: TKmsEncryptor;- deletedCertificatePolicy: TDeletedCertificatePolicy;certificateIdsByFingerprint: Map<string, string>;targetInstallationId?: string;};@@ -362,8 +354,7 @@ const importCertificateChains = async ({certificateDAL: deps.certificateDAL,certificateBodyDAL: deps.certificateBodyDAL,- kmsEncryptor: ctx.kmsEncryptor,- deletedCertificatePolicy: ctx.deletedCertificatePolicy+ kmsEncryptor: ctx.kmsEncryptor},{discoveredBy: ctx.discoveryId,@@ -621,12 +612,6 @@ export const executeLinuxServerScan = async (discoveryId: string, deps: THostScascanTime: 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.tsindex 828533f213..2e87354f06 100644--- a/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts+++ b/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts@@ -1,4 +1,3 @@-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";@@ -41,7 +40,6 @@ 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;@@ -66,8 +64,7 @@ export const pkiDiscoveryQueueFactory = ({gatewayV2DAL,gatewayPoolService,telemetryService,- keyStore,- auditLogService+ keyStore}: TPkiDiscoveryQueueFactoryDep) => {const scanDeps = {appConnectionDAL,@@ -84,8 +81,7 @@ export const pkiDiscoveryQueueFactory = ({gatewayV2DAL,gatewayPoolService,telemetryService,- keyStore,- auditLogService+ keyStore};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.tsindex 80de5fb3b3..4396cb40a7 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,7 +11,6 @@ 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 {@@ -98,12 +97,6 @@ export const rescanInstallation = async (installationId: string, deps: THostScanscanTime: 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.tsindex 912285ebae..90267a0ea9 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,8 +3,7 @@ import { Knex } from "knex";import net from "net";import pLimit from "p-limit";-import { TCertificates, TCertificatesInsert, TPkiCertificateInstallationsInsert } from "@app/db/schemas";-import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";+import { TCertificatesInsert, TPkiCertificateInstallationsInsert } from "@app/db/schemas";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";@@ -13,11 +12,9 @@ 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 { canRestoreDeletedCertificate } from "@app/services/certificate/certificate-fns";-import { CertificateRestoreSource, CertStatus } from "@app/services/certificate/certificate-types";+import { 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";@@ -69,44 +66,8 @@ 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,@@ -340,12 +301,6 @@ 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;@@ -365,7 +320,6 @@ export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps):now,deps,kmsEncryptor,- deletedCertificatePolicy,effectiveGatewayId ?? undefined,gatewayName,discoveryConfig.gatewayPoolId ?? effectiveGatewayId ?? undefined@@ -545,7 +499,6 @@ const processEndpointResult = async (scanTime: Date,deps: TExecuteScanDeps,kmsEncryptor: TKmsEncryptor,- deletedCertificatePolicy: TDeletedCertificatePolicy,gatewayId?: string,gatewayName?: string,fingerprintGatewayKey?: string@@ -591,7 +544,7 @@ const processEndpointResult = async (const certId = await processDiscoveredCertificate(certResult,projectId,- { certificateDAL, certificateBodyDAL, kmsEncryptor, deletedCertificatePolicy },+ { certificateDAL, certificateBodyDAL, kmsEncryptor },{discoveredBy: discoveryId,host: result.host,@@ -640,7 +593,6 @@ type TProcessDiscoveredCertDeps = {certificateDAL: TCertificateDALFactory;certificateBodyDAL: TCertificateBodyDALFactory;kmsEncryptor: TKmsEncryptor;- deletedCertificatePolicy: TDeletedCertificatePolicy;};export const processDiscoveredCertificate = async (@@ -649,7 +601,7 @@ export const processDiscoveredCertificate = async (deps: TProcessDiscoveredCertDeps,discoveryMetadata?: Record<string, unknown>): Promise<string | null> => {- const { certificateDAL, certificateBodyDAL, kmsEncryptor, deletedCertificatePolicy } = deps;+ const { certificateDAL, certificateBodyDAL, kmsEncryptor } = deps;try {const existingCerts = await certificateDAL.find({@@ -657,17 +609,8 @@ export const processDiscoveredCertificate = async (fingerprintSha256: certResult.fingerprint});- 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;+ if (existingCerts.length > 0) {+ return existingCerts[0].id;}const friendlyName =@@ -679,8 +622,9 @@ 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" | "status"> = {+ const certData: Omit<TCertificatesInsert, "quotaKey"> = {projectId,+ status: CertStatus.ACTIVE,serialNumber: truncateString(serialNumber, DB_SHORT_VARCHAR_LIMIT) || "unknown",friendlyName,commonName: truncateString(certResult.commonName, DB_SHORT_VARCHAR_LIMIT) || "Unknown",@@ -723,23 +667,7 @@ export const processDiscoveredCertificate = async (}const newCert = await certificateDAL.transaction(async (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;+ const cert = await certificateDAL.create(certData, tx);if (encryptedCertificate) {await certificateBodyDAL.create(@@ -755,9 +683,6 @@ 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.tsindex bcf52b7798..d513562b09 100644--- a/backend/src/ee/services/pki-discovery/pki-discovery-service.ts+++ b/backend/src/ee/services/pki-discovery/pki-discovery-service.ts@@ -181,7 +181,6 @@ export const pkiDiscoveryServiceFactory = ({gatewayId,gatewayPoolId,orgActor,- restoreDeletedCertificates,actor,actorId,actorAuthMethod,@@ -273,8 +272,7 @@ export const pkiDiscoveryServiceFactory = ({scanIntervalDays: isAutoScanEnabled ? scanIntervalDays : null,gatewayId: gatewayPoolId ? null : gatewayId,gatewayPoolId: gatewayPoolId ?? null,- isActive: true,- restoreDeletedCertificates+ isActive: true});return discovery;@@ -300,7 +298,6 @@ export const pkiDiscoveryServiceFactory = ({gatewayPoolId,isActive,orgActor,- restoreDeletedCertificates,actor,actorId,actorAuthMethod,@@ -399,8 +396,7 @@ export const pkiDiscoveryServiceFactory = ({scanIntervalDays: isAutoScanEnabled ? scanIntervalDays : null,gatewayId: gatewayIdValue,gatewayPoolId: gatewayPoolIdValue,- isActive,- restoreDeletedCertificates+ isActive});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.tsindex 93ba6281aa..25da2d47be 100644--- a/backend/src/ee/services/pki-discovery/pki-discovery-types.ts+++ b/backend/src/ee/services/pki-discovery/pki-discovery-types.ts@@ -132,7 +132,6 @@ export type TCreatePkiDiscoveryDTO = {gatewayId?: string | null;gatewayPoolId?: string | null;orgActor: OrgServiceActor;- restoreDeletedCertificates?: boolean;} & Omit<TProjectPermission, "projectId">;export type TUpdatePkiDiscoveryDTO = {@@ -146,7 +145,6 @@ export type TUpdatePkiDiscoveryDTO = {gatewayPoolId?: string | null;isActive?: boolean;orgActor: OrgServiceActor;- restoreDeletedCertificates?: boolean;} & Omit<TProjectPermission, "projectId">;export type TDeletePkiDiscoveryDTO = {diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 400f429e10..07831309ef 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -2310,9 +2310,7 @@ export const CERTIFICATES = {"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."+ deletedByActorName: "The name of the user or machine identity that deleted this certificate, if it still exists."},RENEW: {id: "The ID of the certificate to renew.",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 73f3dc7378..050ad7fb2c 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -4345,8 +4345,7 @@ export const registerRoutes = async (gatewayV2DAL,gatewayPoolService,telemetryService,- keyStore,- auditLogService+ keyStore});const pkiDiscoveryService = pkiDiscoveryServiceFactory({diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.tsindex 2300df1402..08a8d5d863 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, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";+import { EventType } 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";@@ -16,12 +16,7 @@ import { getTelemetryDistinctId } from "@app/server/lib/telemetry";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { ActorType, AuthMode } from "@app/services/auth/auth-type";import { SanitizedCertificateSchema } from "@app/services/certificate/certificate-schemas";-import {- CertificateRestoreSource,- CertKeyAlgorithm,- CertSignatureAlgorithm,- CrlReason-} from "@app/services/certificate/certificate-types";+import { 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 {@@ -1516,7 +1511,6 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {.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()})})@@ -1788,45 +1782,33 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {}},handler: async (req) => {- 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 { 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 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: restoredFromDeletion- ? {- type: EventType.RESTORE_CERT,- metadata: { ...importMetadata, restoredVia: CertificateRestoreSource.Import }- }- : { type: EventType.IMPORT_CERT, metadata: importMetadata }+ 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+ }+ }});await server.services.telemetry.sendPostHogEvents({@@ -1947,15 +1929,14 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {}},handler: async (req) => {- 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- });+ const { deletedCert, applicationName, statusAtDeletion } = 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,@@ -1970,7 +1951,6 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {notAfter: deletedCert.notAfter.toISOString(),source: (deletedCert.source as CertificateSource | null) ?? CertificateSource.Issued,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.tsindex 151c30e378..e9f88601f1 100644--- a/backend/src/server/routes/v1/deprecated-certificate-router.ts+++ b/backend/src/server/routes/v1/deprecated-certificate-router.ts@@ -13,12 +13,7 @@ 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,- CertificateRestoreSource,- CertKeyUsage,- CrlReason-} from "@app/services/certificate/certificate-types";+import { CertExtendedKeyUsage, CertKeyUsage, CrlReason } from "@app/services/certificate/certificate-types";import {validateAltNamesField,validateCaDateField@@ -330,7 +325,7 @@ export const registerDeprecatedCertRouter = async (server: FastifyZodProvider) =}},handler: async (req) => {- const { certificate, certificateChain, privateKey, serialNumber, cert, applicationName, restoredFromDeletion } =+ const { certificate, certificateChain, privateKey, serialNumber, cert, applicationName } =await server.services.certificate.importCert({actor: req.permission.type,actorId: req.permission.id,@@ -342,28 +337,16 @@ export const registerDeprecatedCertRouter = async (server: FastifyZodProvider) =await server.services.auditLog.createAuditLog({...req.auditLogInfo,projectId: cert.projectId,- 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- }- }+ event: {+ type: EventType.IMPORT_CERT,+ metadata: {+ certId: cert.id,+ cn: cert.commonName,+ serialNumber,+ applicationId: cert.applicationId,+ applicationName+ }+ }});return {@@ -558,8 +541,7 @@ export const registerDeprecatedCertRouter = async (server: FastifyZodProvider) =schema: {hide: false,tags: [ApiDocsTags.PkiCertificates],- 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.",+ description: "Delete certificate. Only expired, discovered, or imported certificates can be deleted.",params: z.object({serialNumber: z.string().trim().describe(CERTIFICATES.DELETE.serialNumber)}),@@ -570,15 +552,14 @@ export const registerDeprecatedCertRouter = async (server: FastifyZodProvider) =}},handler: async (req) => {- 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- });+ const { deletedCert, applicationName, statusAtDeletion } = 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,@@ -593,7 +574,6 @@ export const registerDeprecatedCertRouter = async (server: FastifyZodProvider) =notAfter: deletedCert.notAfter.toISOString(),source: (deletedCert.source as CertificateSource | null) ?? CertificateSource.Issued,statusAtDeletion,- deletionAllowedReason,applicationId: deletedCert.applicationId,applicationName}diff --git a/backend/src/services/certificate-authority/certificate-issuance-queue.ts b/backend/src/services/certificate-authority/certificate-issuance-queue.tsindex a4e30b09b1..39b31f6b65 100644--- a/backend/src/services/certificate-authority/certificate-issuance-queue.ts+++ b/backend/src/services/certificate-authority/certificate-issuance-queue.ts@@ -380,7 +380,11 @@ export const certificateIssuanceQueueFactory = ({/*** Process certificate issuance jobs*/- const processCertificateIssuanceJobs = async (data: TIssueCertificateFromProfileJobData, signal?: AbortSignal) => {+ const processCertificateIssuanceJobs = async (+ data: TIssueCertificateFromProfileJobData,+ signal?: AbortSignal,+ attemptsMade = 0+ ) => {const {certificateId,profileId,@@ -446,7 +450,7 @@ export const certificateIssuanceQueueFactory = ({});}- if (isRenewal && originalCertificateId) {+ if (isRenewal && originalCertificateId && attemptsMade === 0) {const originalCertificate = await certificateDAL.findById(originalCertificateId);if (originalCertificate) assertCertificateNotDeleted(originalCertificate);}@@ -1315,7 +1319,7 @@ export const certificateIssuanceQueueFactory = ({queueService.start(QueueName.CertificateIssuance, async (job, _token, signal) => {const work = (async () => {try {- await processCertificateIssuanceJobs(job.data, signal);+ await processCertificateIssuanceJobs(job.data, signal, job.attemptsMade ?? 0);} catch (error) {// AcmPendingError is rethrown on every retry so BullMQ keeps polling; the in-handler// FAILED-update branch never runs for it. On the final attempt we still need to flip the requestdiff --git a/backend/src/services/certificate-authority/digicert/digicert-code-signing-fns.ts b/backend/src/services/certificate-authority/digicert/digicert-code-signing-fns.tsindex c664d530f0..f394459bd7 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@@ -12,8 +12,8 @@ import {import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";import {- extractExternallyIssuedCertificateFields,- getCertificateDeletedMessage+ assertCertificateNotDeleted,+ extractExternallyIssuedCertificateFields} from "@app/services/certificate/certificate-fns";import { CertStatus } from "@app/services/certificate/certificate-types";import { TDigiCertExternalMetadata } from "@app/services/certificate-common/external-metadata-schemas";@@ -370,16 +370,9 @@ 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;+ assertCertificateNotDeleted(existingCert, "Request a new code signing certificate instead.");return { certificatePem: leaf, existingCertificateId: existingCert.id, insert: null };}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.tsindex c020fc1221..14906d720b 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@@ -8,6 +8,7 @@ import { TPermissionServiceFactory } from "../../ee/services/permission/permissiimport { ProjectPermissionActions, ProjectPermissionSub } from "../../ee/services/permission/project-permission";import { ResourcePermissionSub } from "../../ee/services/permission/resource-permission";import { NON_PQC_KEY_ALGORITHMS, PQC_KEY_ALGORITHMS } from "../certificate/certificate-dal";+import { CertStatus } from "../certificate/certificate-types";import { TPkiApplicationDALFactory } from "../pki-application/pki-application-dal";import { TCertificateInventoryViewDALFactory } from "./certificate-inventory-view-dal";import {@@ -77,7 +78,7 @@ const SYSTEM_VIEWS: TSystemView[] = [{id: "system-deleted",name: "Deleted",- filters: { status: ["deleted"] },+ filters: { status: [CertStatus.DELETED] },columns: null,isSystem: true,createdByUserId: nulldiff --git a/backend/src/services/certificate-sync/certificate-sync-dal.ts b/backend/src/services/certificate-sync/certificate-sync-dal.tsindex 5abdac14fa..1ebdf26b5a 100644--- a/backend/src/services/certificate-sync/certificate-sync-dal.ts+++ b/backend/src/services/certificate-sync/certificate-sync-dal.ts@@ -14,23 +14,6 @@ type CertificateSyncFindFilter = Parameters<typeof buildFindFilter<TCertificateSexport const certificateSyncDALFactory = (db: TDbClient) => {const certificateSyncOrm = ormify(db, TableName.CertificateSync);- const $withLiveCertificateIds = async <T>(- certificateIds: string[],- tx: Knex | undefined,- write: (liveIds: Set<string>, trx: Knex) => Promise<T>- ): Promise<T> => {- const run = async (trx: Knex) => {- const rows = (await trx(TableName.Certificate)- .whereIn("id", certificateIds)- .whereNull("deletedAt")- .orderBy("id")- .forShare()- .select("id")) as Array<{ id: string }>;- return write(new Set(rows.map(({ id }) => id)), trx);- };- return tx ? run(tx) : db.transaction(run);- };-const findByPkiSyncId = async (pkiSyncId: string, tx?: Knex) => {try {const docs = await (tx || db.replicaNode())(TableName.CertificateSync)@@ -114,19 +97,16 @@ export const certificateSyncDALFactory = (db: TDbClient) => {tx?: Knex): Promise<void> => {try {- await $withLiveCertificateIds([certificateId], tx, async (liveIds, trx) => {- if (!liveIds.has(certificateId)) return;- await trx(TableName.CertificateSync)- .insert({ pkiSyncId, certificateId, syncStatus: CertificateSyncStatus.Pending, externalIdentifier })- .onConflict(["pkiSyncId", "certificateId"])- .ignore();- await trx(TableName.CertificateSync)- .where({ pkiSyncId, certificateId })- .where((qb) => {- void qb.whereNull("externalIdentifier").orWhereNot("externalIdentifier", externalIdentifier);- })- .update({ externalIdentifier });- });+ await (tx || db)(TableName.CertificateSync)+ .insert({ pkiSyncId, certificateId, syncStatus: CertificateSyncStatus.Pending, externalIdentifier })+ .onConflict(["pkiSyncId", "certificateId"])+ .ignore();+ await (tx || db)(TableName.CertificateSync)+ .where({ pkiSyncId, certificateId })+ .where((qb) => {+ void qb.whereNull("externalIdentifier").orWhereNot("externalIdentifier", externalIdentifier);+ })+ .update({ externalIdentifier });} catch (error) {throw new DatabaseError({ error, name: "ClaimExternalIdentifier" });}@@ -138,23 +118,16 @@ export const certificateSyncDALFactory = (db: TDbClient) => {tx?: Knex): Promise<TCertificateSyncs[]> => {try {- return await $withLiveCertificateIds(- certificateData.map(({ certificateId }) => certificateId),- tx,- async (liveIds, trx) => {- const insertData = certificateData- .filter(({ certificateId }) => liveIds.has(certificateId))- .map(({ certificateId, externalIdentifier }) => ({- pkiSyncId,- certificateId,- syncStatus: CertificateSyncStatus.Pending,- externalIdentifier- }));- if (insertData.length === 0) return [];-- return trx(TableName.CertificateSync).insert(insertData).returning("*");- }- );+ const insertData = certificateData.map(({ certificateId, externalIdentifier }) => ({+ pkiSyncId,+ certificateId,+ syncStatus: CertificateSyncStatus.Pending,+ externalIdentifier+ }));++ const docs = await (tx || db)(TableName.CertificateSync).insert(insertData).returning("*");++ return docs;} catch (error) {throw new DatabaseError({ error, name: "AddCertificates" });}diff --git a/backend/src/services/certificate-v3/certificate-renewal-service.ts b/backend/src/services/certificate-v3/certificate-renewal-service.tsindex e540ce67a5..b4f483060b 100644--- a/backend/src/services/certificate-v3/certificate-renewal-service.ts+++ b/backend/src/services/certificate-v3/certificate-renewal-service.ts@@ -594,6 +594,8 @@ export const certificateRenewalServiceFactory = ({throw new NotFoundError({ message: "Certificate not found" });}+ assertCertificateNotDeleted(originalCert);+if (!originalCert.profileId) {throw new ForbiddenRequestError({message:@@ -1122,8 +1124,6 @@ export const certificateRenewalServiceFactory = ({? undefined: await $authorizeRenewal({ originalCert, profile, actorCtx, isEditingCertificate }, tx);- assertCertificateNotDeleted(originalCert);-const { issuerType, ca, caType, policy } = await $resolveRenewalIssuer({originalCert,diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.tsindex 52243b2478..0d7367f898 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts@@ -3157,7 +3157,7 @@ describe("CertificateV3Service", () => {certificateId: "cert-123",...mockActor})- ).rejects.toThrow("was deleted on 2026-10-20T14:38:27.000Z and can no longer be renewed or changed");+ ).rejects.toThrow("was deleted on 2026-10-20T14:38:27.000Z. It can no longer be renewed or changed");});it("should reject renewal if CA is inactive", async () => {diff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.tsindex d23c64de6b..31c31011ae 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, TCertificatesUpdate } from "@app/db/schemas";+import { TableName, TCertificates, TCertificatesInsert } 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,7 +20,6 @@ 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";@@ -84,38 +83,6 @@ 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@@ -1533,7 +1500,6 @@ export const certificateDALFactory = (db: TDbClient) => {...certificateOrm,findByIdForUpdate,findByIdForShare,- restoreDeleted,create,countCertificatesInProject,countActiveCertificatesForSync,diff --git a/backend/src/services/certificate/certificate-fns.test.ts b/backend/src/services/certificate/certificate-fns.test.tsindex f80cad717c..84d6f8f028 100644--- a/backend/src/services/certificate/certificate-fns.test.ts+++ b/backend/src/services/certificate/certificate-fns.test.ts@@ -2,16 +2,12 @@ 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,@@ -20,10 +16,9 @@ import {normalizeThumbprint,parseCertificateBody,parsePemCertificateChain,- resolveCertificateDeletionEligibility,resolveCertificateStatus} from "./certificate-fns";-import { CertExtendedKeyUsage, CertificateDeletionEligibility, CertKeyUsage, CertStatus } from "./certificate-types";+import { CertExtendedKeyUsage, CertKeyUsage, CertStatus } from "./certificate-types";describe("normalizeThumbprint", () => {const sha1Hex = "a".repeat(40);@@ -303,43 +298,6 @@ describe("resolveCertificateStatus", () => {});});-describe("resolveCertificateDeletionEligibility", () => {- const future = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);- const past = new Date(Date.now() - 24 * 60 * 60 * 1000);-- it("reports an expired certificate", () => {- expect(resolveCertificateDeletionEligibility({ status: CertStatus.REVOKED, notAfter: past })).toBe(- CertificateDeletionEligibility.Expired- );- });-- it("reports discovered and imported certificates by source, revoked or not", () => {- expect(- resolveCertificateDeletionEligibility({- status: CertStatus.REVOKED,- notAfter: future,- source: CertificateSource.Discovered- })- ).toBe(CertificateDeletionEligibility.Discovered);- expect(- resolveCertificateDeletionEligibility({- status: CertStatus.ACTIVE,- notAfter: future,- source: CertificateSource.Imported- })- ).toBe(CertificateDeletionEligibility.Imported);- });-- it("always returns a reason, so the audit event keeps the field", () => {- expect(resolveCertificateDeletionEligibility({ status: CertStatus.ACTIVE, notAfter: future })).toBe(- CertificateDeletionEligibility.Issued- );- expect(resolveCertificateDeletionEligibility({ status: CertStatus.REVOKED, notAfter: future })).toBe(- CertificateDeletionEligibility.Issued- );- });-});-describe("deleted certificate guards", () => {const deletedAt = new Date("2026-10-20T14:38:27.000Z");const certificate = { friendlyName: "web", commonName: "web.example.com", serialNumber: "0a1b2c" };@@ -361,7 +319,7 @@ describe("deleted certificate guards", () => {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."+ "Certificate 'web' was deleted on 2026-10-20T14:38:27.000Z. It can no longer be renewed or changed.");});@@ -452,74 +410,3 @@ 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.tsindex 308bc2087f..ecb7230d9f 100644--- a/backend/src/services/certificate/certificate-fns.ts+++ b/backend/src/services/certificate/certificate-fns.ts@@ -3,8 +3,6 @@ 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";import { logger } from "@app/lib/logger";@@ -22,7 +20,6 @@ import type { TCertificateDALFactory } from "./certificate-dal";import {CertExtendedKeyUsage,CertExtendedKeyUsageOIDToName,- CertificateDeletionEligibility,CertKeyAlgorithm,CertKeyUsage,CertSignatureAlgorithm,@@ -542,18 +539,6 @@ export const resolveCertificateStatus = (certificate: {return CertStatus.ACTIVE;};-export const resolveCertificateDeletionEligibility = (certificate: {- status: string;- notAfter: Date;- source?: string | null;-}): CertificateDeletionEligibility => {- if (certificate.source === CertificateSource.Discovered) return CertificateDeletionEligibility.Discovered;- if (certificate.source === CertificateSource.Imported) return CertificateDeletionEligibility.Imported;- if (new Date(certificate.notAfter).getTime() <= Date.now()) return CertificateDeletionEligibility.Expired;-- return CertificateDeletionEligibility.Issued;-};-type TDeletableCertificate = {friendlyName?: string | null;commonName?: string | null;@@ -564,27 +549,19 @@ type TDeletableCertificate = {export const getCertificateDisplayName = (certificate: Omit<TDeletableCertificate, "deletedAt">) =>certificate.friendlyName || certificate.commonName || certificate.serialNumber;-export const assertCertificateMaterialAvailable = (certificate: TDeletableCertificate) => {+export const assertCertificateNotDeleted = (+ certificate: TDeletableCertificate,+ consequence = "It can no longer be renewed or changed."+) => {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.`+ message: `Certificate '${getCertificateDisplayName(certificate)}' was deleted on ${new Date(certificate.deletedAt).toISOString()}. ${consequence}`});};-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 assertCertificateMaterialAvailable = (certificate: TDeletableCertificate) =>+ assertCertificateNotDeleted(certificate, "Its certificate and private key are no longer available.");export const linkRenewedCertificate = async (certificateDAL: Pick<TCertificateDALFactory, "findById" | "updateById">,@@ -600,45 +577,3 @@ export const linkRenewedCertificate = async (await certificateDAL.updateById(originalCertificateId, { 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.tsindex 97b6c1963d..994dbc2ca2 100644--- a/backend/src/services/certificate/certificate-service.test.ts+++ b/backend/src/services/certificate/certificate-service.test.ts@@ -102,7 +102,6 @@ describe("certificateService.deleteCert", () => {expect.objectContaining({deletedByActorType: ActorType.USER,deletedByActorId: "user-1",- deletedVia: UserAgentType.TERRAFORM,deletedAt: expect.any(Date) as Date}),txdiff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.tsindex 1d7283f3ec..05736ff279 100644--- a/backend/src/services/certificate/certificate-service.ts+++ b/backend/src/services/certificate/certificate-service.ts@@ -1,10 +1,9 @@/* 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, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";+import { TAuditLogServiceFactory } 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";@@ -20,7 +19,7 @@ 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, ForbiddenRequestError, InternalServerError, 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";@@ -95,8 +94,6 @@ import { parseExtendedKeyUsages, parseKeyUsages } from "../certificate-v3/certifimport {assertCertificateMaterialAvailable,assertCertificateNotDeleted,- buildRestoredImportData,- canRestoreDeletedCertificate,CertificateThumbprintAlgorithm,extractCertificateAlgorithms,extractCertificateFields,@@ -107,7 +104,6 @@ import {normalizeThumbprint,parseCertificateBody,parsePemCertificateChain,- resolveCertificateDeletionEligibility,resolveCertificateStatus,revocationReasonToCrlCode} from "./certificate-fns";@@ -145,10 +141,9 @@ type TCertificateServiceFactoryDep = {| "findLatestRenewalOf"| "updateById"| "findByIdForUpdate"- | "restoreDeleted">;pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;- certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs" | "findById">;+ certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs">;pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory, "findOneByApplicationAndProfile">;apiEnrollmentConfigDAL: Pick<TApiEnrollmentConfigDALFactory, "findById">;digicertFns: Pick<ReturnType<typeof DigiCertCertificateAuthorityFns>, "assertOrderMatchesCertificate">;@@ -256,40 +251,6 @@ export const certificateServiceFactory = ({return application?.name ?? null;};- 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;@@ -342,7 +303,7 @@ export const certificateServiceFactory = ({// Unified lookup - consistent response for both id and serialNumberconst certWithDetails = await certificateDAL.findWithFullDetails(id ? { id } : { serialNumber: serialNumber! });- if (!certWithDetails || (certWithDetails.deletedAt && !includeDeleted)) {+ if (!certWithDetails) {throw new NotFoundError({ message: "Certificate not found" });}@@ -375,6 +336,12 @@ export const certificateServiceFactory = ({}}+ if (certWithDetails.deletedAt && !includeDeleted) {+ throw new NotFoundError({+ message: `Certificate '${getCertificateDisplayName(certWithDetails)}' was deleted on ${new Date(certWithDetails.deletedAt).toISOString()}.`+ });+ }+// Extract additional details from the joined result while creating clean cert objectconst { caName, profileName, applicationName, ...cert } = certWithDetails;@@ -467,7 +434,6 @@ export const certificateServiceFactory = ({applicationName,latestRenewalCertificateId,deletedByActorType: cert.deletedByActorType as ActorType | null | undefined,- deletedVia: cert.deletedVia as UserAgentType | null | undefined,deletedByActorName,metadata: certMetadata}@@ -602,18 +568,6 @@ export const certificateServiceFactory = ({});}- const missingFingerprints = cert.fingerprintSha256- ? undefined- : await $parseStoredCertificateBody(cert)- .then((parsed) => parsed?.fingerprints)- .catch((error: unknown) => {- logger.error(error, `Could not read fingerprints before deleting certificate [certificateId=${cert.id}]`);- throw new InternalServerError({- error,- message: `Certificate '${getCertificateDisplayName(cert)}' could not be read to record its fingerprint, which is needed to recognize it if it is imported or discovered again. It was not deleted. Try again in a few minutes.`- });- });-const { deletedCert, pkiSyncIdsHoldingCertificate } = await certificateDAL.transaction(async (tx) => {const lockedCert = await certificateDAL.findByIdForUpdate(cert.id, tx);if (!lockedCert || lockedCert.deletedAt) {@@ -634,12 +588,7 @@ export const certificateServiceFactory = ({{deletedAt: new Date(),deletedByActorType: actor,- deletedByActorId: actorId,- deletedVia: auditLogInfo?.userAgentType ?? null,- ...(missingFingerprints?.sha256 && {- fingerprintSha256: missingFingerprints.sha256,- fingerprintSha1: missingFingerprints.sha1 ?? null- })+ deletedByActorId: actorId},tx);@@ -669,7 +618,6 @@ export const certificateServiceFactory = ({return {deletedCert,statusAtDeletion: resolveCertificateStatus(deletedCert),- deletionAllowedReason: resolveCertificateDeletionEligibility(deletedCert),applicationName: await $resolveApplicationName(deletedCert.applicationId)};};@@ -1418,6 +1366,11 @@ export const certificateServiceFactory = ({const { serialNumber, notBefore, notAfter } = leafCert;+ const existingCertWithSerial = await certificateDAL.findOne({ serialNumber, projectId });+ if (existingCertWithSerial) {+ assertCertificateNotDeleted(existingCertWithSerial, "A deleted certificate can't be imported again.");+ }+const keyUsagesExt = leafCert.getExtension("2.5.29.15") as x509.KeyUsagesExtension;let keyUsages: CertKeyUsage[] = [];@@ -1495,54 +1448,34 @@ export const certificateServiceFactory = ({renewBeforeDays = calculateFinalRenewBeforeDays({ apiConfig: effectiveApiConfig }, `${validityDays}d`, notAfter);}- 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) => {+ const cert = await certificateDAL.transaction(async (tx) => {try {- const matchingCertificates = await certificateDAL.find(- { serialNumber, projectId, fingerprintSha256: certificateFields.fingerprintSha256 },- { tx }- );- const deletedMatch = matchingCertificates.find((match) =>- canRestoreDeletedCertificate(match, importedCertificateData)+ 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 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({@@ -1573,7 +1506,7 @@ export const certificateServiceFactory = ({);}- return { cert: txCert, restoredFromDeletion: Boolean(deletedMatch) };+ return txCert;} catch (error) {// @ts-expect-error We're expecting a database error// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access@@ -1601,8 +1534,7 @@ export const certificateServiceFactory = ({cert,applicationName: await $resolveApplicationName(cert.applicationId),profileName: linkage?.profileName ?? null,- caName: linkage?.caName ?? null,- restoredFromDeletion+ caName: linkage?.caName ?? null};};diff --git a/backend/src/services/certificate/certificate-types.ts b/backend/src/services/certificate/certificate-types.tsindex fe34754fcf..8d2023870d 100644--- a/backend/src/services/certificate/certificate-types.ts+++ b/backend/src/services/certificate/certificate-types.ts@@ -21,18 +21,6 @@ export enum CertStatus {DELETED = "deleted"}-export enum CertificateDeletionEligibility {- Expired = "expired",- Discovered = "discovered",- Imported = "imported",- Issued = "issued"-}--export enum CertificateRestoreSource {- Import = "import",- Discovery = "discovery"-}-export enum CertKeyAlgorithm {RSA_2048 = "RSA_2048",RSA_3072 = "RSA_3072",diff --git a/backend/src/services/pki-collection/pki-collection-service.ts b/backend/src/services/pki-collection/pki-collection-service.tsindex c590ac97ee..9940493f48 100644--- a/backend/src/services/pki-collection/pki-collection-service.ts+++ b/backend/src/services/pki-collection/pki-collection-service.ts@@ -263,12 +263,12 @@ export const pkiCollectionServiceFactory = ({id: itemId});if (!certificate) throw new NotFoundError({ message: `Certificate with ID '${itemId}' not found` });- assertCertificateNotDeleted(certificate, "be added to a collection");+ assertCertificateNotDeleted(certificate, "It can't be added to a collection.");pkiCollectionItem = await certificateDAL.transaction(async (tx) => {const lockedCertificate = await certificateDAL.findByIdForShare(itemId, tx);if (!lockedCertificate) throw new NotFoundError({ message: `Certificate with ID '${itemId}' not found` });- assertCertificateNotDeleted(lockedCertificate, "be added to a collection");+ assertCertificateNotDeleted(lockedCertificate, "It can't be added to a collection.");return pkiCollectionItemDAL.create({ pkiCollectionId: collectionId, certId: itemId }, tx);});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.tsindex c75f4a898d..4c41aba33f 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@@ -194,8 +194,7 @@ export const applyPkiSyncCertificateDiff = async (removalOptions?: TPkiSyncRemovalOptions): Promise<{ linked: TPkiSyncCertificateRef[]; unlinked: TPkiSyncCertificateRef[] }> => {const { certificateSyncDAL, pkiSyncQueue, auditLogService, pkiApplicationDAL } = deps;- const { toUnlink } = diff;- let { toLink } = diff;+ const { toLink, toUnlink } = diff;const unlinkIds = new Set(toUnlink.map((certificate) => certificate.id));const canRemoveCertificates = Boolean(@@ -212,13 +211,11 @@ export const applyPkiSyncCertificateDiff = async (if (writeFilters) await writeFilters(tx);if (toLink.length > 0) {- const linked = await certificateSyncDAL.addCertificates(+ await certificateSyncDAL.addCertificates(pkiSync.id,toLink.map((certificate) => ({ certificateId: certificate.id })),tx);- const linkedIds = new Set(linked.map(({ certificateId }) => certificateId));- toLink = toLink.filter((certificate) => linkedIds.has(certificate.id));}if (idsOnlyLinked.length > 0) {diff --git a/backend/src/services/signer/signer-service.ts b/backend/src/services/signer/signer-service.tsindex d98b81282a..a5171003ac 100644--- a/backend/src/services/signer/signer-service.ts+++ b/backend/src/services/signer/signer-service.ts@@ -580,7 +580,7 @@ export const signerServiceFactory = ({if (!lockedCertificate) {throw new NotFoundError({ message: `The certificate in DigiCert order ${imported.orderId} no longer exists.` });}- assertCertificateNotDeleted(lockedCertificate, "be used by a signer");+ assertCertificateNotDeleted(lockedCertificate, "It can't be used by a signer.");const signerUsingCertificate = await signerDAL.findOne({ certificateId }, tx);if (signerUsingCertificate && signerUsingCertificate.id !== signerId) {throw new ConflictError({@@ -669,7 +669,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");+ assertCertificateNotDeleted(certificate, "It can't be used by a signer.");if (certificate.status === CertStatus.REVOKED) {throw new BadRequestError({ message: "Certificate has been revoked" });}@@ -799,7 +799,7 @@ export const signerServiceFactory = ({if (!lockedCertificate) {throw new NotFoundError({ message: `Certificate with ID '${dto.certificateId}' not found` });}- assertCertificateNotDeleted(lockedCertificate, "be used by a signer");+ assertCertificateNotDeleted(lockedCertificate, "It can't be used by a signer.");}const importedCertificateId = importedCertificatediff --git a/docs/documentation/platform/pki/concepts/certificate-lifecycle.mdx b/docs/documentation/platform/pki/concepts/certificate-lifecycle.mdxindex 340f621eaa..98d8534233 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-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.+Deleting a certificate removes the certificate and its private key, and its details stay in the inventory as **Deleted**. A deleted certificate can't be renewed. Deleting doesn't revoke it, but you can still revoke it afterward if its certificate authority supports revocation. The exception is a certificate imported into a profile with an internal certificate authority, which you must revoke before deleting it. A deleted certificate issued from a certificate authority keeps counting toward your certificate quota until it expires or is revoked. Deleted imported and discovered certificates stop counting right away. 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.mdxindex e8765b3eb0..2face8e231 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 foldFiles 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**. 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.+ 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**.</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.mdxindex 9007ecfc32..7db694ed16 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**. 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.+ 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**.</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.mdxindex 0e39ed0a4b..64429f523c 100644--- a/docs/documentation/platform/pki/discovery/overview.mdx+++ b/docs/documentation/platform/pki/discovery/overview.mdx@@ -32,8 +32,6 @@ An installation represents a unique location where a certificate was discoveredDiscovered 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/settings/certificate-cleanup.mdx b/docs/documentation/platform/pki/settings/certificate-cleanup.mdxindex 6458fa7bc4..e7e352b554 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 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.+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, its details stay in the inventory until it expires and cleanup removes it.<Info>This setting is managed by product admins and applies to all certificates in the Certificate Manager.diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex 93fa4d9053..55ef8a81e8 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -82,7 +82,6 @@ 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.tsxindex 96238790f8..14486c3bd5 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -98,7 +98,6 @@ 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.tsxindex edf9176b8e..a2651fa45f 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 { CertificateRestoreSource, CertStatus, CrlReason } from "../certificates/enums";+import { CertStatus, CrlReason } from "../certificates/enums";import { IdentityTrustedIp } from "../identities/types";import { PkiItemType } from "../pkiCollections/constants";import { WorkflowIntegration } from "../workflowIntegrations/types";@@ -684,24 +684,6 @@ 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: {@@ -721,7 +703,7 @@ interface DeleteCert {notAfter: string;source: string;statusAtDeletion?: CertStatus;- deletionAllowedReason: string;+ deletionAllowedReason?: string;applicationId?: string | null;applicationName?: string | null;};@@ -1108,7 +1090,6 @@ export type Event =| ImportCert| GetCert| DeleteCert- | RestoreCert| RevokeCert| GetCertBody| GetCertPrivateKeydiff --git a/frontend/src/hooks/api/certificates/enums.tsx b/frontend/src/hooks/api/certificates/enums.tsxindex 5758ee3f84..00aa37450f 100644--- a/frontend/src/hooks/api/certificates/enums.tsx+++ b/frontend/src/hooks/api/certificates/enums.tsx@@ -60,11 +60,6 @@ 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/types.ts b/frontend/src/hooks/api/certificates/types.tsindex bf47a1896e..463067ee09 100644--- a/frontend/src/hooks/api/certificates/types.ts+++ b/frontend/src/hooks/api/certificates/types.ts@@ -1,5 +1,5 @@import type { TPkcs12Entry } from "@app/helpers/pkcs12";-import { ActorType, UserAgentType } from "@app/hooks/api/auditLogs/enums";+import { ActorType } from "@app/hooks/api/auditLogs/enums";import { CaType } from "@app/hooks/api/ca/enums";import {@@ -86,7 +86,6 @@ export type TCertificate = {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.tsindex d018e72836..ee2e4486e6 100644--- a/frontend/src/hooks/api/pkiDiscovery/types.ts+++ b/frontend/src/hooks/api/pkiDiscovery/types.ts@@ -71,7 +71,6 @@ export type TPkiDiscovery = {discoveryType: PkiDiscoveryType;targetConfig: TPkiDiscoveryTargetConfig;isAutoScanEnabled: boolean;- restoreDeletedCertificates: boolean;scanIntervalDays: number | null;gatewayId: string | null;gatewayPoolId: string | null;@@ -182,7 +181,6 @@ export type TCreatePkiDiscoveryDTO = {discoveryType?: PkiDiscoveryType;targetConfig: TPkiDiscoveryTargetConfig;isAutoScanEnabled?: boolean;- restoreDeletedCertificates?: boolean;scanIntervalDays?: number;gatewayId?: string;gatewayPoolId?: string;@@ -194,7 +192,6 @@ 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/pkiSyncs/queries.tsx b/frontend/src/hooks/api/pkiSyncs/queries.tsxindex 5ea1655443..34fedf4dd9 100644--- a/frontend/src/hooks/api/pkiSyncs/queries.tsx+++ b/frontend/src/hooks/api/pkiSyncs/queries.tsx@@ -25,8 +25,18 @@ export const pkiSyncKeys = {applicationId? ([...pkiSyncKeys.all, "list", projectId, "application", applicationId] as const): ([...pkiSyncKeys.all, "list", projectId] as const),- listWithCertificate: (projectId: string, certificateId: string) =>- [...pkiSyncKeys.all, "list", projectId, "with-certificate", certificateId] as const,+ listWithCertificate: (projectId: string, certificateId: string, applicationId?: string) =>+ applicationId+ ? ([+ ...pkiSyncKeys.all,+ "list",+ projectId,+ "with-certificate",+ certificateId,+ "application",+ applicationId+ ] as const)+ : ([...pkiSyncKeys.all, "list", projectId, "with-certificate", certificateId] as const),byId: (syncId: string, projectId: string) =>[...pkiSyncKeys.all, "by-id", syncId, projectId] as const,certificates: (syncId: string, pagination?: { offset: number; limit: number }) =>@@ -230,11 +240,12 @@ export const useListPkiSyncsWithCertificate = (ReturnType<typeof pkiSyncKeys.listWithCertificate>>,"queryKey" | "queryFn"- >+ >,+ applicationId?: string) => {return useQuery({- queryKey: pkiSyncKeys.listWithCertificate(projectId, certificateId),- queryFn: () => fetchPkiSyncsByProjectId(projectId, certificateId),+ queryKey: pkiSyncKeys.listWithCertificate(projectId, certificateId, applicationId),+ queryFn: () => fetchPkiSyncsByProjectId(projectId, certificateId, applicationId),enabled: !!projectId && !!certificateId,...options});diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationRequestsTab.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationRequestsTab.tsxindex 2da66596e6..fa0ada0b40 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationRequestsTab.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationRequestsTab.tsx@@ -1,7 +1,6 @@import { useNavigate, useParams } from "@tanstack/react-router";import { CertificateRequestsSection } from "../../CertificateRequestsPage/components/CertificateRequestsSection";-import { ApplicationTab } from "../application-tabs";type Props = {applicationId: string;@@ -14,12 +13,9 @@ export const ApplicationRequestsTab = ({ applicationId, applicationName }: Propsconst handleViewCertificateFromRequest = (certificateId: string) => {navigate({- to: "/organizations/$orgId/cert-manager/applications/$applicationName",- params: {- orgId: orgId ?? "",- applicationName- },- search: { selectedTab: ApplicationTab.Certificates, search: certificateId }+ to: "/organizations/$orgId/cert-manager/certificates/$certificateId",+ params: { orgId: orgId ?? "", certificateId },+ search: { fromApplication: applicationName }});};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.tsindex fb71f7f38b..0acec5d4dc 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.test.ts+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { ActorType, UserAgentType } from "@app/hooks/api/auditLogs/enums";+import { ActorType } from "@app/hooks/api/auditLogs/enums";import { CertStatus } from "@app/hooks/api/certificates/enums";import {@@ -127,41 +127,22 @@ describe("getCertificateDeletionWarning sync removal", () => {});describe("getCertificateDeletedBySummary", () => {- it("names the actor and says UI for deletions from the web app", () => {+ it("names the actor that deleted the certificate", () => {expect(getCertificateDeletedBySummary({deletedByActorType: ActorType.USER,- deletedByActorName: "John Smith",- deletedVia: UserAgentType.WEB+ deletedByActorName: "John Smith"})- ).toBe("John Smith via UI");+ ).toBe("John Smith");});- it("names the client for other callers and falls back when the actor is gone", () => {+ it("falls back to the actor type when the actor no longer exists", () => {expect(getCertificateDeletedBySummary({deletedByActorType: ActorType.IDENTITY,- deletedByActorName: null,- deletedVia: UserAgentType.TERRAFORM+ deletedByActorName: null})- ).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");+ ).toBe("A machine identity");+ expect(getCertificateDeletedBySummary({ deletedByActorType: ActorType.USER })).toBe("A user");});});diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.tsindex ec0262f517..005f69dcde 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.ts+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.ts@@ -1,8 +1,7 @@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 { ActorType } 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";@@ -62,20 +61,12 @@ export const getCertificateDisplayStatus = (certificate: TCertificateStatusSourctype 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];- }+ if (certificate.deletedByActorName) return certificate.deletedByActorName;- return `${certificate.deletedByActorName || fallbackActor} via ${channel}`;+ return certificate.deletedByActorType === ActorType.IDENTITY ? "A machine identity" : "A user";};export const canRevokeAfterDeletion = (diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificateHoldingSyncs.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificateHoldingSyncs.tsindex 24dd8578dd..8c03ee2d60 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificateHoldingSyncs.ts+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificateHoldingSyncs.ts@@ -1,5 +1,3 @@-import { useQuery } from "@tanstack/react-query";-import { useProject, useProjectPermission } from "@app/context";import {ProjectPermissionPkiSyncActions,@@ -10,7 +8,7 @@ import {PkiApplicationResourceActions,PkiApplicationResourceSub} from "@app/hooks/api/pkiApplications/types";-import { fetchPkiSyncsByProjectId, pkiSyncKeys } from "@app/hooks/api/pkiSyncs/queries";+import { useListPkiSyncsWithCertificate } from "@app/hooks/api/pkiSyncs/queries";export const useCertificateHoldingSyncs = ({certificateId,@@ -37,14 +35,12 @@ export const useCertificateHoldingSyncs = ({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- });+ const { data: syncs = [], isPending } = useListPkiSyncsWithCertificate(+ projectId,+ certificateId || "",+ { enabled: isQueryEnabled },+ applicationId ?? undefined+ );return {holdingSyncs: syncs.filter((sync) => sync.hasCertificate),diff --git a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsx b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsxindex c4dddb95aa..dd55032c70 100644--- a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsx+++ b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsx@@ -97,16 +97,6 @@ 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.tsxindex e72c759ee4..b045de01f4 100644--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryDetailsFields.tsx+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryDetailsFields.tsx@@ -114,27 +114,6 @@ 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'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.tsxindex 6561e8a4c3..d1afb4c6e1 100644--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobForm.tsx+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobForm.tsx@@ -100,13 +100,7 @@ const STEP_FIELDS: Record<DiscoveryJobStep, FieldPath<TDiscoveryJobForm>[]> = {[DiscoveryJobStep.Hosts]: ["connections"],[DiscoveryJobStep.Folders]: ["searchFolderPaths", "skipFolderPaths"],[DiscoveryJobStep.Options]: ["maxFolderDepth", "importStandaloneCaCertificates"],- [DiscoveryJobStep.Details]: [- "name",- "description",- "isAutoScanEnabled",- "scanIntervalDays",- "restoreDeletedCertificates"- ],+ [DiscoveryJobStep.Details]: ["name", "description", "isAutoScanEnabled", "scanIntervalDays"],[DiscoveryJobStep.Review]: []};@@ -189,8 +183,7 @@ export const DiscoveryJobForm = ({const payload = {name: form.name,targetConfig: buildTargetConfig(form),- isAutoScanEnabled: form.isAutoScanEnabled,- restoreDeletedCertificates: form.restoreDeletedCertificates+ isAutoScanEnabled: form.isAutoScanEnabled};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.tsxindex 5c5f4d518e..b5aaf607ba 100644--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryReviewFields.tsx+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryReviewFields.tsx@@ -117,11 +117,6 @@ 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.tsindex 94b3d2724a..9424648f05 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,7 +107,6 @@ 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")@@ -171,7 +170,6 @@ 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/PoliciesPage/PoliciesPage.tsx b/frontend/src/pages/cert-manager/PoliciesPage/PoliciesPage.tsxindex 434d3a5076..c2c59ff875 100644--- a/frontend/src/pages/cert-manager/PoliciesPage/PoliciesPage.tsx+++ b/frontend/src/pages/cert-manager/PoliciesPage/PoliciesPage.tsx@@ -1,10 +1,10 @@-import { useMemo, useState } from "react";+import { useMemo } from "react";import { Helmet } from "react-helmet";import { useTranslation } from "react-i18next";import { useNavigate, useSearch } from "@tanstack/react-router";import { AccessRestrictedDialog, PageHeader, PageLoader } from "@app/components/v3";-import { useProject, useProjectPermission } from "@app/context";+import { useOrganization, useProject, useProjectPermission } from "@app/context";import {ProjectPermissionCertificateActions,ProjectPermissionCertificatePolicyActions,@@ -27,6 +27,7 @@ enum TabSections {export const PoliciesPage = () => {const { t } = useTranslation();+ const { currentOrg } = useOrganization();const { currentProject } = useProject();const { permission } = useProjectPermission();const navigate = useNavigate();@@ -35,7 +36,6 @@ export const PoliciesPage = () => {});const activeTab = (searchParams.selectedTab as TabSections) || TabSections.Certificates;- const [certificateFilter, setCertificateFilter] = useState<{ search?: string }>({});const dashboardFilters = useMemo(() => {const filters: Array<{@@ -102,10 +102,9 @@ export const PoliciesPage = () => {}, [searchParams]);const handleViewCertificateFromRequest = (certificateId: string) => {- setCertificateFilter({ search: certificateId });navigate({- // eslint-disable-next-line @typescript-eslint/no-explicit-any- search: { selectedTab: TabSections.Certificates } as any+ to: "/organizations/$orgId/cert-manager/certificates/$certificateId",+ params: { orgId: currentOrg.id, certificateId }});};@@ -145,7 +144,6 @@ export const PoliciesPage = () => {{activeTab === TabSections.Certificates &&(canReadCertificates ? (<CertificatesTab- externalFilter={certificateFilter}dashboardFilters={dashboardFilters}dashboardViewId={searchParams.viewId}/>