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
refactor(soft-delete): update project and environment schemas to replace deletedByUserId and deletedByIdentityId with deletedByActorType and deletedByActorId; adjust related migrations and queries to ensure proper handling of soft-deletion logic across the application.
Victor Hugo dos Santos8ac3f373a688
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex d5cee6a38a..fd5a2f3bf2 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -229,8 +229,9 @@ See `src/services/health-alert/health-alert-queue.ts` for a minimal example, `srResources 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.+- **Soft-delete columns** on the table: `deleteAfter`, `softDeletedAt`, `deletedByActorType`, `deletedByActorId`, 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. The actor pair follows the same `(actorType, actorId)` pattern used by audit logs — extensible to any `ActorType` without schema changes.- **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.+- **`Environment.deleteAfter` ≠ `Project.deleteAfter` — filter both.** The two soft-deletes are independent: soft-deleting a project does NOT soft-delete its environments. Many DALs already filter `Environment.deleteAfter` (from the env soft-delete) — that does **not** exclude a soft-deleted *project*'s data. So any **cron / cross-project enumeration** must also filter `Project.deleteAfter`: the rotation/sync/reminder queue queries, and cross-project listings (project/identity memberships, group projects, org product stats). External side effects are the dangerous case — without it, a soft-deleted project's secrets get rotated, synced, or reminded on during the cleanup window. Per-project reads resolved through `projectDAL.findById` are protected upstream (it returns nothing for a soft-deleted project).- **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`).diff --git a/backend/src/db/migrations/20260527120000_add-delete-after-and-soft-deleted-at-to-project-environments.ts b/backend/src/db/migrations/20260527120000_add-delete-after-and-soft-deleted-at-to-project-environments.tsindex 672922f546..e3e42f47f5 100644--- a/backend/src/db/migrations/20260527120000_add-delete-after-and-soft-deleted-at-to-project-environments.ts+++ b/backend/src/db/migrations/20260527120000_add-delete-after-and-soft-deleted-at-to-project-environments.ts@@ -8,21 +8,15 @@ export async function up(knex: Knex): Promise<void> {const hasDeleteAfter = await knex.schema.hasColumn(TableName.Environment, "deleteAfter");const hasSoftDeletedAt = await knex.schema.hasColumn(TableName.Environment, "softDeletedAt");- const hasDeletedByUserId = await knex.schema.hasColumn(TableName.Environment, "deletedByUserId");- const hasDeletedByIdentityId = await knex.schema.hasColumn(TableName.Environment, "deletedByIdentityId");+ const hasDeletedByActorType = await knex.schema.hasColumn(TableName.Environment, "deletedByActorType");+ const hasDeletedByActorId = await knex.schema.hasColumn(TableName.Environment, "deletedByActorId");- if (!hasDeleteAfter || !hasSoftDeletedAt || !hasDeletedByUserId || !hasDeletedByIdentityId) {+ if (!hasDeleteAfter || !hasSoftDeletedAt || !hasDeletedByActorType || !hasDeletedByActorId) {await knex.schema.alterTable(TableName.Environment, (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");- }+ if (!hasDeletedByActorType) t.string("deletedByActorType").nullable();+ if (!hasDeletedByActorId) t.uuid("deletedByActorId").nullable();});}}@@ -33,13 +27,13 @@ export async function down(knex: Knex): Promise<void> {const hasDeleteAfter = await knex.schema.hasColumn(TableName.Environment, "deleteAfter");const hasSoftDeletedAt = await knex.schema.hasColumn(TableName.Environment, "softDeletedAt");- const hasDeletedByUserId = await knex.schema.hasColumn(TableName.Environment, "deletedByUserId");- const hasDeletedByIdentityId = await knex.schema.hasColumn(TableName.Environment, "deletedByIdentityId");+ const hasDeletedByActorType = await knex.schema.hasColumn(TableName.Environment, "deletedByActorType");+ const hasDeletedByActorId = await knex.schema.hasColumn(TableName.Environment, "deletedByActorId");- if (hasDeleteAfter || hasSoftDeletedAt || hasDeletedByUserId || hasDeletedByIdentityId) {+ if (hasDeleteAfter || hasSoftDeletedAt || hasDeletedByActorType || hasDeletedByActorId) {await knex.schema.alterTable(TableName.Environment, (t) => {- if (hasDeletedByUserId) t.dropColumn("deletedByUserId");- if (hasDeletedByIdentityId) t.dropColumn("deletedByIdentityId");+ if (hasDeletedByActorType) t.dropColumn("deletedByActorType");+ if (hasDeletedByActorId) t.dropColumn("deletedByActorId");if (hasDeleteAfter) t.dropColumn("deleteAfter");if (hasSoftDeletedAt) t.dropColumn("softDeletedAt");});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.tsindex 977be0fd06..2817ac03de 100644--- a/backend/src/db/migrations/20260602100100_add-soft-delete-to-projects.ts+++ b/backend/src/db/migrations/20260602100100_add-soft-delete-to-projects.ts@@ -8,21 +8,15 @@ export async function up(knex: Knex): Promise<void> {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");+ const hasDeletedByActorType = await knex.schema.hasColumn(TableName.Project, "deletedByActorType");+ const hasDeletedByActorId = await knex.schema.hasColumn(TableName.Project, "deletedByActorId");- if (!hasDeleteAfter || !hasSoftDeletedAt || !hasDeletedByUserId || !hasDeletedByIdentityId) {+ if (!hasDeleteAfter || !hasSoftDeletedAt || !hasDeletedByActorType || !hasDeletedByActorId) {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");- }+ if (!hasDeletedByActorType) t.string("deletedByActorType").nullable();+ if (!hasDeletedByActorId) t.uuid("deletedByActorId").nullable();});}}@@ -33,13 +27,13 @@ export async function down(knex: Knex): Promise<void> {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");+ const hasDeletedByActorType = await knex.schema.hasColumn(TableName.Project, "deletedByActorType");+ const hasDeletedByActorId = await knex.schema.hasColumn(TableName.Project, "deletedByActorId");- if (hasDeleteAfter || hasSoftDeletedAt || hasDeletedByUserId || hasDeletedByIdentityId) {+ if (hasDeleteAfter || hasSoftDeletedAt || hasDeletedByActorType || hasDeletedByActorId) {await knex.schema.alterTable(TableName.Project, (t) => {- if (hasDeletedByUserId) t.dropColumn("deletedByUserId");- if (hasDeletedByIdentityId) t.dropColumn("deletedByIdentityId");+ if (hasDeletedByActorType) t.dropColumn("deletedByActorType");+ if (hasDeletedByActorId) t.dropColumn("deletedByActorId");if (hasDeleteAfter) t.dropColumn("deleteAfter");if (hasSoftDeletedAt) t.dropColumn("softDeletedAt");});diff --git a/backend/src/db/schemas/project-environments.ts b/backend/src/db/schemas/project-environments.tsindex 0f6f686d96..a3bea5a9bd 100644--- a/backend/src/db/schemas/project-environments.ts+++ b/backend/src/db/schemas/project-environments.ts@@ -17,8 +17,8 @@ export const ProjectEnvironmentsSchema = z.object({updatedAt: z.date(),deleteAfter: z.date().nullable().optional(),softDeletedAt: z.date().nullable().optional(),- deletedByUserId: z.string().uuid().nullable().optional(),- deletedByIdentityId: z.string().uuid().nullable().optional()+ deletedByActorType: z.string().nullable().optional(),+ deletedByActorId: z.string().uuid().nullable().optional()});export type TProjectEnvironments = z.infer<typeof ProjectEnvironmentsSchema>;diff --git a/backend/src/db/schemas/projects.ts b/backend/src/db/schemas/projects.tsindex 1f49da721a..851143ab5c 100644--- a/backend/src/db/schemas/projects.ts+++ b/backend/src/db/schemas/projects.ts@@ -35,8 +35,8 @@ export const ProjectsSchema = z.object({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()+ deletedByActorType: z.string().nullable().optional(),+ deletedByActorId: z.string().uuid().nullable().optional()});export type TProjects = z.infer<typeof ProjectsSchema>;diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.tsindex 11148dce49..439ed7c1b1 100644--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts@@ -37,6 +37,8 @@ const baseSecretRotationV2Query = ({.join(TableName.SecretFolder, `${TableName.SecretRotationV2}.folderId`, `${TableName.SecretFolder}.id`).join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`).whereNull(`${TableName.Environment}.deleteAfter`)+ .join(TableName.Project, `${TableName.Environment}.projectId`, `${TableName.Project}.id`)+ .whereNull(`${TableName.Project}.deleteAfter`).join(TableName.AppConnection, `${TableName.SecretRotationV2}.connectionId`, `${TableName.AppConnection}.id`).select(selectAllTableCols(TableName.SecretRotationV2)).select(diff --git a/backend/src/services/project-env/project-env-dal.ts b/backend/src/services/project-env/project-env-dal.tsindex 3b7cd0ce74..052b78e25e 100644--- a/backend/src/services/project-env/project-env-dal.ts+++ b/backend/src/services/project-env/project-env-dal.ts@@ -72,8 +72,8 @@ export const projectEnvDALFactory = (db: TDbClient) => {projectId: string,deleteAfter: Date,softDeletedAt: Date,- deletedByUserId: string | null,- deletedByIdentityId: string | null,+ deletedByActorType: string | null,+ deletedByActorId: string | null,position: number,tx?: Knex) => {@@ -81,7 +81,7 @@ export const projectEnvDALFactory = (db: TDbClient) => {const [doc] = await (tx || db)(TableName.Environment).where({ id, projectId }).whereNull("deleteAfter")- .update({ deleteAfter, softDeletedAt, deletedByUserId, deletedByIdentityId, position })+ .update({ deleteAfter, softDeletedAt, deletedByActorType, deletedByActorId, position }).returning("*");return doc as TProjectEnvironments | undefined;} catch (error) {@@ -120,8 +120,8 @@ export const projectEnvDALFactory = (db: TDbClient) => {.update({deleteAfter: null,softDeletedAt: null,- deletedByUserId: null,- deletedByIdentityId: null,+ deletedByActorType: null,+ deletedByActorId: null,position}).returning("*");diff --git a/backend/src/services/project-env/project-env-service.ts b/backend/src/services/project-env/project-env-service.tsindex 2ba756c276..57183e2f09 100644--- a/backend/src/services/project-env/project-env-service.ts+++ b/backend/src/services/project-env/project-env-service.ts@@ -10,7 +10,6 @@ import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/import { BadRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";-import { ActorType } from "../auth/auth-type";import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";import { TProjectEnvDALFactory } from "./project-env-dal";import { SOFT_DELETE_GRACE_MS } from "./project-env-queue";@@ -303,15 +302,13 @@ export const projectEnvServiceFactory = ({const softDeletedAt = new Date();const deleteAfter = new Date(softDeletedAt.getTime() + SOFT_DELETE_GRACE_MS);- const deletedByUserId = actor === ActorType.USER ? actorId : null;- const deletedByIdentityId = actor === ActorType.IDENTITY ? actorId : null;const doc = await projectEnvDAL.softDeleteById(id,projectId,deleteAfter,softDeletedAt,- deletedByUserId,- deletedByIdentityId,+ actor,+ actorId,maxPos,tx);diff --git a/backend/src/services/project-membership/project-membership-dal.ts b/backend/src/services/project-membership/project-membership-dal.tsindex 87c6f4c9ee..dda0edc18e 100644--- a/backend/src/services/project-membership/project-membership-dal.ts+++ b/backend/src/services/project-membership/project-membership-dal.ts@@ -209,6 +209,7 @@ export const projectMembershipDALFactory = (db: TDbClient) => {.join(TableName.Users, `${TableName.Membership}.actorUserId`, `${TableName.Users}.id`).where(`${TableName.Users}.id`, userId).where(`${TableName.Project}.orgId`, orgId)+ .whereNull(`${TableName.Project}.deleteAfter`).join(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`).leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`).select(@@ -305,6 +306,7 @@ export const projectMembershipDALFactory = (db: TDbClient) => {.join(TableName.Users, `${TableName.Membership}.actorUserId`, `${TableName.Users}.id`).whereIn(`${TableName.Users}.id`, userIds).where(`${TableName.Project}.orgId`, orgId)+ .whereNull(`${TableName.Project}.deleteAfter`).leftJoin<TUserEncryptionKeys>(TableName.UserEncryptionKey,`${TableName.UserEncryptionKey}.userId`,diff --git a/backend/src/services/project/project-dal.ts b/backend/src/services/project/project-dal.tsindex 9f790a8cb9..bc449a53b8 100644--- a/backend/src/services/project/project-dal.ts+++ b/backend/src/services/project/project-dal.ts@@ -105,8 +105,8 @@ export const projectDALFactory = (db: TDbClient) => {update: {deleteAfter: Date;softDeletedAt: Date;- deletedByUserId: string | null;- deletedByIdentityId: string | null;+ deletedByActorType: string | null;+ deletedByActorId: string | null;slug: string;},tx?: Knex@@ -694,8 +694,8 @@ export const projectDALFactory = (db: TDbClient) => {name: string;deleteAfter: Date;softDeletedAt: Date;- deletedByUserId: string | null;- deletedByIdentityId: string | null;+ deletedByActorType: string | null;+ deletedByActorId: string | null;deletedByUserEmail: string | null;deletedByUserUsername: string | null;deletedByUserFirstName: string | null;@@ -704,8 +704,20 @@ export const projectDALFactory = (db: TDbClient) => {};const rows = (await (tx || db.replicaNode())(TableName.Environment)- .leftJoin(TableName.Users, `${TableName.Environment}.deletedByUserId`, `${TableName.Users}.id`)- .leftJoin(TableName.Identity, `${TableName.Environment}.deletedByIdentityId`, `${TableName.Identity}.id`)+ .leftJoin(TableName.Users, function joinUser() {+ this.on(`${TableName.Environment}.deletedByActorId`, `${TableName.Users}.id`).andOnVal(+ `${TableName.Environment}.deletedByActorType`,+ "=",+ "user"+ );+ })+ .leftJoin(TableName.Identity, function joinIdentity() {+ this.on(`${TableName.Environment}.deletedByActorId`, `${TableName.Identity}.id`).andOnVal(+ `${TableName.Environment}.deletedByActorType`,+ "=",+ "identity"+ );+ }).where(`${TableName.Environment}.projectId`, projectId).whereNotNull(`${TableName.Environment}.deleteAfter`).whereNotNull(`${TableName.Environment}.softDeletedAt`)@@ -715,8 +727,8 @@ export const projectDALFactory = (db: TDbClient) => {`${TableName.Environment}.name`,`${TableName.Environment}.deleteAfter`,`${TableName.Environment}.softDeletedAt`,- `${TableName.Environment}.deletedByUserId`,- `${TableName.Environment}.deletedByIdentityId`,+ `${TableName.Environment}.deletedByActorType`,+ `${TableName.Environment}.deletedByActorId`,db.ref("email").withSchema(TableName.Users).as("deletedByUserEmail"),db.ref("username").withSchema(TableName.Users).as("deletedByUserUsername"),db.ref("firstName").withSchema(TableName.Users).as("deletedByUserFirstName"),@@ -738,19 +750,19 @@ export const projectDALFactory = (db: TDbClient) => {| { type: "identity"; id: string; name: string }| null = null;- if (row.deletedByUserId) {+ if (row.deletedByActorType === "user" && row.deletedByActorId) {deletedBy = {type: "user",- id: row.deletedByUserId,+ id: row.deletedByActorId,email: row.deletedByUserEmail,username: row.deletedByUserUsername,firstName: row.deletedByUserFirstName,lastName: row.deletedByUserLastName};- } else if (row.deletedByIdentityId) {+ } else if (row.deletedByActorType === "identity" && row.deletedByActorId) {deletedBy = {type: "identity",- id: row.deletedByIdentityId,+ id: row.deletedByActorId,name: row.deletedByIdentityName ?? ""};}diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.tsindex 20084938a1..90b36444ce 100644--- a/backend/src/services/project/project-service.ts+++ b/backend/src/services/project/project-service.ts@@ -830,8 +830,8 @@ export const projectServiceFactory = ({const softDeletedProject = await projectDAL.softDeleteById(project.id, {deleteAfter: now,softDeletedAt: now,- deletedByUserId: actor === ActorType.USER ? actorId : null,- deletedByIdentityId: actor === ActorType.IDENTITY ? actorId : null,+ deletedByActorType: actor,+ deletedByActorId: actorId,slug: `del-${alphaNumericNanoId(20)}`});diff --git a/backend/src/services/reminder/reminder-dal.ts b/backend/src/services/reminder/reminder-dal.tsindex 82c7464eb8..2ff067c5bd 100644--- a/backend/src/services/reminder/reminder-dal.ts+++ b/backend/src/services/reminder/reminder-dal.ts@@ -55,6 +55,7 @@ export const reminderDALFactory = (db: TDbClient) => {);}).leftJoin<TProjects>(TableName.Project, `${TableName.Environment}.projectId`, `${TableName.Project}.id`)+ .whereNull(`${TableName.Project}.deleteAfter`).leftJoin<TOrganizations>(TableName.Organization, `${TableName.Project}.orgId`, `${TableName.Organization}.id`).select(selectAllTableCols(TableName.Reminder)).select(db.ref("email").withSchema(TableName.Users))diff --git a/backend/src/services/secret-sync/secret-sync-dal.ts b/backend/src/services/secret-sync/secret-sync-dal.tsindex c28f2c5f2c..2771ff811f 100644--- a/backend/src/services/secret-sync/secret-sync-dal.ts+++ b/backend/src/services/secret-sync/secret-sync-dal.ts@@ -20,6 +20,8 @@ const baseSecretSyncQuery = ({ filter, db, tx }: { db: TDbClient; filter?: Secre);}).join(TableName.AppConnection, `${TableName.SecretSync}.connectionId`, `${TableName.AppConnection}.id`)+ .join(TableName.Project, `${TableName.SecretSync}.projectId`, `${TableName.Project}.id`)+ .whereNull(`${TableName.Project}.deleteAfter`).select(selectAllTableCols(TableName.SecretSync)).select(// environment