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: update soft-delete handling and foreign key constraints in database migrations
Victor Hugo dos Santos399a48e5af09
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex fd5a2f3bf2..d326d26598 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -233,8 +233,9 @@ Pattern:- **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`).+- **Only manually chunk-delete a table whose inbound FKs are all `CASCADE`/`SET NULL`.** A table with a `DEFERRABLE NO ACTION` inbound FK (e.g. `secret_rotation_v2_secret_mappings.secretId → secrets_v2`) must be left to the final `deleteById` cascade, which resolves the deferred check at COMMIT across the whole tree; deleting its parent outside that tree fails the check. Use `SET LOCAL statement_timeout` per batch so the bound can't leak to pooled connections. (Example: `secret_versions_v2` is chunked by `folderId` because all its inbound FKs are CASCADE/SET NULL and it has no `folderId`/`secretId` FK back to the project, so the project cascade would otherwise orphan it.)+- **A non-deferrable `NO ACTION`/`RESTRICT` inbound FK is unsafe under cascading deletes; make it `DEFERRABLE INITIALLY DEFERRED`.** It is checked at end of *statement*, so within one cascading `DELETE` a parent branch can be processed before a sibling branch deletes the referencer, raising "update or delete on X violates FK on Y". When a CASCADE child of the deleted root is itself referenced by `NO ACTION`/`RESTRICT` FKs, declare those FKs `.deferrable("deferred")` so the check runs at COMMIT after the cascade completes (a *direct* parent delete is still blocked while a referencer remains). Audit **all** inbound `NO ACTION`/`RESTRICT` FKs of such a parent, not just one.+- **Index every FK referencing column that participates in a cascade.** Postgres does **not** auto-index FK columns. A cascade fires a **per-row** RI trigger on each child, so an unindexed child means one seq-scan *per deleted parent row*, which blows past `statement_timeout` on a chunked delete. Before chunk-deleting a large table, enumerate **every** inbound FK, including helper-generated ones: `createJunctionTable` (`src/db/utils.ts`) creates CASCADE FK columns with **no index** on either side, so every junction table needs explicit FK indexes. 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 Handlingdiff --git a/backend/src/db/migrations/20260603120000_add-secret-approval-secret-version-index.ts b/backend/src/db/migrations/20260603120000_add-secret-approval-secret-version-index.tsnew file mode 100644index 0000000000..a2d5093d9c--- /dev/null+++ b/backend/src/db/migrations/20260603120000_add-secret-approval-secret-version-index.ts@@ -0,0 +1,40 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++const INDEX_NAME = "idx_secret_approval_requests_secrets_v2_secret_version";+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.SecretApprovalRequestSecretV2)) &&+ (await knex.schema.hasColumn(TableName.SecretApprovalRequestSecretV2, "secretVersion"))+ ) {+ await knex.raw(`+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${INDEX_NAME}"+ ON ${TableName.SecretApprovalRequestSecretV2} ("secretVersion")+ WHERE "secretVersion" 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 CONCURRENTLY IF EXISTS "${INDEX_NAME}"`);+}++const config = { transaction: false };+export { config };diff --git a/backend/src/db/migrations/20260603120100_defer-app-connection-fks.ts b/backend/src/db/migrations/20260603120100_defer-app-connection-fks.tsnew file mode 100644index 0000000000..abeaa4be30--- /dev/null+++ b/backend/src/db/migrations/20260603120100_defer-app-connection-fks.ts@@ -0,0 +1,56 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++type TFk = { table: TableName; column: string; originalOnDelete?: "RESTRICT" };++// Only the FKs that currently BLOCK the cascade (NO ACTION default, or RESTRICT). FKs already on+// CASCADE / SET NULL never block a parent delete and are intentionally left alone.+const BLOCKING_APP_CONNECTION_FKS: TFk[] = [+ { table: TableName.SecretSync, column: "connectionId" },+ { table: TableName.SecretRotationV2, column: "connectionId" },+ { table: TableName.ExternalCertificateAuthority, column: "appConnectionId" },+ { table: TableName.ExternalCertificateAuthority, column: "dnsAppConnectionId" },+ { table: TableName.SecretScanningDataSource, column: "connectionId" },+ { table: TableName.PkiSync, column: "connectionId" },+ { table: TableName.ExternalMigrationConfig, column: "connectionId" },+ { table: TableName.VaultExternalMigrationConfig, column: "connectionId" },+ { table: TableName.HoneyTokenConfig, column: "connectionId" },+ { table: TableName.PamProjectRecordingConfig, column: "connectionId", originalOnDelete: "RESTRICT" }+];++export async function up(knex: Knex): Promise<void> {+ // Drop + re-add takes a brief ACCESS EXCLUSIVE lock and revalidates each table.+ await knex.raw("SET LOCAL lock_timeout = '10s'");++ for (const { table, column } of BLOCKING_APP_CONNECTION_FKS) {+ // eslint-disable-next-line no-await-in-loop+ if (!(await knex.schema.hasTable(table)) || !(await knex.schema.hasColumn(table, column))) {+ // eslint-disable-next-line no-continue+ continue;+ }+ // eslint-disable-next-line no-await-in-loop+ await knex.schema.alterTable(table, (t) => {+ t.dropForeign([column]);+ t.foreign(column).references("id").inTable(TableName.AppConnection).deferrable("deferred");+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ await knex.raw("SET LOCAL lock_timeout = '10s'");++ for (const { table, column, originalOnDelete } of BLOCKING_APP_CONNECTION_FKS) {+ // eslint-disable-next-line no-await-in-loop+ if (!(await knex.schema.hasTable(table)) || !(await knex.schema.hasColumn(table, column))) {+ // eslint-disable-next-line no-continue+ continue;+ }+ // eslint-disable-next-line no-await-in-loop+ await knex.schema.alterTable(table, (t) => {+ t.dropForeign([column]);+ const fk = t.foreign(column).references("id").inTable(TableName.AppConnection);+ if (originalOnDelete === "RESTRICT") fk.onDelete("RESTRICT");+ });+ }+}diff --git a/backend/src/db/migrations/20260603120200_add-secret-version-v2-tag-junction-index.ts b/backend/src/db/migrations/20260603120200_add-secret-version-v2-tag-junction-index.tsnew file mode 100644index 0000000000..cb720749f8--- /dev/null+++ b/backend/src/db/migrations/20260603120200_add-secret-version-v2-tag-junction-index.ts@@ -0,0 +1,40 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++const INDEX_NAME = "idx_secret_version_v2_tag_junction_version_id";+const COLUMN = "secret_versions_v2Id";+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.SecretVersionV2Tag)) &&+ (await knex.schema.hasColumn(TableName.SecretVersionV2Tag, COLUMN))+ ) {+ await knex.raw(`+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${INDEX_NAME}"+ ON ${TableName.SecretVersionV2Tag} ("${COLUMN}")+ `);+ }+ } 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 CONCURRENTLY IF EXISTS "${INDEX_NAME}"`);+}++const config = { transaction: false };+export { config };diff --git a/backend/src/db/migrations/20260603120300_add-secret-v2-tag-junction-index.ts b/backend/src/db/migrations/20260603120300_add-secret-v2-tag-junction-index.tsnew file mode 100644index 0000000000..bc0b1d3575--- /dev/null+++ b/backend/src/db/migrations/20260603120300_add-secret-v2-tag-junction-index.ts@@ -0,0 +1,40 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++const INDEX_NAME = "idx_secret_v2_tag_junction_secret_id";+const COLUMN = "secrets_v2Id";+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.SecretV2JnTag)) &&+ (await knex.schema.hasColumn(TableName.SecretV2JnTag, COLUMN))+ ) {+ await knex.raw(`+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${INDEX_NAME}"+ ON ${TableName.SecretV2JnTag} ("${COLUMN}")+ `);+ }+ } 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 CONCURRENTLY IF EXISTS "${INDEX_NAME}"`);+}++const config = { transaction: false };+export { config };