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
block project deletion on cross-project grants, checked under the delete lock
DimitrisStaratzisdb00ee99a177
diff --git a/backend/e2e-test/routes/v1/project.spec.ts b/backend/e2e-test/routes/v1/project.spec.tsindex 6081fe3045..3186d067f0 100644--- a/backend/e2e-test/routes/v1/project.spec.ts+++ b/backend/e2e-test/routes/v1/project.spec.ts@@ -186,44 +186,32 @@ describe("Project deletion (soft-delete + async cleanup)", async () => {expect((await permanentlyDeleteProject(project.id)).statusCode).toBe(200);});- test("refuses to delete a project that another project imports secrets from", async () => {+ test("refuses to delete a project that shares secrets with another project", async () => {const orgId = seedData1.organization.id;const headers = { authorization: `Bearer ${jwtAuthToken}` };const restoreLicense = overrideLicenseFeatures({ crossProjectSecretSharing: true });const org = await testDb(TableName.Organization).where({ id: orgId }).first();await testDb(TableName.Organization).where({ id: orgId }).update({ allowCrossProjectSecretSharing: true });try {- const source = await createProject("e2e-import-source");- const importer = await createProject("e2e-import-target");+ const source = await createProject("e2e-share-source");+ const target = await createProject("e2e-share-target");const grantRes = await testServer.inject({method: "POST",url: "/api/v1/project-folder-grants",headers,- body: { sourceProjectId: source.id, environment: "dev", secretPath: "/", targetProjectId: importer.id }+ body: { sourceProjectId: source.id, environment: "dev", secretPath: "/", targetProjectId: target.id }});expect(grantRes.statusCode).toBe(200);- const importRes = await testServer.inject({- method: "POST",- url: "/api/v2/secret-imports",- headers,- body: {- projectId: importer.id,- environment: "dev",- path: "/",- import: { sourceProjectId: source.id, environment: "dev", path: "/" }- }- });- expect(importRes.statusCode).toBe(200);const blockedRes = await deleteProject(source.id);expect(blockedRes.statusCode).toBe(400);- expect(JSON.parse(blockedRes.payload).message).toContain(importer.name);+ expect(JSON.parse(blockedRes.payload).message).toContain(target.name);- // with sharing off the import is inactive (and hidden), so it no longer blocks the delete+ // with sharing off the grant is ignored, so it no longer blocks the deleteawait testDb(TableName.Organization).where({ id: orgId }).update({ allowCrossProjectSecretSharing: false });expect((await deleteProject(source.id, true)).statusCode).toBe(200);- await deleteProject(importer.id, true);+ await deleteProject(target.id, true);} finally {await testDb(TableName.Organization).where({ id: orgId })diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex ac8574ac4c..dbe50e83ca 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2560,7 +2560,8 @@ export const registerRoutes = async (projectAccessRequestDAL,usageMeteringService,dynamicSecretLeaseDAL,- dynamicSecretQueueService+ dynamicSecretQueueService,+ projectFolderGrantDAL});const projectEnvQueue = projectEnvQueueFactory({diff --git a/backend/src/services/project/project-dal.ts b/backend/src/services/project/project-dal.tsindex de6d622d95..a1c1352e24 100644--- a/backend/src/services/project/project-dal.ts+++ b/backend/src/services/project/project-dal.ts@@ -1087,29 +1087,6 @@ export const projectDALFactory = (db: TDbClient) => {}};- // Other live projects with a secret import pointing at one of this project's live environments.- const findProjectsImportingFrom = async (projectId: string, tx?: Knex) => {- try {- const sourceEnvIds = db- .replicaNode()(TableName.Environment)- .where({ projectId })- .whereNull("deleteAfter")- .select("id");- const docs = await (tx || db.replicaNode())(TableName.SecretImport)- .join(TableName.SecretFolder, `${TableName.SecretImport}.folderId`, `${TableName.SecretFolder}.id`)- .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)- .join(TableName.Project, `${TableName.Environment}.projectId`, `${TableName.Project}.id`)- .whereIn(`${TableName.SecretImport}.importEnv`, sourceEnvIds)- .whereNot(`${TableName.Project}.id`, projectId)- .whereNull(`${TableName.Environment}.deleteAfter`)- .whereNull(`${TableName.Project}.deleteAfter`)- .distinct(db.ref("id").withSchema(TableName.Project), db.ref("name").withSchema(TableName.Project));- return docs as { id: string; name: string }[];- } catch (error) {- throw new DatabaseError({ error, name: "Find projects importing from project" });- }- };-const countOfBillableOrgProjects = async (orgId: string | null, tx?: Knex) => {try {const subOrgProjects = db.replicaNode()(TableName.Organization).where({ rootOrgId: orgId }).select("id");@@ -1174,7 +1151,6 @@ export const projectDALFactory = (db: TDbClient) => {findProjectByEnvId,findProjectDeletedEnvironments,findDeletedProjects,- findProjectsImportingFrom,countOfBillableOrgProjects};};diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.tsindex ac99caa5d2..a378647a25 100644--- a/backend/src/services/project/project-service.ts+++ b/backend/src/services/project/project-service.ts@@ -92,6 +92,7 @@ import { TPkiAlertDALFactory } from "../pki-alert/pki-alert-dal";import { TPkiCollectionDALFactory } from "../pki-collection/pki-collection-dal";import { TProjectEnvDALFactory } from "../project-env/project-env-dal";import { SOFT_DELETE_GRACE_MS } from "../project-env/project-env-queue";+import { TProjectFolderGrantDALFactory } from "../project-folder-grant/project-folder-grant-dal";import { TProjectMembershipDALFactory } from "../project-membership/project-membership-dal";import { getPredefinedRoles } from "../project-role/project-role-fns";import { TRoleDALFactory } from "../role/role-dal";@@ -215,6 +216,7 @@ type TProjectServiceFactoryDep = {TDynamicSecretLeaseQueueServiceFactory,"setLeaseRevocation" | "unsetRestoredLeaseRevocation">;+ projectFolderGrantDAL: Pick<TProjectFolderGrantDALFactory, "listBySourceProject">;};export type TProjectServiceFactory = ReturnType<typeof projectServiceFactory>;@@ -267,7 +269,8 @@ export const projectServiceFactory = ({projectAccessRequestDAL,usageMeteringService,dynamicSecretLeaseDAL,- dynamicSecretQueueService+ dynamicSecretQueueService,+ projectFolderGrantDAL}: TProjectServiceFactoryDep) => {// The (orgId, slug) unique index already refuses a taken slug; this only names the cause when the holder is// a project pending deletion.@@ -880,23 +883,7 @@ export const projectServiceFactory = ({}}- // Deleting a project that others import from would silently drop those secrets from their reads and- // syncs, and the deleter may not be a member of those projects, so the imports must be removed first.- // With cross-project sharing off, those imports are already ignored by reads and hidden from the list.const { allowCrossProjectSecretSharing } = (await orgDAL.findOne({ id: project.orgId })) ?? {};- const importingProjects = allowCrossProjectSecretSharing- ? await projectDAL.findProjectsImportingFrom(project.id)- : [];- if (importingProjects.length) {- const preview = importingProjects- .slice(0, 5)- .map(({ name }) => `'${name}'`)- .join(", ");- const remaining = importingProjects.length - 5;- throw new BadRequestError({- message: `Project '${project.name}' can't be deleted while other projects import secrets from it: ${remaining > 0 ? `${preview}, and ${remaining} more` : preview}. Remove those secret imports first, then retry.`- });- }let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | undefined;try {@@ -917,12 +904,36 @@ export const projectServiceFactory = ({// unchanged; otherwise the slug is freed so a same-named project can be recreated right away.const now = new Date();const hasGracePeriod = !hardDelete && project.type === ProjectType.SecretManager;- const softDeletedProject = await projectDAL.softDeleteById(project.id, {- deleteAfter: hasGracePeriod ? new Date(now.getTime() + SOFT_DELETE_GRACE_MS) : now,- softDeletedAt: now,- deletedByActorType: actor,- deletedByActorId: actorId,- slug: hasGracePeriod ? project.slug : `del-${alphaNumericNanoId(20)}`+ const softDeletedProject = await projectDAL.transaction(async (tx) => {+ // Deleting a project that shares folders with other projects would silently drop those secrets from+ // their imports, references and syncs, so that access must be revoked first. Read under the lock from+ // the primary so a grant made just before the delete is seen. With sharing off, grants are ignored.+ const grants = allowCrossProjectSecretSharing+ ? await projectFolderGrantDAL.listBySourceProject(project.id, tx)+ : [];+ const sharedWith = [...new Set(grants.map(({ targetProjectName }) => targetProjectName))];+ if (sharedWith.length) {+ const preview = sharedWith+ .slice(0, 5)+ .map((name) => `'${name}'`)+ .join(", ");+ const remaining = sharedWith.length - 5;+ throw new BadRequestError({+ message: `Project '${project.name}' can't be deleted while it shares secrets with other projects: ${remaining > 0 ? `${preview}, and ${remaining} more` : preview}. Revoke their access in Project Settings → Cross-Project Secret Sharing first, then retry.`+ });+ }++ return projectDAL.softDeleteById(+ project.id,+ {+ deleteAfter: hasGracePeriod ? new Date(now.getTime() + SOFT_DELETE_GRACE_MS) : now,+ softDeletedAt: now,+ deletedByActorType: actor,+ deletedByActorId: actorId,+ slug: hasGracePeriod ? project.slug : `del-${alphaNumericNanoId(20)}`+ },+ tx+ );});if (!softDeletedProject) {