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
Implement soft-delete and async cleanup for projects; add related migrations and tests. Introduce project hard-delete queue and update project service to handle soft-deletion logic, ensuring immediate removal from reads while deferring actual deletion. Enhance database schema with soft-delete fields and indexes for efficient cleanup.
Victor Hugo dos Santosa1fd164b0c2f
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 1414a787d8..d5cee6a38a 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -180,6 +180,8 @@ Queue jobs support: delays, attempts with exponential/fixed backoff, and completQueue handler factories (e.g., `src/services/secret/secret-queue.ts`) follow the same DI pattern as services — they receive DALs and services as dependencies.+`queueService.start(name, handler, opts)` accepts `concurrency` (per-worker parallelism ceiling) and BullMQ's `limiter: { max, duration }` (fleet-wide throughput cap, coordinated via Redis). Use both to **rate-shape DB-heavy background work** so a large backlog drains as an even plateau instead of a burst — see `src/services/project/project-cleanup-queue.ts`. The cron cadence must not be the pacer; load is bounded by `concurrency × per-job cost`, and the limiter caps steady throughput.+### Scheduled Jobs (Cron Manager)Recurring work runs through the cron manager in `src/lib/cron/cron-job.ts` (`cronJobFactory`). A single instance is constructed in `src/server/routes/index.ts` (~line 541) and injected as `cronJob` into any service that needs to schedule periodic work. The factory exposes `register`, `start`, and `stop`; `start` is called once after construction, and `stop` is invoked during graceful shutdown to drain in-flight handlers.@@ -222,6 +224,18 @@ Recurring work runs through the cron manager in `src/lib/cron/cron-job.ts` (`croSee `src/services/health-alert/health-alert-queue.ts` for a minimal example, `src/services/resource-cleanup/resource-cleanup-queue.ts` for a service with multiple registrations, and `src/ee/services/secret-rotation-v2/secret-rotation-v2-queue.ts` for a cron-tick that fans out into a BullMQ queue.+### Soft-Delete + Async Cleanup++Resources whose deletion cascades across many/large tables use a **soft-delete + paced async hard-delete** pattern instead of a synchronous cascade in the request path.++Pattern:+- **Soft-delete columns** on the table: `deleteAfter`, `softDeletedAt`, `deletedByUserId`, `deletedByIdentityId`, plus a **partial index** `WHERE deleteAfter IS NOT NULL` (tiny, ~zero write cost on the live path). The DELETE handler sets `deleteAfter` (one UPDATE) and returns immediately. Set `deleteAfter = now()` for "real delete" UX (reaped on the next worker tick) or `now + grace` for a restore window.+- **Hide soft-deleted rows from every read.** Override the `ormify` base `findById`/`findOne`/`find` to append `.whereNull("deleteAfter")`, and add explicit `*IncludingExpired` escape hatches used only by the cleanup worker/restore. Patch all custom read queries too — **especially any count feeding a plan/quota limit** (e.g. `countOfOrgProjects`), or soft-deleted rows wrongly count against limits. Free unique columns (e.g. the project slug) on soft-delete so the resource can be recreated immediately.+- **Cron discovery + paced worker** (cron fans out to BullMQ): the cron selects the oldest `LIMIT N` expired rows (`ORDER BY deleteAfter ASC`) and enqueues one job each with a deterministic `jobId` (dedupe → queue stays bounded at ~N; never enqueue the whole backlog). The worker (`concurrency` + `limiter`) does the actual delete, re-reading via the **primary** under a per-resource lock to defeat replica-lag/restore races.+- **Chunked deletes are FK-order-sensitive.** You may only manually chunk-delete a table whose inbound FKs are all `CASCADE`/`SET NULL`. A `DEFERRABLE … NO ACTION` inbound FK (e.g. `secret_rotation_v2_secret_mappings.secretId → secrets_v2`) fails the deferred check at COMMIT if you delete the parent outside the full cascade tree — leave those tables to the final `deleteById` cascade (PG resolves the whole tree in one transaction). `secret_versions_v2` is chunk-deleted by `folderId` only because it has no such inbound FK (and the cascade would otherwise orphan it — it has no `folderId`/`secretId` FK). Use `SET LOCAL statement_timeout` per batch so it can't leak to pooled connections.+- **Index every FK referencing column** that participates in a cascade — Postgres does **not** auto-index FK columns, so an unindexed FK forces a seq-scan per parent delete. For a mostly-NULL nullable FK, a partial index `WHERE col IS NOT NULL` serves the cascade lookup at a fraction of the size/write cost (e.g. `idx_secret_versions_v2_envid`).+- **Observe the backlog, not just the queue.** Queue depth caps at the discovery batch size, so it can't reveal the true backlog. Emit a DB-count observable gauge of pending rows (`infisical.project_cleanup.pending` on the `InfisicalCore` meter) and **alert on sustained growth** — it means the drain rate can't keep up (raise concurrency/limiter) or a mass-delete is in progress.+### Error HandlingCustom error classes in `src/lib/errors/index.ts`:diff --git a/backend/e2e-test/routes/v1/project.spec.ts b/backend/e2e-test/routes/v1/project.spec.tsnew file mode 100644index 0000000000..0f2059e3cc--- /dev/null+++ b/backend/e2e-test/routes/v1/project.spec.ts@@ -0,0 +1,93 @@+type TProject = { id: string; name: string; slug: string };++const createProject = async (projectName: string, slug?: string): Promise<TProject> => {+ const res = await testServer.inject({+ method: "POST",+ url: "/api/v1/projects",+ headers: {+ authorization: `Bearer ${jwtAuthToken}`+ },+ body: {+ projectName,+ ...(slug ? { slug } : {})+ }+ });++ expect(res.statusCode).toBe(200);+ const payload = JSON.parse(res.payload);+ expect(payload).toHaveProperty("project");+ return payload.project as TProject;+};++const deleteProject = async (projectId: string) => {+ return testServer.inject({+ method: "DELETE",+ url: `/api/v1/projects/${projectId}`,+ headers: {+ authorization: `Bearer ${jwtAuthToken}`+ }+ });+};++const getProject = async (projectId: string) => {+ return testServer.inject({+ method: "GET",+ url: `/api/v1/projects/${projectId}`,+ headers: {+ authorization: `Bearer ${jwtAuthToken}`+ }+ });+};++const listProjects = async (): Promise<TProject[]> => {+ const res = await testServer.inject({+ method: "GET",+ url: "/api/v1/projects",+ headers: {+ authorization: `Bearer ${jwtAuthToken}`+ }+ });+ expect(res.statusCode).toBe(200);+ return (JSON.parse(res.payload).projects as TProject[]) ?? [];+};++describe("Project deletion (soft-delete + async cleanup)", async () => {+ test("DELETE soft-deletes a project and removes it from all reads", async () => {+ const project = await createProject("e2e-delete-removed-from-reads");++ // present before delete+ expect((await getProject(project.id)).statusCode).toBe(200);+ expect((await listProjects()).some((p) => p.id === project.id)).toBe(true);++ const delRes = await deleteProject(project.id);+ expect(delRes.statusCode).toBe(200);+ expect(JSON.parse(delRes.payload).project).toEqual(expect.objectContaining({ id: project.id }));++ // gone from every read path immediately (read filters exclude soft-deleted)+ expect((await getProject(project.id)).statusCode).toBe(404);+ expect((await listProjects()).some((p) => p.id === project.id)).toBe(false);+ });++ test("frees the slug so a same-slug project can be recreated immediately", async () => {+ const slug = "e2e-slug-reuse-test";+ const first = await createProject("e2e-slug-reuse-1", slug);+ expect(first.slug).toBe(slug);++ expect((await deleteProject(first.id)).statusCode).toBe(200);++ // recreating with the same slug must succeed (slug was tombstoned on delete)+ const second = await createProject("e2e-slug-reuse-2", slug);+ expect(second.slug).toBe(slug);+ expect(second.id).not.toBe(first.id);++ await deleteProject(second.id);+ });++ test("cannot delete an already-deleted project", async () => {+ const project = await createProject("e2e-double-delete");+ expect((await deleteProject(project.id)).statusCode).toBe(200);++ // second delete resolves the project via the soft-delete-filtered read → not found+ expect((await deleteProject(project.id)).statusCode).toBe(404);+ });+});diff --git a/backend/src/db/migrations/20260602100000_add-secret-versions-v2-envid-index.ts b/backend/src/db/migrations/20260602100000_add-secret-versions-v2-envid-index.tsnew file mode 100644index 0000000000..1609aa8177--- /dev/null+++ b/backend/src/db/migrations/20260602100000_add-secret-versions-v2-envid-index.ts@@ -0,0 +1,45 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++// secret_versions_v2.envId has an ON DELETE CASCADE FK to project_environments but no index, so+// deleting an environment seq-scans the entire secret_versions_v2 table to enforce the+// cascade. envId is nullable and ~99% NULL, and the cascade only ever looks up specific non-null+// env UUIDs, so a partial index over the non-null rows fully serves the cascade while staying tiny+// and imposing ~zero write overhead (NULL-envId inserts skip it).+const INDEX_NAME = "idx_secret_versions_v2_envid";+const MIGRATION_TIMEOUT = 60 * 60 * 1000; // 60 minutes+const MIGRATION_LOCK_TIMEOUT = 30 * 1000; // 30 seconds++export async function up(knex: Knex): Promise<void> {+ const stmtResult = await knex.raw("SHOW statement_timeout");+ const originalStatementTimeout = stmtResult.rows[0].statement_timeout;+ const lockResult = await knex.raw("SHOW lock_timeout");+ const originalLockTimeout = lockResult.rows[0].lock_timeout;++ try {+ await knex.raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);+ await knex.raw(`SET lock_timeout = ${MIGRATION_LOCK_TIMEOUT}`);++ if (+ (await knex.schema.hasTable(TableName.SecretVersionV2)) &&+ (await knex.schema.hasColumn(TableName.SecretVersionV2, "envId"))+ ) {+ await knex.raw(`+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${INDEX_NAME}"+ ON ${TableName.SecretVersionV2} ("envId")+ WHERE "envId" IS NOT NULL+ `);+ }+ } finally {+ await knex.raw(`SET statement_timeout = '${originalStatementTimeout}'`);+ await knex.raw(`SET lock_timeout = '${originalLockTimeout}'`);+ }+}++export async function down(knex: Knex): Promise<void> {+ await knex.raw(`DROP INDEX IF EXISTS "${INDEX_NAME}"`);+}++const config = { transaction: false };+export { config };diff --git a/backend/src/db/migrations/20260602100100_add-soft-delete-to-projects.ts b/backend/src/db/migrations/20260602100100_add-soft-delete-to-projects.tsnew file mode 100644index 0000000000..977be0fd06--- /dev/null+++ b/backend/src/db/migrations/20260602100100_add-soft-delete-to-projects.ts@@ -0,0 +1,47 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ const hasTable = await knex.schema.hasTable(TableName.Project);+ if (!hasTable) return;++ const hasDeleteAfter = await knex.schema.hasColumn(TableName.Project, "deleteAfter");+ const hasSoftDeletedAt = await knex.schema.hasColumn(TableName.Project, "softDeletedAt");+ const hasDeletedByUserId = await knex.schema.hasColumn(TableName.Project, "deletedByUserId");+ const hasDeletedByIdentityId = await knex.schema.hasColumn(TableName.Project, "deletedByIdentityId");++ if (!hasDeleteAfter || !hasSoftDeletedAt || !hasDeletedByUserId || !hasDeletedByIdentityId) {+ await knex.schema.alterTable(TableName.Project, (t) => {+ if (!hasDeleteAfter) t.timestamp("deleteAfter", { useTz: true }).nullable();+ if (!hasSoftDeletedAt) t.timestamp("softDeletedAt", { useTz: true }).nullable();+ if (!hasDeletedByUserId) {+ t.uuid("deletedByUserId").nullable();+ t.foreign("deletedByUserId").references("id").inTable(TableName.Users).onDelete("SET NULL");+ }+ if (!hasDeletedByIdentityId) {+ t.uuid("deletedByIdentityId").nullable();+ t.foreign("deletedByIdentityId").references("id").inTable(TableName.Identity).onDelete("SET NULL");+ }+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ const hasTable = await knex.schema.hasTable(TableName.Project);+ if (!hasTable) return;++ const hasDeleteAfter = await knex.schema.hasColumn(TableName.Project, "deleteAfter");+ const hasSoftDeletedAt = await knex.schema.hasColumn(TableName.Project, "softDeletedAt");+ const hasDeletedByUserId = await knex.schema.hasColumn(TableName.Project, "deletedByUserId");+ const hasDeletedByIdentityId = await knex.schema.hasColumn(TableName.Project, "deletedByIdentityId");++ if (hasDeleteAfter || hasSoftDeletedAt || hasDeletedByUserId || hasDeletedByIdentityId) {+ await knex.schema.alterTable(TableName.Project, (t) => {+ if (hasDeletedByUserId) t.dropColumn("deletedByUserId");+ if (hasDeletedByIdentityId) t.dropColumn("deletedByIdentityId");+ if (hasDeleteAfter) t.dropColumn("deleteAfter");+ if (hasSoftDeletedAt) t.dropColumn("softDeletedAt");+ });+ }+}diff --git a/backend/src/db/migrations/20260602100200_add-projects-soft-deleted-index.ts b/backend/src/db/migrations/20260602100200_add-projects-soft-deleted-index.tsnew file mode 100644index 0000000000..2c0b981c1f--- /dev/null+++ b/backend/src/db/migrations/20260602100200_add-projects-soft-deleted-index.ts@@ -0,0 +1,43 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++// Partial index over only soft-deleted projects. The hard-delete cron scans for+// "deleteAfter <= now()", so this keeps that scan cheap while staying tiny and+// imposing ~zero write overhead on live projects (deleteAfter IS NULL skips it).+const INDEX_NAME = "idx_projects_delete_after";+const MIGRATION_TIMEOUT = 60 * 60 * 1000; // 60 minutes+const MIGRATION_LOCK_TIMEOUT = 30 * 1000; // 30 seconds++export async function up(knex: Knex): Promise<void> {+ const stmtResult = await knex.raw("SHOW statement_timeout");+ const originalStatementTimeout = stmtResult.rows[0].statement_timeout;+ const lockResult = await knex.raw("SHOW lock_timeout");+ const originalLockTimeout = lockResult.rows[0].lock_timeout;++ try {+ await knex.raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);+ await knex.raw(`SET lock_timeout = ${MIGRATION_LOCK_TIMEOUT}`);++ if (+ (await knex.schema.hasTable(TableName.Project)) &&+ (await knex.schema.hasColumn(TableName.Project, "deleteAfter"))+ ) {+ await knex.raw(`+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${INDEX_NAME}"+ ON ${TableName.Project} ("deleteAfter")+ WHERE "deleteAfter" IS NOT NULL+ `);+ }+ } finally {+ await knex.raw(`SET statement_timeout = '${originalStatementTimeout}'`);+ await knex.raw(`SET lock_timeout = '${originalLockTimeout}'`);+ }+}++export async function down(knex: Knex): Promise<void> {+ await knex.raw(`DROP INDEX IF EXISTS "${INDEX_NAME}"`);+}++const config = { transaction: false };+export { config };diff --git a/backend/src/db/migrations/20260602100300_cleanup-orphan-secret-versions-v2.ts b/backend/src/db/migrations/20260602100300_cleanup-orphan-secret-versions-v2.tsnew file mode 100644index 0000000000..2729b0fc02--- /dev/null+++ b/backend/src/db/migrations/20260602100300_cleanup-orphan-secret-versions-v2.ts@@ -0,0 +1,51 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++// One-off cleanup of ORPHANED secret_versions_v2 rows. secret_versions_v2 has no FK on folderId+// (only a mostly-NULL envId cascade), so the OLD synchronous project-delete path left version rows+// behind with folderId pointing at folders that were cascade-deleted. The daily pruneExcessVersions+// job can't reach them (its INNER JOINs folder→env→project drop orphans), so they accumulate as dead+// weight that also bloats scans of this table. New deletions no longer orphan (the cleanup queue+// prunes versions by folderId first), so this is a one-time reclaim.+//+// Batched (one short autocommitted DELETE per iteration, statement_timeout-bounded) so it never takes+// one giant lock / WAL spike. Idempotent: if the migration is re-run after a partial failure it simply+// continues deleting whatever orphans remain.+const BATCH_SIZE = 20_000;+const BATCH_STATEMENT_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes per batch++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.SecretVersionV2))) return;++ const stmtResult = await knex.raw("SHOW statement_timeout");+ const originalStatementTimeout = stmtResult.rows[0].statement_timeout;++ try {+ await knex.raw(`SET statement_timeout = ${BATCH_STATEMENT_TIMEOUT_MS}`);++ for (;;) {+ const idsToDelete = knex(TableName.SecretVersionV2)+ .whereNotExists((qb) => {+ void qb+ .select(knex.raw("1"))+ .from(TableName.SecretFolder)+ .whereRaw(`"${TableName.SecretFolder}".id = "${TableName.SecretVersionV2}"."folderId"`);+ })+ .select("id")+ .limit(BATCH_SIZE);++ // eslint-disable-next-line no-await-in-loop+ const deleted = await knex(TableName.SecretVersionV2).whereIn("id", idsToDelete).delete();+ if (deleted < BATCH_SIZE) break;+ }+ } finally {+ await knex.raw(`SET statement_timeout = '${originalStatementTimeout}'`);+ }+}++// Irreversible by design — deleted orphan rows cannot be reconstructed.+export async function down(): Promise<void> {}++const config = { transaction: false };+export { config };diff --git a/backend/src/db/schemas/projects.ts b/backend/src/db/schemas/projects.tsindex 600edfa438..1f49da721a 100644--- a/backend/src/db/schemas/projects.ts+++ b/backend/src/db/schemas/projects.ts@@ -32,7 +32,11 @@ export const ProjectsSchema = z.object({showSnapshotsLegacy: z.boolean().default(false),defaultProduct: z.string().nullable().optional(),secretDetectionIgnoreValues: z.string().array().nullable().optional(),- enforceEncryptedSecretManagerSecretMetadata: z.boolean().nullable().optional()+ enforceEncryptedSecretManagerSecretMetadata: z.boolean().nullable().optional(),+ deleteAfter: z.date().nullable().optional(),+ softDeletedAt: z.date().nullable().optional(),+ deletedByUserId: z.string().uuid().nullable().optional(),+ deletedByIdentityId: z.string().uuid().nullable().optional()});export type TProjects = z.infer<typeof ProjectsSchema>;diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex ae8fe769b7..6dbe76cd03 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -5416,6 +5416,9 @@ interface ProjectDeleteEvent {metadata: {id: string;name: string;+ // true: actor soft-deleted the project (marked for deletion).+ // false: the async cleanup worker hard-deleted an expired soft-deleted project.+ softDelete?: boolean;};}diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.tsindex c69b91e310..33e9ccca41 100644--- a/backend/src/lib/cron/cron-job.ts+++ b/backend/src/lib/cron/cron-job.ts@@ -30,6 +30,7 @@ export const CronJobName = {TelemetryAggregatedEvents: "telemetry-aggregated-events",DigiCertOrderPolling: "digicert-order-polling",ProjectEnvHardDelete: "project-env-hard-delete",+ ProjectHardDelete: "project-hard-delete",DigiCertRevocationSync: "digicert-revocation-sync",CaCrlRotation: "ca-crl-rotation"} as const;diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex 3708f0023b..d89864139a 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -109,7 +109,8 @@ export enum QueueName {AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate",AuditLogClickHouseBatch = "audit-log-clickhouse-batch",PamDiscoveryScan = "pam-discovery-scan",- CaAutoRenewal = "ca-auto-renewal"+ CaAutoRenewal = "ca-auto-renewal",+ ProjectHardDelete = "project-hard-delete"}export enum QueueJobs {@@ -181,7 +182,8 @@ export enum QueueJobs {CaAdcsInstall = "ca-adcs-install-job",CertificateCleanup = "certificate-cleanup-job",DailySecretSyncRetry = "daily-secret-sync-retry-job",- DigiCertOrderPolling = "digicert-order-polling-job"+ DigiCertOrderPolling = "digicert-order-polling-job",+ ProjectHardDelete = "project-hard-delete-job"}export type TQueueOptions = {@@ -495,6 +497,10 @@ export type TQueueJobTypes = {name: QueueJobs.CaAdcsInstall;payload: { caId: string; maxPathLength?: number };};+ [QueueName.ProjectHardDelete]: {+ name: QueueJobs.ProjectHardDelete;+ payload: { projectId: string };+ };};const SECRET_SCANNING_QUEUES = [@@ -527,7 +533,7 @@ export type TQueueServiceFactory = {token?: string,signal?: AbortSignal) => Promise<void>,- queueSettings?: Omit<QueueOptions, "connection"> & Pick<WorkerOptions, "concurrency">+ queueSettings?: Omit<QueueOptions, "connection"> & Pick<WorkerOptions, "concurrency" | "limiter">) => void;listen: <T extends QueueName,diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 8de212dea5..1cfbf45a43 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -422,6 +422,7 @@ import { pkiSyncServiceFactory } from "@app/services/pki-sync/pki-sync-service";import { pkiTemplatesDALFactory } from "@app/services/pki-templates/pki-templates-dal";import { pkiTemplatesServiceFactory } from "@app/services/pki-templates/pki-templates-service";import { projectAccessRequestDALFactory } from "@app/services/project/project-access-request-dal";+import { projectCleanupQueueFactory } from "@app/services/project/project-cleanup-queue";import { projectDALFactory } from "@app/services/project/project-dal";import { projectQueueFactory } from "@app/services/project/project-queue";import { projectServiceFactory } from "@app/services/project/project-service";@@ -1743,6 +1744,17 @@ export const registerRoutes = async (auditLogService});+ const projectCleanupQueue = projectCleanupQueueFactory({+ cronJob,+ queueService,+ projectDAL,+ membershipUserDAL,+ userDAL,+ kmsService,+ keyStore,+ auditLogService+ });+const projectEnvService = projectEnvServiceFactory({permissionService,projectEnvDAL,@@ -3417,6 +3429,7 @@ export const registerRoutes = async (telemetryQueue.startAggregatedEventsJob();dailyResourceCleanUp.init();projectEnvQueue.init();+ projectCleanupQueue.init();healthAlert.init();pkiSyncCleanup.init();pkiDiscoveryQueue.startPkiDiscoveryScanQueue();diff --git a/backend/src/server/routes/v1/project-router.ts b/backend/src/server/routes/v1/project-router.tsindex c5967d3125..8354a57cb3 100644--- a/backend/src/server/routes/v1/project-router.ts+++ b/backend/src/server/routes/v1/project-router.ts@@ -25,7 +25,6 @@ import { loginMappingSchema, sanitizedSshHost } from "@app/ee/services/ssh-host/import { LoginMappingSource } from "@app/ee/services/ssh-host/ssh-host-types";import { sanitizedSshHostGroup } from "@app/ee/services/ssh-host-group/ssh-host-group-schema";import { ApiDocsTags, PROJECTS } from "@app/lib/api-docs";-import { BadRequestError } from "@app/lib/errors";import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";import { re2Validator } from "@app/lib/zod";import { projectCreationLimit, readLimit, requestAccessLimit, writeLimit } from "@app/server/config/rateLimiter";@@ -435,10 +434,35 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {}},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async () => {- throw new BadRequestError({- message: "Project deletion is temporarily disabled. Please try again later."+ handler: async (req) => {+ // Soft delete: returns fast (single UPDATE). The async cleanup worker hard-deletes the project+ // after its grace period.+ const project = await server.services.project.deleteProject({+ actorId: req.permission.id,+ actor: req.permission.type,+ actorOrgId: req.permission.orgId,+ actorAuthMethod: req.permission.authMethod,+ filter: {+ type: ProjectFilterType.ID,+ projectId: req.params.projectId+ }});++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: project.id,+ event: {+ type: EventType.DELETE_PROJECT,+ metadata: {+ id: project.id,+ name: project.name,+ softDelete: true+ }+ }+ });++ return { project };}});diff --git a/backend/src/services/project/project-cleanup-queue.ts b/backend/src/services/project/project-cleanup-queue.tsnew file mode 100644index 0000000000..8815800e10--- /dev/null+++ b/backend/src/services/project/project-cleanup-queue.ts@@ -0,0 +1,260 @@+import opentelemetry from "@opentelemetry/api";++import { AccessScope } from "@app/db/schemas";+import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";+import { getConfig } from "@app/lib/config/env";+import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";+import { logger } from "@app/lib/logger";+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";++import { ActorType } from "../auth/auth-type";+import { TKmsServiceFactory } from "../kms/kms-service";+import { TMembershipUserDALFactory } from "../membership-user/membership-user-dal";+import { TUserDALFactory } from "../user/user-dal";+import { TProjectDALFactory } from "./project-dal";++// ── load shaping ──────────────────────────────────────────────────────────────+// The cron tick is NOT the pacer — it only keeps the queue fed. Selecting the oldest+// DISCOVERY_BATCH expired projects (ORDER BY deleteAfter ASC) + jobId dedupe keeps the in-flight+// set bounded at ~DISCOVERY_BATCH regardless of backlog size (we never enqueue 85k at once).+// The worker meters the actual drain RATE via the rate limiter + concurrency, so DB load is a+// flat plateau rather than a per-tick spike.+const DISCOVERY_BATCH = 200;+const WORKER_CONCURRENCY = 3; // ceiling on simultaneous heavy deletes (fleet-wide)+const RATE_LIMIT_MAX = 30; // steady drain rate: 30 projects / minute+const RATE_LIMIT_DURATION_MS = 60 * 1000;++// per-project chunked secret_versions_v2 delete tuning+const SECRET_VERSION_DELETE_BATCH = 5000;+const BATCH_STATEMENT_TIMEOUT_MS = 30 * 1000;+const INTER_BATCH_SLEEP_MS = 10;++// Generous so a large project's chunked delete won't see the lock expire mid-flight and let a+// second worker start; crash recovery happens on the next cron tick after expiry.+const PROJECT_DELETE_LOCK_TTL_MS = 30 * 60 * 1000;+const CRON_HANDLER_TIMEOUT_MS = 5 * 60 * 1000;++type TProjectCleanupQueueFactoryDep = {+ projectDAL: Pick<+ TProjectDALFactory,+ | "findExpiredForHardDelete"+ | "countPendingHardDelete"+ | "findByIdIncludingExpired"+ | "findIncludingExpired"+ | "findProjectGhostUser"+ | "hardDeleteProjectSecretVersionsInBatches"+ | "deleteById"+ | "transaction"+ >;+ membershipUserDAL: Pick<TMembershipUserDALFactory, "delete">;+ userDAL: Pick<TUserDALFactory, "deleteById">;+ kmsService: Pick<TKmsServiceFactory, "deleteInternalKms">;+ keyStore: Pick<TKeyStoreFactory, "acquireLock" | "deleteItem">;+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;+ queueService: Pick<TQueueServiceFactory, "queue" | "start">;+ cronJob: TCronJobFactory;+};++export type TProjectCleanupQueueFactory = ReturnType<typeof projectCleanupQueueFactory>;++export const projectCleanupQueueFactory = ({+ projectDAL,+ membershipUserDAL,+ userDAL,+ kmsService,+ keyStore,+ auditLogService,+ queueService,+ cronJob+}: TProjectCleanupQueueFactoryDep) => {+ const appCfg = getConfig();++ if (appCfg.isDailyResourceCleanUpDevelopmentMode) {+ logger.warn("Project hard-delete cron is in development mode.");+ }++ // ── observability ─────────────────────────────────────────────────────────────+ // Generic per-queue metrics (job count/duration/wait/depth, tagged queue.name=project-hard-delete)+ // come for free from queue-service. These are the domain-specific signals that tell us whether the+ // drain is healthy or the knobs (RATE_LIMIT_MAX / WORKER_CONCURRENCY / SECRET_VERSION_DELETE_BATCH)+ // need tuning — and surface a mass-delete event early.+ const meter = opentelemetry.metrics.getMeter("InfisicalCore");+ const processedCounter = meter.createCounter("infisical.project_cleanup.processed", {+ description: "Projects processed by the hard-delete worker, by outcome (deleted/skipped/failed)",+ unit: "{project}"+ });+ const durationHistogram = meter.createHistogram("infisical.project_cleanup.duration", {+ description: "Per-project hard-delete wall-clock seconds. Rising p95 → raise concurrency/limiter or lower batch.",+ unit: "s"+ });+ const versionsPrunedHistogram = meter.createHistogram("infisical.project_cleanup.secret_versions_pruned", {+ description: "secret_versions_v2 rows pruned per project — reveals project-size distribution for batch tuning",+ unit: "{row}"+ });+ // Queue depth caps at ~DISCOVERY_BATCH, so it can't reveal the true+ // backlog. This counts projects with deleteAfter set directly in the DB. Sustained growth = the+ // drain rate can't keep up or a mass-delete is in progress.+ const pendingGauge = meter.createObservableGauge("infisical.project_cleanup.pending", {+ description:+ "Projects awaiting hard delete (deleteAfter set). Sustained growth = drain can't keep up / mass-delete.",+ unit: "{project}"+ });+ pendingGauge.addCallback(async (observableResult) => {+ if (!getConfig().OTEL_TELEMETRY_COLLECTION_ENABLED) return;+ try {+ observableResult.observe(await projectDAL.countPendingHardDelete());+ } catch (err) {+ logger.warn({ err }, "project_cleanup.pending gauge: count failed");+ }+ });++ const processProjectHardDelete = async (projectId: string) => {+ const startedAt = Date.now();+ const lock = await keyStore+ .acquireLock([KeyStorePrefixes.ProjectDeleteLock(projectId)], PROJECT_DELETE_LOCK_TTL_MS)+ .catch(() => null);+ if (!lock) {+ processedCounter.add(1, { outcome: "skipped", reason: "locked" });+ logger.info(`project-hard-delete: lock held, will retry next firing [projectId=${projectId}]`);+ return;+ }++ try {+ // Read via transaction → primary, not replica. Defeats replica-lag races against a concurrent+ // worker that already finished.+ const project = await projectDAL.transaction((tx) => projectDAL.findByIdIncludingExpired(projectId, tx));+ if (!project || !project.deleteAfter || new Date(project.deleteAfter).getTime() > Date.now()) {+ processedCounter.add(1, { outcome: "skipped", reason: "gone_or_restored" });+ logger.info(`project-hard-delete: skipping (gone/already-removed/not-yet-expired) [projectId=${projectId}]`);+ return;+ }++ // 1) Chunk-delete the largest project-scoped table ahead of the final cascade. secret_versions_v2+ // has no folderId/secretId FK (only a mostly-NULL envId cascade), so the project-delete cascade+ // would otherwise orphan ~all of these rows. Deleting by folderId is FK-safe and bounds the+ // final cascade's transaction size.+ const deletedVersions = await projectDAL.hardDeleteProjectSecretVersionsInBatches(+ projectId,+ SECRET_VERSION_DELETE_BATCH,+ BATCH_STATEMENT_TIMEOUT_MS,+ INTER_BATCH_SLEEP_MS+ );++ // 2) Final cascade in one transaction — handles the remaining (smaller) child tables, including+ // deferred / NO ACTION FKs (e.g. secret_rotation_v2_secret_mappings) that PG resolves correctly+ // as a single cascade tree (the same proven path the synchronous delete used).+ const deleted = await projectDAL.transaction(async (tx) => {+ // capture the ghost user before its project membership is removed below+ const ghostUser = await projectDAL.findProjectGhostUser(projectId, tx).catch(() => null);++ await membershipUserDAL.delete(+ { scopeOrgId: project.orgId, scopeProjectId: projectId, scope: AccessScope.Project },+ tx+ );++ const delProject = await projectDAL.deleteById(projectId, tx);+ // a racing worker may have hard-deleted it after our re-read but before we acquired the row+ if (!delProject) return false;++ // before removing a KMS key, ensure no other (incl. pending-deletion) project references it+ if (delProject.kmsCertificateKeyId) {+ const linked = await projectDAL.findIncludingExpired(+ { kmsCertificateKeyId: delProject.kmsCertificateKeyId },+ { tx }+ );+ if (!linked.length) await kmsService.deleteInternalKms(delProject.kmsCertificateKeyId, delProject.orgId, tx);+ }+ if (delProject.kmsSecretManagerKeyId) {+ const linked = await projectDAL.findIncludingExpired(+ { kmsSecretManagerKeyId: delProject.kmsSecretManagerKeyId },+ { tx }+ );+ if (!linked.length)+ await kmsService.deleteInternalKms(delProject.kmsSecretManagerKeyId, delProject.orgId, tx);+ }++ if (ghostUser) await userDAL.deleteById(ghostUser.id, tx);+ return true;+ });++ if (!deleted) {+ processedCounter.add(1, { outcome: "skipped", reason: "already_removed" });+ logger.info(`project-hard-delete: already removed by a concurrent worker [projectId=${projectId}]`);+ return;+ }++ await keyStore.deleteItem(KeyStorePrefixes.LicenseCloudPlan(project.orgId));+ await auditLogService.createAuditLog({+ projectId,+ actor: { type: ActorType.PLATFORM, metadata: {} },+ event: {+ type: EventType.DELETE_PROJECT,+ metadata: { id: projectId, name: project.name, softDelete: false }+ }+ });++ const durationSec = (Date.now() - startedAt) / 1000;+ processedCounter.add(1, { outcome: "deleted" });+ durationHistogram.record(durationSec);+ versionsPrunedHistogram.record(deletedVersions);+ logger.info(+ { projectId, deletedVersions, durationSec },+ `project-hard-delete: hard-deleted project [projectId=${projectId}] [versionsPruned=${deletedVersions}] [durationSec=${durationSec.toFixed(1)}]`+ );+ } catch (err) {+ processedCounter.add(1, { outcome: "failed" });+ logger.error({ err, projectId }, `project-hard-delete: failed [projectId=${projectId}]`);+ throw err; // surface to BullMQ so it retries (attempts: 3) and the generic failure metric fires+ } finally {+ await lock.release();+ }+ };++ const init = () => {+ // Worker: meters the actual drain rate. concurrency caps parallelism; the limiter caps throughput+ // (fleet-wide via Redis) so a backlog drains as an even plateau instead of a burst.+ queueService.start(+ QueueName.ProjectHardDelete,+ async (job) => {+ await processProjectHardDelete(job.data.projectId);+ },+ { concurrency: WORKER_CONCURRENCY, limiter: { max: RATE_LIMIT_MAX, duration: RATE_LIMIT_DURATION_MS } }+ );++ // Cron tick: discovery only (fast). Enqueues the oldest expired projects; jobId dedupe keeps the+ // queue bounded and idempotent across ticks.+ cronJob.register({+ name: CronJobName.ProjectHardDelete,+ pattern: appCfg.isDailyResourceCleanUpDevelopmentMode ? "* * * * *" : "*/5 * * * *",+ runHashTtlS: 3 * 24 * 60 * 60,+ handlerTimeoutMs: CRON_HANDLER_TIMEOUT_MS,+ leaseDurationMs: CRON_HANDLER_TIMEOUT_MS,+ enabled: !appCfg.isSecondaryInstance,+ handler: async () => {+ const expiredProjects = await projectDAL.findExpiredForHardDelete(DISCOVERY_BATCH);+ if (expiredProjects.length === 0) return;++ logger.info(`cron[${CronJobName.ProjectHardDelete}]: enqueuing ${expiredProjects.length} expired project(s)`);+ await Promise.all(+ expiredProjects.map((project) =>+ queueService.queue(+ QueueName.ProjectHardDelete,+ QueueJobs.ProjectHardDelete,+ { projectId: project.id },+ {+ jobId: `project-hard-delete-${project.id}`,+ removeOnComplete: true,+ removeOnFail: { count: 50 },+ attempts: 3,+ backoff: { type: "exponential", delay: 5000 }+ }+ )+ )+ );+ }+ });+ };++ return { init };+};diff --git a/backend/src/services/project/project-dal.ts b/backend/src/services/project/project-dal.tsindex 91c8831690..0a6823964d 100644--- a/backend/src/services/project/project-dal.ts+++ b/backend/src/services/project/project-dal.ts@@ -14,7 +14,14 @@ import {} from "@app/db/schemas";import { BadRequestError, DatabaseError, NotFoundError, UnauthorizedError } from "@app/lib/errors";import { sanitizeSqlLikeString } from "@app/lib/fn";-import { buildFindFilter, ormify, selectAllTableCols, sqlNestRelationships } from "@app/lib/knex";+import {+ buildFindFilter,+ ormify,+ selectAllTableCols,+ sqlNestRelationships,+ TFindFilter,+ TFindOpt+} from "@app/lib/knex";import { ActorType } from "../auth/auth-type";import { Filter, ProjectFilterType, SearchProjectSortBy } from "./project-types";@@ -24,6 +31,150 @@ export type TProjectDALFactory = ReturnType<typeof projectDALFactory>;export const projectDALFactory = (db: TDbClient) => {const projectOrm = ormify(db, TableName.Project);+ // Soft-deleted projects (deleteAfter set) must be hidden from every read path. We override the+ // ormify base reads so indirect callers can't accidentally surface a pending-deletion project,+ // and expose explicit *IncludingExpired escape hatches for the restore + hard-delete worker.+ const findById: typeof projectOrm.findById = async (id, tx) => {+ try {+ const result = await (tx || db.replicaNode())(TableName.Project)+ .where({ id })+ .whereNull("deleteAfter")+ .first("*");+ return result;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find by id" });+ }+ };++ const findOne: typeof projectOrm.findOne = async (filter, tx) => {+ try {+ const res = await (tx || db.replicaNode())(TableName.Project).where(filter).whereNull("deleteAfter").first("*");+ return res;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find one" });+ }+ };++ const find = (async (filter: TFindFilter<TProjects>, { offset, limit, sort, tx }: TFindOpt<TProjects> = {}) => {+ try {+ const query = (tx || db.replicaNode())(TableName.Project)+ // eslint-disable-next-line @typescript-eslint/no-misused-promises+ .where(buildFindFilter(filter))+ .whereNull("deleteAfter");+ if (limit) void query.limit(limit);+ if (offset) void query.offset(offset);+ if (sort) {+ void query.orderBy(sort.map(([column, order, nulls]) => ({ column: column as string, order, nulls })));+ }+ const res = await query;+ return res as TProjects[];+ } catch (error) {+ throw new DatabaseError({ error, name: "Find" });+ }+ }) as typeof projectOrm.find;++ // Bypasses the soft-delete read filter — restore + hard-delete worker only.+ const findByIdIncludingExpired = async (id: string, tx?: Knex) => {+ try {+ const result = await (tx || db.replicaNode())(TableName.Project).where({ id }).first("*");+ return result as TProjects | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find by id including expired" });+ }+ };++ // Raw find that includes soft-deleted rows. Used by the hard-delete worker's KMS shared-key+ // check so a *second* pending-deletion project sharing a key still counts as a referencer.+ const findIncludingExpired = projectOrm.find;++ const softDeleteById = async (+ id: string,+ update: {+ deleteAfter: Date;+ softDeletedAt: Date;+ deletedByUserId: string | null;+ deletedByIdentityId: string | null;+ slug: string;+ },+ tx?: Knex+ ) => {+ try {+ const [doc] = await (tx || db)(TableName.Project)+ .where({ id })+ .whereNull("deleteAfter")+ .update(update)+ .returning("*");+ return doc as TProjects | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Soft delete project" });+ }+ };++ // Count of projects awaiting hard delete (deleteAfter set). Backs the observability gauge — if this+ // climbs and stays high, the async worker's drain rate (concurrency + rate limiter) isn't keeping up+ // and needs tuning, or a mass-delete event is in progress. Uses the partial idx_projects_delete_after.+ const countPendingHardDelete = async (tx?: Knex) => {+ try {+ const doc = await (tx || db.replicaNode())(TableName.Project).whereNotNull("deleteAfter").count();+ return Number(doc?.[0]?.count ?? 0);+ } catch (error) {+ throw new DatabaseError({ error, name: "Count pending hard delete" });+ }+ };++ const findExpiredForHardDelete = async (limit: number, tx?: Knex) => {+ try {+ const rows = await (tx || db.replicaNode())(TableName.Project)+ .whereNotNull("deleteAfter")+ .andWhere("deleteAfter", "<=", new Date())+ .orderBy("deleteAfter", "asc")+ .limit(limit)+ .select("*");+ return rows as TProjects[];+ } catch (error) {+ throw new DatabaseError({ error, name: "Find expired projects for hard delete" });+ }+ };++ // Chunked delete of a project's secret_versions_v2 rows ahead of the final cascade. This table+ // is the largest project-scoped table and has NO FK on folderId/secretId (only a mostly-NULL+ // envId cascade), so the project-delete cascade otherwise orphans ~all of its version rows.+ // Deleting by folderId is FK-safe (no inbound RESTRICT FK; snapshot_secrets_v2.secretVersionId+ // is ON DELETE CASCADE). Each batch is its own transaction so a crash just leaves fewer rows for+ // the next run (idempotent/resumable). statement_timeout is SET LOCAL so it can't leak to pooled+ // connections.+ const hardDeleteProjectSecretVersionsInBatches = async (+ projectId: string,+ batchSize: number,+ statementTimeoutMs: number,+ interBatchSleepMs: number+ ) => {+ let totalDeleted = 0;+ for (;;) {+ // eslint-disable-next-line no-await-in-loop+ const deletedCount = await db.transaction(async (tx): Promise<number> => {+ await tx.raw(`SET LOCAL statement_timeout = ${statementTimeoutMs}`);+ const folderIdsSubquery = tx(TableName.SecretFolder)+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)+ .where(`${TableName.Environment}.projectId`, projectId)+ .select(`${TableName.SecretFolder}.id`);+ const idsToDelete = tx(TableName.SecretVersionV2)+ .whereIn("folderId", folderIdsSubquery)+ .select("id")+ .limit(batchSize);+ const deleted = await tx(TableName.SecretVersionV2).whereIn("id", idsToDelete).delete();+ return deleted;+ });+ totalDeleted += deletedCount;+ if (deletedCount < batchSize) break;+ // eslint-disable-next-line no-await-in-loop+ await new Promise((resolve) => {+ setTimeout(resolve, interBatchSleepMs + Math.floor(Math.random() * interBatchSleepMs));+ });+ }+ return totalDeleted;+ };+const findIdentityProjects = async (identityId: string, orgId: string, projectType?: ProjectType) => {try {const identityGroupSubquery = db@@ -41,6 +192,7 @@ export const projectDALFactory = (db: TDbClient) => {.where(`${TableName.Membership}.scope`, AccessScope.Project).join(TableName.Project, `${TableName.Membership}.scopeProjectId`, `${TableName.Project}.id`).where(`${TableName.Project}.orgId`, orgId)+ .whereNull(`${TableName.Project}.deleteAfter`).andWhere((qb) => {void qb.where(`${TableName.Membership}.actorIdentityId`, identityId)@@ -107,6 +259,7 @@ export const projectDALFactory = (db: TDbClient) => {.where(`${TableName.Membership}.scope`, AccessScope.Project).join(TableName.Project, `${TableName.Membership}.scopeProjectId`, `${TableName.Project}.id`).where(`${TableName.Project}.orgId`, orgId)+ .whereNull(`${TableName.Project}.deleteAfter`).andWhere((qb) => {void qb.where(`${TableName.Membership}.actorUserId`, userId)@@ -188,6 +341,8 @@ export const projectDALFactory = (db: TDbClient) => {.where(`${TableName.Membership}.scope`, AccessScope.Project).where(`${TableName.Membership}.scopeOrgId`, orgId).whereNotNull(`${TableName.Membership}.scopeProjectId`)+ .join(TableName.Project, `${TableName.Membership}.scopeProjectId`, `${TableName.Project}.id`)+ .whereNull(`${TableName.Project}.deleteAfter`).andWhere((qb) => {void qb.where(`${TableName.Membership}.${actorColumn}`, actorId)@@ -204,7 +359,10 @@ export const projectDALFactory = (db: TDbClient) => {// Lightweight all-projects-in-org lookup that returns only the IDs.const findOrgProjectIds = async (orgId: string, tx?: Knex): Promise<string[]> => {try {- const rows = await (tx || db.replicaNode())(TableName.Project).where({ orgId }).select("id");+ const rows = await (tx || db.replicaNode())(TableName.Project)+ .where({ orgId })+ .whereNull("deleteAfter")+ .select("id");return rows.map((r) => r.id);} catch (error) {throw new DatabaseError({ error, name: "Find org project ids" });@@ -243,6 +401,7 @@ export const projectDALFactory = (db: TDbClient) => {const workspaces = await db.replicaNode()(TableName.Project).where(`${TableName.Project}.id`, id)+ .whereNull(`${TableName.Project}.deleteAfter`).leftJoin(TableName.Environment, function joinActiveEnvByProject() {this.on(`${TableName.Environment}.projectId`, `${TableName.Project}.id`).andOnNull(`${TableName.Environment}.deleteAfter`@@ -300,6 +459,7 @@ export const projectDALFactory = (db: TDbClient) => {.replicaNode()(TableName.Project).where(`${TableName.Project}.slug`, slug).where(`${TableName.Project}.orgId`, orgId)+ .whereNull(`${TableName.Project}.deleteAfter`).leftJoin(TableName.Environment, function joinActiveEnvByProject() {this.on(`${TableName.Environment}.projectId`, `${TableName.Project}.id`).andOnNull(`${TableName.Environment}.deleteAfter`@@ -387,7 +547,7 @@ export const projectDALFactory = (db: TDbClient) => {const project = await db(TableName.Project).where({ [`${TableName.Project}.id` as "id"]: projectId })-+ .whereNull(`${TableName.Project}.deleteAfter`).join(TableName.Organization, `${TableName.Organization}.id`, `${TableName.Project}.orgId`).select(@@ -459,6 +619,7 @@ export const projectDALFactory = (db: TDbClient) => {const query = db.replicaNode()(TableName.Project).where(`${TableName.Project}.orgId`, dto.orgId)+ .whereNull(`${TableName.Project}.deleteAfter`).select(selectAllTableCols(TableName.Project)).select(db.raw("COUNT(*) OVER() AS count")).select<(TProjects & { isMember: boolean; count: number })[]>(@@ -503,6 +664,7 @@ export const projectDALFactory = (db: TDbClient) => {})// eslint-disable-next-line @typescript-eslint/no-misused-promises.where(buildFindFilter({ id: envId }, TableName.Environment))+ .whereNull(`${TableName.Project}.deleteAfter`).select(selectAllTableCols(TableName.Project)).first();return project;@@ -596,6 +758,7 @@ export const projectDALFactory = (db: TDbClient) => {const subOrgProjects = db.replicaNode()(TableName.Organization).where({ rootOrgId: orgId }).select("id");const doc = await (tx || db.replicaNode())(TableName.Project)+ .whereNull("deleteAfter").andWhere((bd) => {if (orgId) {void bd.where({ orgId }).orWhereIn("orgId", subOrgProjects);@@ -610,6 +773,15 @@ export const projectDALFactory = (db: TDbClient) => {return {...projectOrm,+ findById,+ findOne,+ find,+ findByIdIncludingExpired,+ findIncludingExpired,+ softDeleteById,+ countPendingHardDelete,+ findExpiredForHardDelete,+ hardDeleteProjectSecretVersionsInBatches,findUserProjects,findIdentityProjects,findActorAccessibleProjectIds,diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.tsindex 24b48f30a8..e85d3de55b 100644--- a/backend/src/services/project/project-service.ts+++ b/backend/src/services/project/project-service.ts@@ -822,47 +822,28 @@ export const projectServiceFactory = ({}try {- const deletedProject = await projectDAL.transaction(async (tx) => {- // delete these so that project custom roles can be deleted in cascade effect- // direct deletion of project without these will cause fk error- // this will clean up all memberships- await membershipUserDAL.delete(- { scopeOrgId: project.orgId, scopeProjectId: project.id, scope: AccessScope.Project },- tx- );- const delProject = await projectDAL.deleteById(project.id, tx);- const projectGhostUser = await projectMembershipDAL.findProjectGhostUser(project.id, tx).catch(() => null);- // akhilmhdh: before removing those kms checking any other project uses it- // happened due to project split- if (delProject.kmsCertificateKeyId) {- const projectsLinkedToForiegnKey = await projectDAL.find(- { kmsCertificateKeyId: delProject.kmsCertificateKeyId },- { tx }- );- if (!projectsLinkedToForiegnKey.length) {- await kmsService.deleteInternalKms(delProject.kmsCertificateKeyId, delProject.orgId, tx);- }- }-- if (delProject.kmsSecretManagerKeyId) {- const projectsLinkedToForiegnKey = await projectDAL.find(- { kmsSecretManagerKeyId: delProject.kmsSecretManagerKeyId },- { tx }- );- if (!projectsLinkedToForiegnKey.length) {- await kmsService.deleteInternalKms(delProject.kmsSecretManagerKeyId, delProject.orgId, tx);- }- }- // Delete the org membership for the ghost user if it's found.- if (projectGhostUser) {- await userDAL.deleteById(projectGhostUser.id, tx);- }-- return delProject;+ // "Real delete" from the caller's perspective: this returns immediately (one UPDATE) and the+ // project disappears from every read, but the expensive cascade runs asynchronously in the+ // hard-delete worker. deleteAfter = now marks it immediately eligible for the next worker tick+ // (no grace period). The slug is freed so a same-named project can be recreated right away.+ const now = new Date();+ const deleteAfter = now;+ const softDeletedProject = await projectDAL.softDeleteById(project.id, {+ deleteAfter,+ softDeletedAt: now,+ deletedByUserId: actor === ActorType.USER ? actorId : null,+ deletedByIdentityId: actor === ActorType.IDENTITY ? actorId : null,+ slug: `del-${alphaNumericNanoId(20)}`});+ if (!softDeletedProject) {+ throw new NotFoundError({ message: `Project with ID '${project.id}' not found` });+ }++ // refresh the cached plan so the freed workspace slot is reflected immediately+ // (countOfOrgProjects now excludes soft-deleted projects)await keyStore.deleteItem(KeyStorePrefixes.LicenseCloudPlan(actorOrgId));- return deletedProject;+ return softDeletedProject;} finally {await lock.release();}