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
feat: add a check on membership removal to check if the user can be removed from a project
adilson8c8bedc35167
diff --git a/backend/e2e-test/routes/v1/secret-approval-global-guards.spec.ts b/backend/e2e-test/routes/v1/secret-approval-global-guards.spec.tsnew file mode 100644index 0000000000..413727b602--- /dev/null+++ b/backend/e2e-test/routes/v1/secret-approval-global-guards.spec.ts@@ -0,0 +1,282 @@+import crypto from "node:crypto";++import { createFolder, deleteFolder } from "e2e-test/testUtils/folders";+import { seedLegacySecretApprovalPolicy } from "e2e-test/testUtils/secret-approval-policies";+import { Knex } from "knex";++import { AccessScope, OrgMembershipRole, ProjectMembershipRole, TableName } from "@app/db/schemas";+import { seedData1 } from "@app/db/seed-data";+import { ApproverType } from "@app/ee/services/access-approval-policy/access-approval-policy-types";+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";++const getDb = () => (globalThis as unknown as { testDb: Knex }).testDb;++const projectId = seedData1.projectV3.id;+const orgId = seedData1.organization.id;+const envSlug = seedData1.environment.slug;+const authHeaders = () => ({ authorization: `Bearer ${jwtAuthToken}` });++const insertMembership = async (+ membership: { scope: AccessScope; scopeProjectId?: string; actorUserId?: string; actorGroupId?: string },+ role: string+) => {+ const [row] = await getDb()(TableName.Membership)+ .insert({ scopeOrgId: orgId, ...membership })+ .returning("id");+ const membershipId = (row as { id: string }).id;+ await getDb()(TableName.MembershipRole).insert({ membershipId, role });+ return membershipId;+};++const createProjectUser = async (label: string) => {+ const username = `${label}-${crypto.randomUUID()}@localhost.local`;+ const [user] = await getDb()(TableName.Users)+ .insert({ username, email: username, firstName: label, isAccepted: true, isGhost: false })+ .returning("id");+ const userId = (user as { id: string }).id;+ await insertMembership({ scope: AccessScope.Organization, actorUserId: userId }, OrgMembershipRole.Member);+ await insertMembership(+ { scope: AccessScope.Project, scopeProjectId: projectId, actorUserId: userId },+ ProjectMembershipRole.Member+ );+ return { userId, username };+};++const createProjectGroup = async (label: string) => {+ const slug = `${label}-${crypto.randomUUID().slice(0, 8)}`;+ const [group] = await getDb()(TableName.Groups).insert({ orgId, name: slug, slug }).returning("id");+ const groupId = (group as { id: string }).id;+ await insertMembership({ scope: AccessScope.Organization, actorGroupId: groupId }, OrgMembershipRole.NoAccess);+ await insertMembership(+ { scope: AccessScope.Project, scopeProjectId: projectId, actorGroupId: groupId },+ ProjectMembershipRole.Member+ );+ return groupId;+};++const createGlobalPolicy = async (name: string, secretPath: string, approver: { type: ApproverType; id: string }) => {+ const res = await testServer.inject({+ method: "POST",+ url: "/api/v2/secret-approvals",+ headers: authHeaders(),+ body: { projectId, environment: envSlug, secretPath, approvers: [approver], approvals: 1, name }+ });+ expect(res.statusCode).toBe(200);+ const policyId = (res.json() as { approval: { id: string } }).approval.id;+ expect(await getDb()(TableName.ApprovalPolicies).where({ id: policyId }).first()).toBeDefined();+ return policyId;+};++const deleteGlobalPolicy = async (policyId: string) => {+ const res = await testServer.inject({+ method: "DELETE",+ url: `/api/v2/secret-approvals/${policyId}`,+ headers: authHeaders()+ });+ expect(res.statusCode).toBe(200);+};++const removeProjectUser = (username: string) =>+ testServer.inject({+ method: "DELETE",+ url: `/api/v1/projects/${projectId}/memberships`,+ headers: authHeaders(),+ body: { usernames: [username] }+ });++const removeProjectGroup = (groupId: string) =>+ testServer.inject({+ method: "DELETE",+ url: `/api/v1/projects/${projectId}/memberships/groups/${groupId}`,+ headers: authHeaders()+ });++const deleteFolderRequest = (folderId: string, secretPath: string) =>+ testServer.inject({+ method: "DELETE",+ url: `/api/v1/folders/${folderId}`,+ headers: authHeaders(),+ body: { workspaceId: projectId, environment: envSlug, path: secretPath, forceDelete: true }+ });++const seedOpenSecretChangeRequest = async (folderId: string) => {+ const [request] = await getDb()(TableName.ApprovalRequests)+ .insert({+ projectId,+ organizationId: orgId,+ policyId: null,+ requesterId: seedData1.id,+ requesterName: "test",+ requesterEmail: seedData1.email,+ type: ApprovalPolicyType.SecretChange,+ status: "open",+ currentStep: 0,+ requestData: JSON.stringify({})+ })+ .returning("id");+ const approvalRequestId = (request as { id: string }).id;+ await getDb()(TableName.SecretChangeRequests).insert({+ approvalRequestId,+ folderId,+ slug: `guard-${crypto.randomUUID().slice(0, 8)}`+ });+ return approvalRequestId;+};++const seedOpenLegacyRequest = async (folderId: string, policyId: string) => {+ const [request] = await getDb()(TableName.SecretApprovalRequest)+ .insert({+ policyId,+ folderId,+ slug: `guard-${crypto.randomUUID().slice(0, 8)}`,+ status: "open",+ committerUserId: seedData1.id+ })+ .returning("id");+ return (request as { id: string }).id;+};++const createFolderTree = async () => {+ const parentName = `folder-guard-${crypto.randomUUID().slice(0, 8)}`;+ const parent = await createFolder({+ workspaceId: projectId,+ environmentSlug: envSlug,+ secretPath: "/",+ name: parentName,+ authToken: jwtAuthToken+ });+ const child = await createFolder({+ workspaceId: projectId,+ environmentSlug: envSlug,+ secretPath: `/${parentName}`,+ name: "child",+ authToken: jwtAuthToken+ });+ return { parentName, parent, child };+};++const openRequestMessage = (folderPath: string) =>+ `You cannot delete the selected folder because it has open change requests at folder path "${folderPath}". Merge or close the change requests and try again.`;++describe("Global approval system guards outside the approval routes", () => {+ const userIds: string[] = [];+ const groupIds: string[] = [];+ const policyIds: string[] = [];+ const requestIds: string[] = [];+ const legacyPolicyIds: string[] = [];+ const legacyRequestIds: string[] = [];++ afterAll(async () => {+ const db = getDb();+ await db(TableName.ApprovalRequests).whereIn("id", requestIds).del();+ await db(TableName.ApprovalPolicies).whereIn("id", policyIds).del();+ await db(TableName.SecretApprovalRequest).whereIn("id", legacyRequestIds).del();+ await db(TableName.SecretApprovalPolicy).whereIn("id", legacyPolicyIds).del();+ await db(TableName.Membership).whereIn("actorUserId", userIds).del();+ await db(TableName.Membership).whereIn("actorGroupId", groupIds).del();+ await db(TableName.Groups).whereIn("id", groupIds).del();+ await db(TableName.Users).whereIn("id", userIds).del();+ });++ test("a user who approves a global policy cannot be removed from the project until the policy is gone", async () => {+ const { userId, username } = await createProjectUser("global-approver");+ userIds.push(userId);+ const policyId = await createGlobalPolicy("global-user-guard", "/global-user-guard", {+ type: ApproverType.User,+ id: userId+ });+ policyIds.push(policyId);++ const blocked = await removeProjectUser(username);+ expect(blocked.statusCode).toBe(400);+ expect(blocked.json().message).toBe(+ "Cannot remove user from project: user is an approver in secret approval policy: global-user-guard"+ );++ await deleteGlobalPolicy(policyId);++ const removed = await removeProjectUser(username);+ expect(removed.statusCode).toBe(200);+ });++ test("a group that approves a global policy cannot be removed from the project until the policy is gone", async () => {+ const groupId = await createProjectGroup("global-approver-group");+ groupIds.push(groupId);+ const policyId = await createGlobalPolicy("global-group-guard", "/global-group-guard", {+ type: ApproverType.Group,+ id: groupId+ });+ policyIds.push(policyId);++ const blocked = await removeProjectGroup(groupId);+ expect(blocked.statusCode).toBe(400);+ expect(blocked.json().message).toBe(+ "Cannot remove group from project: group is an approver in secret approval policy: global-group-guard"+ );++ await deleteGlobalPolicy(policyId);++ const removed = await removeProjectGroup(groupId);+ expect(removed.statusCode).toBe(200);+ });++ test("a folder with an open global change request cannot be deleted, directly or through its parent", async () => {+ const { parentName, parent, child } = await createFolderTree();+ const requestId = await seedOpenSecretChangeRequest(child.id);+ requestIds.push(requestId);++ const expectedMessage = openRequestMessage(`/${parentName}/child`);++ const childBlocked = await deleteFolderRequest(child.id, `/${parentName}`);+ expect(childBlocked.statusCode).toBe(400);+ expect(childBlocked.json().message).toBe(expectedMessage);++ const parentBlocked = await deleteFolderRequest(parent.id, "/");+ expect(parentBlocked.statusCode).toBe(400);+ expect(parentBlocked.json().message).toBe(expectedMessage);++ expect(await getDb()(TableName.SecretFolder).where({ id: child.id }).first()).toBeDefined();++ await getDb()(TableName.ApprovalRequests).where({ id: requestId }).update({ status: "close" });++ await deleteFolder({+ workspaceId: projectId,+ environmentSlug: envSlug,+ secretPath: "/",+ id: parent.id,+ authToken: jwtAuthToken,+ forceDelete: true+ });+ expect(await getDb()(TableName.SecretFolder).where({ id: child.id }).first()).toBeUndefined();+ });++ test("a folder with an open legacy change request cannot be deleted until the request is closed", async () => {+ const { parentName, parent, child } = await createFolderTree();+ const legacyPolicy = await seedLegacySecretApprovalPolicy(getDb(), {+ projectId,+ environment: envSlug,+ secretPath: `/${parentName}/child`,+ name: "legacy-folder-guard",+ approverUserId: seedData1.id+ });+ legacyPolicyIds.push(legacyPolicy.id);+ const legacyRequestId = await seedOpenLegacyRequest(child.id, legacyPolicy.id);+ legacyRequestIds.push(legacyRequestId);++ const blocked = await deleteFolderRequest(parent.id, "/");+ expect(blocked.statusCode).toBe(400);+ expect(blocked.json().message).toBe(openRequestMessage(`/${parentName}/child`));++ await getDb()(TableName.SecretApprovalRequest).where({ id: legacyRequestId }).update({ status: "close" });++ await deleteFolder({+ workspaceId: projectId,+ environmentSlug: envSlug,+ secretPath: "/",+ id: parent.id,+ authToken: jwtAuthToken,+ forceDelete: true+ });+ expect(await getDb()(TableName.SecretFolder).where({ id: child.id }).first()).toBeUndefined();+ });+});diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-creation-fns.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-creation-fns.tsindex 3b4087a689..4107bd47a9 100644--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-creation-fns.ts+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-creation-fns.ts@@ -85,7 +85,7 @@ export const secretApprovalRequestCreationFnsFactory = ({const createSecretApprovalRequest = async (dto: TCreateSecretApprovalRequestDTO, tx?: Knex) => {if (await $isSecretChangePolicy(dto.policy.id, tx)) {throw new BadRequestError({- message: `Secret approval policy with ID '${dto.policy.id}' is on the new approval system, which does not support projects that have not been upgraded to the latest secrets version.`+ message: `Secret approval policy with ID '${dto.policy.id}' is on the global approval system, which does not support projects that have not been upgraded to the latest secrets version.`});}diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.test.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.test.tsindex 402dc1d7bc..21a4179268 100644--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.test.ts+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.test.ts@@ -82,7 +82,7 @@ describe("generateSecretApprovalRequest", () => {})).rejects.toThrow(new BadRequestError({- message: `Secret approval policy with ID '${POLICY_ID}' is on the new approval system, which does not support projects that have not been upgraded to the latest secrets version.`+ message: `Secret approval policy with ID '${POLICY_ID}' is on the global approval system, which does not support projects that have not been upgraded to the latest secrets version.`}));diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.tsindex e7a57fd1be..645c92fa66 100644--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts@@ -161,6 +161,7 @@ type TSecretApprovalRequestServiceFactoryDep = {secretChangeRequestBridgeService: Pick<TSecretChangeRequestBridgeServiceFactory,| "findSecretChangeRequest"+ | "findFolderIdsWithOpenSecretChangeRequests"| "generateSecretChangeRequest"| "mergeSecretChangeRequest"| "reviewSecretChangeRequest"@@ -1286,7 +1287,7 @@ export const secretApprovalRequestServiceFactory = ({if (await secretChangePolicyBridgeService.findSecretChangePolicy(policy.id)) {throw new BadRequestError({- message: `Secret approval policy with ID '${policy.id}' is on the new approval system, which does not support projects that have not been upgraded to the latest secrets version.`+ message: `Secret approval policy with ID '${policy.id}' is on the global approval system, which does not support projects that have not been upgraded to the latest secrets version.`});}@@ -1808,6 +1809,21 @@ export const secretApprovalRequestServiceFactory = ({return secretApprovalRequest;};+ const findFolderIdsWithOpenRequests = async (folderIds: string[], tx?: Knex) => {+ if (!folderIds.length) return [];++ const legacyRequests = await secretApprovalRequestDAL.find(+ { $in: { folderId: folderIds }, status: RequestState.Open },+ { tx }+ );+ const secretChangeFolderIds = await secretChangeRequestBridgeService.findFolderIdsWithOpenSecretChangeRequests(+ folderIds,+ tx+ );++ return [...new Set([...legacyRequests.map((request) => request.folderId), ...secretChangeFolderIds])];+ };+return {generateSecretApprovalRequest,generateSecretApprovalRequestV2Bridge,@@ -1817,6 +1833,7 @@ export const secretApprovalRequestServiceFactory = ({updateApprovalStatus,getSecretApprovals,getSecretApprovalDetails,- requestCount+ requestCount,+ findFolderIdsWithOpenRequests};};diff --git a/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-service.ts b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-service.tsindex 52ee093055..28050ded87 100644--- a/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-service.ts+++ b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-service.ts@@ -140,7 +140,7 @@ export const secretChangePolicyBridgeServiceFactory = ({if (project.version !== ProjectVersion.V3) {throw new BadRequestError({message:- "Secret approval policies on the new approval system are only supported on projects that have been upgraded to the latest secrets version. Upgrade the project before creating one."+ "Secret approval policies on the global approval system are only supported on projects that have been upgraded to the latest secrets version. Upgrade the project before creating one."});}diff --git a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.ts b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.tsindex dfdd6aa74e..00b6a36e9d 100644--- a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.ts+++ b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.ts@@ -95,6 +95,7 @@ import { TSecretChangeRequestDALFactory } from "./secret-change-request-dal";type TSecretChangeRequestBridgeServiceFactoryDep = {approvalRequestDAL: Pick<TApprovalRequestDALFactory,+ | "find"| "findById"| "findByIdForUpdate"| "findStepsByRequestId"@@ -109,7 +110,7 @@ type TSecretChangeRequestBridgeServiceFactoryDep = {approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "findStepsByPolicyId" | "findBypassersByPolicyIds">;secretChangeRequestDAL: Pick<TSecretChangeRequestDALFactory,- "create" | "findOne" | "updateById" | "findByProjectId" | "countByProjectId"+ "create" | "find" | "findOne" | "updateById" | "findByProjectId" | "countByProjectId">;secretApprovalRequestSecretDAL: Pick<TSecretApprovalRequestSecretDALFactory,@@ -249,6 +250,23 @@ export const secretChangeRequestBridgeServiceFactory = ({const findSecretChangeRequest = (requestId: string, tx?: Knex) => approvalRequestDAL.findById(requestId, tx);+ const findFolderIdsWithOpenSecretChangeRequests = async (folderIds: string[], tx?: Knex) => {+ if (!folderIds.length) return [];++ const secretChangeRequests = await secretChangeRequestDAL.find({ $in: { folderId: folderIds } }, { tx });+ if (!secretChangeRequests.length) return [];++ const openRequests = await approvalRequestDAL.find(+ { $in: { id: secretChangeRequests.map((request) => request.approvalRequestId) }, status: RequestState.Open },+ { tx }+ );+ const openRequestIds = new Set(openRequests.map((request) => request.id));++ return secretChangeRequests+ .filter((request) => openRequestIds.has(request.approvalRequestId))+ .map((request) => request.folderId);+ };+const $findSecretChangeRequestOrThrow = async (requestId: string, tx?: Knex) => {const approvalRequest = await approvalRequestDAL.findById(requestId, tx);if (!approvalRequest || approvalRequest.type !== ApprovalPolicyType.SecretChange) {@@ -1072,6 +1090,7 @@ export const secretChangeRequestBridgeServiceFactory = ({return {findSecretChangeRequest,+ findFolderIdsWithOpenSecretChangeRequests,generateSecretChangeRequest,createSecretChangeRequest,createSecretChangeRequestSideEffects,diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 3e3a8885c9..a667caaede 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -998,6 +998,7 @@ export const registerRoutes = async (accessApprovalPolicyApproverDAL,secretApprovalPolicyDAL,secretApprovalPolicyApproverDAL: sapApproverDAL,+ approvalPolicyDAL,roleDAL,permissionService,orgDAL,@@ -1745,6 +1746,7 @@ export const registerRoutes = async (accessApprovalPolicyDAL,secretApprovalPolicyApproverDAL: sapApproverDAL,secretApprovalPolicyDAL,+ approvalPolicyDAL,membershipRoleDAL,applicationMembershipCleanupService,usageMeteringService,@@ -2522,6 +2524,7 @@ export const registerRoutes = async (secretVersionTagDAL: secretVersionTagV2BridgeDAL,resourceMetadataDAL,secretApprovalRequestCreationFns,+ secretApprovalRequestService,secretQueueService,secretSyncQueue,dynamicSecretDAL,diff --git a/backend/src/services/approval-policy/approval-policy-dal.ts b/backend/src/services/approval-policy/approval-policy-dal.tsindex b4bce37a2c..f3693f51b9 100644--- a/backend/src/services/approval-policy/approval-policy-dal.ts+++ b/backend/src/services/approval-policy/approval-policy-dal.ts@@ -217,15 +217,16 @@ export const approvalPolicyDALFactory = (db: TDbClient) => {};/**- * Return the list of policies (with name + id) that include the given subject as an approver- * on any step. The subject is identified by `userId` OR `groupId` (not both). Used to block- * removing a member from an application while they're still wired up as a reviewer.+ * Return the list of policies (with name + id) that include any of the given subjects as an approver+ * on any step. The subjects are identified by `userIds` OR `groupId` (not both). Used to block+ * removing members while they're still wired up as reviewers.*/const findPoliciesWhereSubjectIsApprover = async (args: {projectId: string;+ type?: string;scopeType?: string;scopeId?: string;- userId?: string;+ userIds?: string[];groupId?: string;}) => {try {@@ -244,6 +245,10 @@ export const approvalPolicyDALFactory = (db: TDbClient) => {`${TableName.ApprovalPolicySteps}.id`);+ if (typeof args.type === "string") {+ void baseQuery.where(`${TableName.ApprovalPolicies}.type`, args.type);+ }+if (typeof args.scopeType === "string") {void baseQuery.where(`${TableName.ApprovalPolicies}.scopeType`, args.scopeType);if (typeof args.scopeId === "string") {@@ -251,8 +256,8 @@ export const approvalPolicyDALFactory = (db: TDbClient) => {}}- if (args.userId) {- void baseQuery.where(`${TableName.ApprovalPolicyStepApprovers}.userId`, args.userId);+ if (args.userIds?.length) {+ void baseQuery.whereIn(`${TableName.ApprovalPolicyStepApprovers}.userId`, args.userIds);} else if (args.groupId) {void baseQuery.where(`${TableName.ApprovalPolicyStepApprovers}.groupId`, args.groupId);} else {diff --git a/backend/src/services/membership-group/membership-group-service.ts b/backend/src/services/membership-group/membership-group-service.tsindex aa4f9e7aa7..f4358a6ce9 100644--- a/backend/src/services/membership-group/membership-group-service.ts+++ b/backend/src/services/membership-group/membership-group-service.ts@@ -20,11 +20,13 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors";import { groupBy } from "@app/lib/fn";import { ms } from "@app/lib/ms";import { SearchResourceOperators } from "@app/lib/search-resource/search";+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";import { TAlertChannelRecipientDALFactory } from "../alert/alert-channel-recipient-dal";+import { TApprovalPolicyDALFactory } from "../approval-policy/approval-policy-dal";import { TApplicationMembershipCleanupServiceFactory } from "../membership/application-membership-cleanup-service";import { assertProductWillRetainAdmin, assertSecretsTemporaryAccessAllowed } from "../membership/membership-fns";import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";@@ -50,6 +52,7 @@ type TMembershipGroupServiceFactoryDep = {accessApprovalPolicyApproverDAL: Pick<TAccessApprovalPolicyApproverDALFactory, "find">;secretApprovalPolicyDAL: Pick<TSecretApprovalPolicyDALFactory, "find">;secretApprovalPolicyApproverDAL: Pick<TSecretApprovalPolicyApproverDALFactory, "find">;+ approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "findPoliciesWhereSubjectIsApprover">;roleDAL: Pick<TRoleDALFactory, "find">;permissionService: TPermissionServiceFactory;orgDAL: TOrgDALFactory;@@ -76,6 +79,7 @@ export const membershipGroupServiceFactory = ({accessApprovalPolicyApproverDAL,secretApprovalPolicyDAL,secretApprovalPolicyApproverDAL,+ approvalPolicyDAL,membershipRoleDAL,orgDAL,permissionService,@@ -432,6 +436,20 @@ export const membershipGroupServiceFactory = ({}}+ if (existingMembership.scopeProjectId) {+ const secretChangePolicies = await approvalPolicyDAL.findPoliciesWhereSubjectIsApprover({+ projectId: existingMembership.scopeProjectId,+ type: ApprovalPolicyType.SecretChange,+ groupId: dto.selector.groupId+ });+ if (secretChangePolicies.length > 0) {+ const policyNames = secretChangePolicies.map((p) => p.name).join(", ");+ throw new BadRequestError({+ message: `Cannot remove group from project: group is an approver in secret approval ${secretChangePolicies.length > 1 ? "policies" : "policy"}: ${policyNames}`+ });+ }+ }+const performDelete = async (tx: Knex) => {if (scopeData.scope === AccessScope.Project && existingMembership.scopeProjectId) {await assertProductWillRetainAdmin({diff --git a/backend/src/services/project-membership/project-membership-service.ts b/backend/src/services/project-membership/project-membership-service.tsindex 464833db67..4973be5d4e 100644--- a/backend/src/services/project-membership/project-membership-service.ts+++ b/backend/src/services/project-membership/project-membership-service.ts@@ -12,6 +12,7 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors";import { groupBy, unique } from "@app/lib/fn";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";@@ -22,6 +23,7 @@ import { TSecretApprovalPolicyApproverDALFactory } from "../../ee/services/secreimport { TSecretApprovalPolicyDALFactory } from "../../ee/services/secret-approval-policy/secret-approval-policy-dal";import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";import { TAlertChannelRecipientDALFactory } from "../alert/alert-channel-recipient-dal";+import { TApprovalPolicyDALFactory } from "../approval-policy/approval-policy-dal";import { ActorType } from "../auth/auth-type";import { TGroupProjectDALFactory } from "../group-project/group-project-dal";import { TApplicationMembershipCleanupServiceFactory } from "../membership/application-membership-cleanup-service";@@ -66,6 +68,7 @@ type TProjectMembershipServiceFactoryDep = {accessApprovalPolicyDAL: Pick<TAccessApprovalPolicyDALFactory, "find">;secretApprovalPolicyApproverDAL: Pick<TSecretApprovalPolicyApproverDALFactory, "find">;secretApprovalPolicyDAL: Pick<TSecretApprovalPolicyDALFactory, "find">;+ approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "findPoliciesWhereSubjectIsApprover">;secretReminderRecipientsDAL: Pick<TSecretReminderRecipientsDALFactory, "delete">;groupProjectDAL: TGroupProjectDALFactory;notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;@@ -94,6 +97,7 @@ export const projectMembershipServiceFactory = ({accessApprovalPolicyDAL,secretApprovalPolicyApproverDAL,secretApprovalPolicyDAL,+ approvalPolicyDAL,membershipUserDAL,userDAL,userAliasDAL,@@ -143,6 +147,18 @@ export const projectMembershipServiceFactory = ({});}}++ const secretChangePolicies = await approvalPolicyDAL.findPoliciesWhereSubjectIsApprover({+ projectId,+ type: ApprovalPolicyType.SecretChange,+ userIds+ });+ if (secretChangePolicies.length > 0) {+ const policyNames = secretChangePolicies.map((p) => p.name).join(", ");+ throw new BadRequestError({+ message: `${actionLabel}: user is an approver in secret approval ${secretChangePolicies.length > 1 ? "policies" : "policy"}: ${policyNames}`+ });+ }};const getProjectMemberships = async ({diff --git a/backend/src/services/secret-folder/secret-folder-service.ts b/backend/src/services/secret-folder/secret-folder-service.tsindex d182bd9e33..f9d48a10e6 100644--- a/backend/src/services/secret-folder/secret-folder-service.ts+++ b/backend/src/services/secret-folder/secret-folder-service.ts@@ -13,6 +13,7 @@ import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/servicesimport { shouldApplyPolicy } from "@app/ee/services/secret-approval-policy/secret-approval-policy-fns";import { TSecretApprovalPolicyServiceFactory } from "@app/ee/services/secret-approval-policy/secret-approval-policy-service";import { TSecretApprovalRequestCreationFnsFactory } from "@app/ee/services/secret-approval-request/secret-approval-request-creation-fns";+import { TSecretApprovalRequestServiceFactory } from "@app/ee/services/secret-approval-request/secret-approval-request-service";import { TSecretRotationV2DALFactory } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-dal";import { KeyStorePrefixes, PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore";import { BadRequestError, NotFoundError } from "@app/lib/errors";@@ -107,6 +108,7 @@ type TSecretFolderServiceFactoryDep = {TSecretApprovalRequestCreationFnsFactory,"createSecretApprovalRequestV2Bridge">;+ secretApprovalRequestService: Pick<TSecretApprovalRequestServiceFactory, "findFolderIdsWithOpenRequests">;secretQueueService: Pick<TSecretQueueFactory, "syncSecrets">;secretSyncQueue: Pick<TSecretSyncQueueFactory, "queueSecretSyncsSyncSecretsByPath">;dynamicSecretDAL: Pick<TDynamicSecretDALFactory, "findOne" | "find">;@@ -137,6 +139,7 @@ export const secretFolderServiceFactory = ({secretVersionTagDAL,resourceMetadataDAL,secretApprovalRequestCreationFns,+ secretApprovalRequestService,secretQueueService,secretSyncQueue,dynamicSecretDAL,@@ -613,13 +616,15 @@ export const secretFolderServiceFactory = ({env,parentId,idOrName,- actor+ actor,+ tx}: {projectId: string;env: TProjectEnvironments;parentId: string;idOrName: string;actor: ActorType;+ tx?: Knex;}) => {let targetFolder = await folderDAL.findOne({@@ -685,6 +690,21 @@ export const secretFolderServiceFactory = ({id: folder.id}));+ const folderIdsWithOpenRequests = await secretApprovalRequestService.findFolderIdsWithOpenRequests(+ folderPolicyPaths.map((p) => p.id),+ tx+ );+ if (folderIdsWithOpenRequests.length > 0) {+ const blockedPaths = folderPolicyPaths+ .filter((p) => folderIdsWithOpenRequests.includes(p.id))+ .map((p) => `"${p.path}"`)+ .join(", ");+ throw new BadRequestError({+ message: `You cannot delete the selected folder because it has open change requests at folder path ${blockedPaths}. Merge or close the change requests and try again.`,+ name: "DeleteFolderHasOpenChangeRequests"+ });+ }+// get secrets under the given foldersconst secrets = await secretV2BridgeDAL.findByFolderIds({folderIds: folderPolicyPaths.map((p) => p.id)@@ -745,7 +765,7 @@ export const secretFolderServiceFactory = ({message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`});- await $checkFolderPolicy({ projectId, env, parentId: parentFolder.id, idOrName, actor });+ await $checkFolderPolicy({ projectId, env, parentId: parentFolder.id, idOrName, actor, tx });let folderToDelete = await folderDAL.findOne({@@ -1430,7 +1450,7 @@ export const secretFolderServiceFactory = ({});}- await $checkFolderPolicy({ projectId, env, parentId: parentFolder.id, idOrName, actor });+ await $checkFolderPolicy({ projectId, env, parentId: parentFolder.id, idOrName, actor, tx });let folderToDelete = await folderDAL.findOne({