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
address review comments
adilsone908051a33fd
diff --git a/backend/e2e-test/routes/v1/identity-folder-access.spec.ts b/backend/e2e-test/routes/v1/identity-folder-access.spec.tsindex 4df6c0da9f..f3110117d4 100644--- a/backend/e2e-test/routes/v1/identity-folder-access.spec.ts+++ b/backend/e2e-test/routes/v1/identity-folder-access.spec.ts@@ -2,13 +2,16 @@ import {AccessScope,OrgMembershipRole,ProjectMembershipRole,+ ProjectType,SecretFolderRole,TableName,TemporaryPermissionMode} from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";import { removeIdentitiesFromGroup } from "@app/ee/services/group/group-fns";+import { reapDeletedGroupFolderGrants } from "@app/ee/services/group/group-folder-grant-fns";import { identityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";+import { userGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";import { KeyStorePrefixes } from "@app/keystore/keystore";import { ms } from "@app/lib/ms";import { alphaNumericNanoId } from "@app/lib/nanoid";@@ -16,6 +19,7 @@ import { additionalPrivilegeDALFactory } from "@app/services/additional-privilegimport { ActorType } from "@app/services/auth/auth-type";import { identityDALFactory } from "@app/services/identity/identity-dal";import { membershipDALFactory } from "@app/services/membership/membership-dal";+import { membershipGroupDALFactory } from "@app/services/membership-group/membership-group-dal";const projectId = seedData1.project.id;const orgId = seedData1.organization.id;@@ -807,6 +811,187 @@ describe("Identity folder access CRUD", () => {});});+ describe("sub-org group removal reaps folder grants", () => {+ let subOrgId: string;+ let subOrgProjectId: string;+ let subOrgEnvId: string;+ let subOrgFolderId: string;+ let groupOnlyIdentityId: string;+ let stillLinkedIdentityId: string;+ let soleGroupId: string;+ let firstOfTwoGroupsId: string;+ let secondOfTwoGroupsId: string;++ const insertGroupMembership = async ({+ actorGroupId,+ scopeOrgId,+ scopeProjectId,+ role+ }: {+ actorGroupId: string;+ scopeOrgId: string;+ scopeProjectId?: string;+ role: OrgMembershipRole | ProjectMembershipRole;+ }) => {+ const [membership] = await testDb(TableName.Membership)+ .insert({+ scope: scopeProjectId ? AccessScope.Project : AccessScope.Organization,+ scopeOrgId,+ scopeProjectId: scopeProjectId ?? null,+ actorGroupId+ })+ .returning("*");+ await testDb(TableName.MembershipRole).insert({ membershipId: membership.id, role });+ };++ const createParentGroupLinkedToSubOrgProject = async () => {+ const slug = `identity-folder-suborg-grp-${alphaNumericNanoId(8)}`.toLowerCase();+ const [created] = await testDb(TableName.Groups).insert({ orgId, name: slug, slug }).returning("*");+ await insertGroupMembership({+ actorGroupId: created.id,+ scopeOrgId: orgId,+ role: OrgMembershipRole.Member+ });+ await insertGroupMembership({+ actorGroupId: created.id,+ scopeOrgId: subOrgId,+ role: OrgMembershipRole.Member+ });+ await insertGroupMembership({+ actorGroupId: created.id,+ scopeOrgId: subOrgId,+ scopeProjectId: subOrgProjectId,+ role: ProjectMembershipRole.Member+ });+ return created.id;+ };++ const createOrgOnlyIdentity = async () => {+ const [identity] = await testDb(TableName.Identity)+ .insert({ name: `identity-folder-suborg-${alphaNumericNanoId(8)}`, orgId })+ .returning("*");+ const [orgMembership] = await testDb(TableName.Membership)+ .insert({+ scope: AccessScope.Organization,+ scopeOrgId: orgId,+ actorIdentityId: identity.id+ })+ .returning("*");+ await testDb(TableName.MembershipRole).insert({+ membershipId: orgMembership.id,+ role: OrgMembershipRole.Member+ });+ return identity.id;+ };++ const grantOnSubOrgFolder = async (targetIdentityId: string) => {+ const [grant] = await testDb(TableName.AdditionalPrivilege)+ .insert({+ name: `suborg-folder-grant-${alphaNumericNanoId(8)}`,+ actorIdentityId: targetIdentityId,+ projectId: subOrgProjectId,+ folderId: subOrgFolderId,+ role: SecretFolderRole.Read,+ permissions: JSON.stringify([])+ })+ .returning("*");+ return grant.id;+ };++ const removeIdentityFromGroup = async (groupId: string, targetIdentityId: string) => {+ const res = await testServer.inject({+ method: "DELETE",+ url: `/api/v1/groups/${groupId}/machine-identities/${targetIdentityId}`,+ headers: authHeaders()+ });+ expect(res.statusCode).toBe(200);+ };++ beforeAll(async () => {+ const suffix = alphaNumericNanoId(8).toLowerCase();+ const [subOrg] = await testDb(TableName.Organization)+ .insert({+ name: `folder-suborg-${suffix}`,+ slug: `folder-suborg-${suffix}`,+ parentOrgId: orgId,+ rootOrgId: orgId+ })+ .returning("*");+ subOrgId = subOrg.id;++ const [subOrgProject] = await testDb(TableName.Project)+ .insert({+ name: `folder-suborg-proj-${suffix}`,+ slug: `folder-suborg-proj-${suffix}`,+ orgId: subOrgId,+ type: ProjectType.SecretManager+ })+ .returning("*");+ subOrgProjectId = subOrgProject.id;++ const [env] = await testDb(TableName.Environment)+ .insert({ name: "Development", slug: "dev", position: 1, projectId: subOrgProjectId })+ .returning("*");+ subOrgEnvId = env.id;+ const [rootFolder] = await testDb(TableName.SecretFolder)+ .insert({ name: "root", envId: env.id, parentId: null })+ .returning("*");+ const [subOrgFolder] = await testDb(TableName.SecretFolder)+ .insert({ name: "suborg-folder-access", envId: env.id, parentId: rootFolder.id })+ .returning("*");+ subOrgFolderId = subOrgFolder.id;++ groupOnlyIdentityId = await createOrgOnlyIdentity();+ stillLinkedIdentityId = await createOrgOnlyIdentity();+ soleGroupId = await createParentGroupLinkedToSubOrgProject();+ firstOfTwoGroupsId = await createParentGroupLinkedToSubOrgProject();+ secondOfTwoGroupsId = await createParentGroupLinkedToSubOrgProject();++ await testDb(TableName.IdentityGroupMembership).insert([+ { identityId: groupOnlyIdentityId, groupId: soleGroupId },+ { identityId: stillLinkedIdentityId, groupId: firstOfTwoGroupsId },+ { identityId: stillLinkedIdentityId, groupId: secondOfTwoGroupsId }+ ]);+ });++ afterAll(async () => {+ const groupIds = [soleGroupId, firstOfTwoGroupsId, secondOfTwoGroupsId];+ await testDb(TableName.AdditionalPrivilege)+ .whereIn("actorIdentityId", [groupOnlyIdentityId, stillLinkedIdentityId])+ .del();+ await testDb(TableName.IdentityGroupMembership).whereIn("groupId", groupIds).del();+ await testDb(TableName.Membership).whereIn("actorGroupId", groupIds).del();+ await testDb(TableName.Groups).whereIn("id", groupIds).del();+ await testDb(TableName.Membership).whereIn("actorIdentityId", [groupOnlyIdentityId, stillLinkedIdentityId]).del();+ await testDb(TableName.Identity).whereIn("id", [groupOnlyIdentityId, stillLinkedIdentityId]).del();+ await testDb(TableName.SecretFolder).where({ id: subOrgFolderId }).del();+ await testDb(TableName.SecretFolder).where({ envId: subOrgEnvId }).del();+ await testDb(TableName.Environment).where({ id: subOrgEnvId }).del();+ await testDb(TableName.Project).where({ id: subOrgProjectId }).del();+ await testDb(TableName.Organization).where({ id: subOrgId }).del();+ });++ test("reaps the grant of a group-only identity that reached the sub-org project through the linked group", async () => {+ const grantId = await grantOnSubOrgFolder(groupOnlyIdentityId);++ await removeIdentityFromGroup(soleGroupId, groupOnlyIdentityId);++ expect(await testDb(TableName.AdditionalPrivilege).where({ id: grantId })).toEqual([]);+ });++ test("keeps the grant while another linked group still reaches the sub-org project", async () => {+ const grantId = await grantOnSubOrgFolder(stillLinkedIdentityId);++ await removeIdentityFromGroup(firstOfTwoGroupsId, stillLinkedIdentityId);++ expect(await testDb(TableName.AdditionalPrivilege).where({ id: grantId })).toHaveLength(1);++ await removeIdentityFromGroup(secondOfTwoGroupsId, stillLinkedIdentityId);++ expect(await testDb(TableName.AdditionalPrivilege).where({ id: grantId })).toEqual([]);+ });+ });+describe("group removed from project reaps folder grants", () => {let groupOnlyIdentityId: string;let directIdentityId: string;@@ -904,4 +1089,151 @@ describe("Identity folder access CRUD", () => {expect(await testDb(TableName.AdditionalPrivilege).where({ id: directMemberGrantId })).toHaveLength(1);});});+ describe("group deletion reaps folder grants", () => {+ let groupOnlyIdentityId: string;+ let directIdentityId: string;+ let soleGroupId: string;+ let firstOfTwoGroupsId: string;+ let secondOfTwoGroupsId: string;+ let reapDeps: Parameters<typeof reapDeletedGroupFolderGrants>[0];++ const createProjectGroup = async () => {+ const slug = `identity-folder-del-grp-${alphaNumericNanoId(8)}`.toLowerCase();+ const [created] = await testDb(TableName.Groups).insert({ orgId, name: slug, slug }).returning("*");++ for (const scope of [AccessScope.Organization, AccessScope.Project] as const) {+ // eslint-disable-next-line no-await-in-loop+ const [membership] = await testDb(TableName.Membership)+ .insert({+ scope,+ scopeOrgId: orgId,+ scopeProjectId: scope === AccessScope.Project ? projectId : null,+ actorGroupId: created.id+ })+ .returning("*");+ // eslint-disable-next-line no-await-in-loop+ await testDb(TableName.MembershipRole).insert({+ membershipId: membership.id,+ role: scope === AccessScope.Project ? ProjectMembershipRole.Member : OrgMembershipRole.Member+ });+ }++ return created.id;+ };++ const createOrgOnlyIdentity = async () => {+ const [identity] = await testDb(TableName.Identity)+ .insert({ name: `identity-folder-del-${alphaNumericNanoId(8)}`, orgId })+ .returning("*");++ const [orgMembership] = await testDb(TableName.Membership)+ .insert({ scope: AccessScope.Organization, scopeOrgId: orgId, actorIdentityId: identity.id })+ .returning("*");+ await testDb(TableName.MembershipRole).insert({ membershipId: orgMembership.id, role: OrgMembershipRole.Member });++ return identity.id;+ };++ const grantFolderAccess = async (targetIdentityId: string) => {+ const res = await testServer.inject({+ method: "POST",+ url: folderAccessUrl(targetIdentityId),+ headers: authHeaders(),+ body: { ...folderTarget, permission: SecretFolderRole.Read }+ });+ expect(res.statusCode).toBe(200);+ return res.json().folderAccess.id as string;+ };++ // the group row is what production deletes; its memberships go by ON DELETE CASCADE+ const deleteGroupRow = async (groupId: string) => {+ await testDb(TableName.Groups).where({ id: groupId }).del();+ };++ beforeAll(async () => {+ reapDeps = {+ userGroupMembershipDAL: userGroupMembershipDALFactory(testDb),+ identityGroupMembershipDAL: identityGroupMembershipDALFactory(testDb),+ membershipGroupDAL: membershipGroupDALFactory(testDb),+ additionalPrivilegeDAL: additionalPrivilegeDALFactory(testDb)+ };++ groupOnlyIdentityId = await createOrgOnlyIdentity();+ ({ identityId: directIdentityId } = await createProjectIdentity(ProjectMembershipRole.Member));++ soleGroupId = await createProjectGroup();+ firstOfTwoGroupsId = await createProjectGroup();+ secondOfTwoGroupsId = await createProjectGroup();++ await testDb(TableName.IdentityGroupMembership).insert([+ { identityId: groupOnlyIdentityId, groupId: soleGroupId },+ { identityId: directIdentityId, groupId: soleGroupId },+ { identityId: groupOnlyIdentityId, groupId: firstOfTwoGroupsId },+ { identityId: groupOnlyIdentityId, groupId: secondOfTwoGroupsId }+ ]);+ });++ afterAll(async () => {+ const groupIds = [soleGroupId, firstOfTwoGroupsId, secondOfTwoGroupsId];+ await testDb(TableName.AdditionalPrivilege)+ .whereIn("actorIdentityId", [groupOnlyIdentityId, directIdentityId])+ .del();+ await testDb(TableName.IdentityGroupMembership).whereIn("groupId", groupIds).del();+ await testDb(TableName.Membership).whereIn("actorGroupId", groupIds).del();+ await testDb(TableName.Groups).whereIn("id", groupIds).del();+ await deleteProjectIdentity(groupOnlyIdentityId);+ await deleteProjectIdentity(directIdentityId);+ });++ test("keeps the grant while another group still reaches the project, and reaps it with the last one", async () => {+ const grantId = await grantFolderAccess(groupOnlyIdentityId);++ await reapDeletedGroupFolderGrants(reapDeps, firstOfTwoGroupsId, testDb);+ await deleteGroupRow(firstOfTwoGroupsId);++ expect(await testDb(TableName.AdditionalPrivilege).where({ id: grantId })).toHaveLength(1);++ await reapDeletedGroupFolderGrants(reapDeps, secondOfTwoGroupsId, testDb);+ await deleteGroupRow(secondOfTwoGroupsId);+ await reapDeletedGroupFolderGrants(reapDeps, soleGroupId, testDb);++ expect(await testDb(TableName.AdditionalPrivilege).where({ id: grantId })).toEqual([]);+ });++ test("keeps the grant when the identity still holds a direct project membership", async () => {+ const grantId = await grantFolderAccess(directIdentityId);++ await reapDeletedGroupFolderGrants(reapDeps, soleGroupId, testDb);+ await deleteGroupRow(soleGroupId);++ expect(await testDb(TableName.AdditionalPrivilege).where({ id: grantId })).toHaveLength(1);+ });++ test("reaps only folder grants, leaving the identity's other privileges alone", async () => {+ const otherIdentityId = await createOrgOnlyIdentity();+ const otherGroupId = await createProjectGroup();+ await testDb(TableName.IdentityGroupMembership).insert({ identityId: otherIdentityId, groupId: otherGroupId });++ const folderGrantId = await grantFolderAccess(otherIdentityId);+ const [projectPrivilege] = await testDb(TableName.AdditionalPrivilege)+ .insert({+ name: `proj-priv-${alphaNumericNanoId(8)}`,+ actorIdentityId: otherIdentityId,+ projectId,+ permissions: JSON.stringify([])+ })+ .returning("*");++ await reapDeletedGroupFolderGrants(reapDeps, otherGroupId, testDb);+ await deleteGroupRow(otherGroupId);++ expect(await testDb(TableName.AdditionalPrivilege).where({ id: folderGrantId })).toEqual([]);+ expect(await testDb(TableName.AdditionalPrivilege).where({ id: projectPrivilege.id })).toHaveLength(1);++ await testDb(TableName.AdditionalPrivilege).where({ actorIdentityId: otherIdentityId }).del();+ await testDb(TableName.IdentityGroupMembership).where({ groupId: otherGroupId }).del();+ await testDb(TableName.Membership).where({ actorGroupId: otherGroupId }).del();+ await deleteProjectIdentity(otherIdentityId);+ });+ });});diff --git a/backend/e2e-test/routes/v1/user-folder-access.spec.ts b/backend/e2e-test/routes/v1/user-folder-access.spec.tsindex 9d354d5f01..1475503f0e 100644--- a/backend/e2e-test/routes/v1/user-folder-access.spec.ts+++ b/backend/e2e-test/routes/v1/user-folder-access.spec.ts@@ -13,6 +13,8 @@ import {} from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";import { removeUsersFromGroupByUserIds } from "@app/ee/services/group/group-fns";+import { reapDeletedGroupFolderGrants } from "@app/ee/services/group/group-folder-grant-fns";+import { identityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";import { userGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";import { KeyStorePrefixes } from "@app/keystore/keystore";import { getConfig, initEnvConfig } from "@app/lib/config/env";@@ -1161,4 +1163,179 @@ describe("User folder access CRUD", () => {expect(await testDb(TableName.AdditionalPrivilege).where({ id: grantId })).toEqual([]);});});+ describe("group deletion reaps folder grants", () => {+ let groupOnlyUserId: string;+ let directMemberUserId: string;+ let soleGroupId: string;+ let firstOfTwoGroupsId: string;+ let secondOfTwoGroupsId: string;+ let reapDeps: Parameters<typeof reapDeletedGroupFolderGrants>[0];++ const createProjectGroup = async () => {+ const slug = `folder-del-grp-${alphaNumericNanoId(8)}`.toLowerCase();+ const [group] = await testDb(TableName.Groups).insert({ orgId, name: slug, slug }).returning("*");++ for (const scope of [AccessScope.Organization, AccessScope.Project] as const) {+ // eslint-disable-next-line no-await-in-loop+ const [membership] = await testDb(TableName.Membership)+ .insert({+ scope,+ scopeOrgId: orgId,+ scopeProjectId: scope === AccessScope.Project ? projectId : null,+ actorGroupId: group.id+ })+ .returning("*");+ // eslint-disable-next-line no-await-in-loop+ await testDb(TableName.MembershipRole).insert({+ membershipId: membership.id,+ role: scope === AccessScope.Project ? ProjectMembershipRole.Member : OrgMembershipRole.Member+ });+ }++ return group.id;+ };++ const createOrgOnlyUser = async () => {+ const username = `folder-del-${alphaNumericNanoId(8)}@example.com`;+ const [user] = await testDb(TableName.Users)+ .insert({ username, email: username, isGhost: false, isAccepted: true, authMethods: [AuthMethod.EMAIL] })+ .returning("*");++ const [orgMembership] = await testDb(TableName.Membership)+ .insert({+ scope: AccessScope.Organization,+ scopeOrgId: orgId,+ actorUserId: user.id,+ status: OrgMembershipStatus.Accepted,+ isActive: true+ })+ .returning("*");+ await testDb(TableName.MembershipRole).insert({+ membershipId: orgMembership.id,+ role: OrgMembershipRole.Member+ });++ return user.id;+ };++ const grantFolderAccess = async (targetUserId: string) => {+ const res = await testServer.inject({+ method: "POST",+ url: folderAccessUrl(targetUserId),+ headers: authHeaders(),+ body: { ...folderTarget, permission: SecretFolderRole.Read }+ });+ expect(res.statusCode).toBe(200);+ return res.json().folderAccess.id as string;+ };++ // the group row is what production deletes; its memberships go by ON DELETE CASCADE+ const deleteGroupRow = async (groupId: string) => {+ await testDb(TableName.Groups).where({ id: groupId }).del();+ };++ beforeAll(async () => {+ reapDeps = {+ userGroupMembershipDAL: userGroupMembershipDALFactory(testDb),+ identityGroupMembershipDAL: identityGroupMembershipDALFactory(testDb),+ membershipGroupDAL: membershipGroupDALFactory(testDb),+ additionalPrivilegeDAL: additionalPrivilegeDALFactory(testDb)+ };++ groupOnlyUserId = await createOrgOnlyUser();+ ({ userId: directMemberUserId } = await createProjectUser(ProjectMembershipRole.Member));++ soleGroupId = await createProjectGroup();+ firstOfTwoGroupsId = await createProjectGroup();+ secondOfTwoGroupsId = await createProjectGroup();++ await testDb(TableName.UserGroupMembership).insert([+ { userId: groupOnlyUserId, groupId: soleGroupId },+ { userId: directMemberUserId, groupId: soleGroupId }+ ]);+ });++ afterAll(async () => {+ const groupIds = [soleGroupId, firstOfTwoGroupsId, secondOfTwoGroupsId];+ await testDb(TableName.AdditionalPrivilege).whereIn("actorUserId", [groupOnlyUserId, directMemberUserId]).del();+ await testDb(TableName.UserGroupMembership).whereIn("groupId", groupIds).del();+ await testDb(TableName.Membership).whereIn("actorGroupId", groupIds).del();+ await testDb(TableName.Groups).whereIn("id", groupIds).del();+ await deleteProjectUser(groupOnlyUserId);+ await deleteProjectUser(directMemberUserId);+ });++ test("reaps the group-only member's grant and keeps the direct project member's", async () => {+ const groupOnlyGrantId = await grantFolderAccess(groupOnlyUserId);+ const directMemberGrantId = await grantFolderAccess(directMemberUserId);+ const versionBefore = await getFolderPermissionVersion();++ await reapDeletedGroupFolderGrants(reapDeps, soleGroupId, testDb);+ await deleteGroupRow(soleGroupId);++ expect(await testDb(TableName.AdditionalPrivilege).where({ id: groupOnlyGrantId })).toEqual([]);+ // the direct project membership is still a route into the project, so this grant is untouched+ expect(await testDb(TableName.AdditionalPrivilege).where({ id: directMemberGrantId })).toHaveLength(1);+ // the deleted memberships are already part of the permission fingerprint; no bump is owed+ expect(await getFolderPermissionVersion()).toBe(versionBefore);+ });++ test("keeps the grant until the last group reaching the project is deleted", async () => {+ const secondGroupOnlyUserId = await createOrgOnlyUser();+ await testDb(TableName.UserGroupMembership).insert([+ { userId: secondGroupOnlyUserId, groupId: firstOfTwoGroupsId },+ { userId: secondGroupOnlyUserId, groupId: secondOfTwoGroupsId }+ ]);++ const grantId = await grantFolderAccess(secondGroupOnlyUserId);++ await reapDeletedGroupFolderGrants(reapDeps, firstOfTwoGroupsId, testDb);+ await deleteGroupRow(firstOfTwoGroupsId);++ expect(await testDb(TableName.AdditionalPrivilege).where({ id: grantId })).toHaveLength(1);++ await reapDeletedGroupFolderGrants(reapDeps, secondOfTwoGroupsId, testDb);+ await deleteGroupRow(secondOfTwoGroupsId);++ expect(await testDb(TableName.AdditionalPrivilege).where({ id: grantId })).toEqual([]);++ await deleteProjectUser(secondGroupOnlyUserId);+ });++ test("reaps only folder grants, leaving the actor's other privileges alone", async () => {+ const otherUserId = await createOrgOnlyUser();+ const otherGroupId = await createProjectGroup();+ await testDb(TableName.UserGroupMembership).insert({ userId: otherUserId, groupId: otherGroupId });++ const folderGrantId = await grantFolderAccess(otherUserId);+ const [projectPrivilege] = await testDb(TableName.AdditionalPrivilege)+ .insert({+ name: `proj-priv-${alphaNumericNanoId(8)}`,+ actorUserId: otherUserId,+ projectId,+ permissions: JSON.stringify([])+ })+ .returning("*");+ const [orgPrivilege] = await testDb(TableName.AdditionalPrivilege)+ .insert({+ name: `org-priv-${alphaNumericNanoId(8)}`,+ actorUserId: otherUserId,+ orgId,+ permissions: JSON.stringify([])+ })+ .returning("*");++ await reapDeletedGroupFolderGrants(reapDeps, otherGroupId, testDb);+ await deleteGroupRow(otherGroupId);++ expect(await testDb(TableName.AdditionalPrivilege).where({ id: folderGrantId })).toEqual([]);+ expect(await testDb(TableName.AdditionalPrivilege).where({ id: projectPrivilege.id })).toHaveLength(1);+ expect(await testDb(TableName.AdditionalPrivilege).where({ id: orgPrivilege.id })).toHaveLength(1);++ await testDb(TableName.AdditionalPrivilege).where({ actorUserId: otherUserId }).del();+ await testDb(TableName.UserGroupMembership).where({ groupId: otherGroupId }).del();+ await testDb(TableName.Membership).where({ actorGroupId: otherGroupId }).del();+ await deleteProjectUser(otherUserId);+ });+ });});diff --git a/backend/src/ee/services/group/group-fns.ts b/backend/src/ee/services/group/group-fns.tsindex c3191e5975..6b58e4e125 100644--- a/backend/src/ee/services/group/group-fns.ts+++ b/backend/src/ee/services/group/group-fns.ts@@ -492,14 +492,17 @@ export const removeUsersFromGroupByUserIds = async ({));- for await (const userId of membersToRemoveFromGroupNonPending.map((member) => member.id)) {- const projectsUserStillMemberOf = await userGroupMembershipDAL.filterProjectsByUserMembership(- userId,- group.id,- projectIds,- tx- );- const projectsToDeleteKeyFor = projectIds.filter((projectId) => !projectsUserStillMemberOf.has(projectId));+ const userIdsToRemove = membersToRemoveFromGroupNonPending.map((member) => member.id);+ const stillReach = await userGroupMembershipDAL.filterProjectsByUserMembership(+ userIdsToRemove,+ group.id,+ projectIds,+ tx+ );++ for await (const userId of userIdsToRemove) {+ const reachable = stillReach.get(userId);+ const projectsToDeleteKeyFor = projectIds.filter((projectId) => !reachable?.has(projectId));if (projectsToDeleteKeyFor.length) {await projectKeyDAL.delete(@@ -636,16 +639,16 @@ export const removeIdentitiesFromGroup = async ({));+ const stillReach = await identityGroupMembershipDAL.filterProjectsByIdentityMembership(+ identityIdsArray,+ group.id,+ projectIds,+ tx+ );+for await (const identityId of identityIdsArray) {- const projectsIdentityStillMemberOf = await identityGroupMembershipDAL.filterProjectsByIdentityMembership(- identityId,- group.id,- projectIds,- tx- );- const projectsToReapPrivilegesFor = projectIds.filter(- (projectId) => !projectsIdentityStillMemberOf.has(projectId)- );+ const reachable = stillReach.get(identityId);+ const projectsToReapPrivilegesFor = projectIds.filter((projectId) => !reachable?.has(projectId));if (projectsToReapPrivilegesFor.length) {// additional privileges are keyed on actor + project, not membership, so leaving thediff --git a/backend/src/ee/services/group/group-folder-grant-fns.ts b/backend/src/ee/services/group/group-folder-grant-fns.tsnew file mode 100644index 0000000000..7cb7642b30--- /dev/null+++ b/backend/src/ee/services/group/group-folder-grant-fns.ts@@ -0,0 +1,174 @@+import { Knex } from "knex";++import { AccessScope } from "@app/db/schemas";+import { chunkArray } from "@app/lib/fn";+import { TAdditionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";+import { TMembershipGroupDALFactory } from "@app/services/membership-group/membership-group-dal";++import { TIdentityGroupMembershipDALFactory } from "./identity-group-membership-dal";+import { TUserGroupMembershipDALFactory } from "./user-group-membership-dal";++const ACTOR_CHUNK_SIZE = 50;++type TReapOrphanedFolderGrantsDeps = {+ userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "filterProjectsByUserMembership">;+ identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "filterProjectsByIdentityMembership">;+ additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "delete">;+};++type TReapOrphanedFolderGrantsArg = {+ groupId: string;+ projectIdsByUserId: Map<string, string[]>;+ projectIdsByIdentityId: Map<string, string[]>;+};++type TProjectMembershipActor = {+ actorUserId?: string | null;+ actorIdentityId?: string | null;+ scopeProjectId?: string | null;+};++const $appendProjectId = (byActorId: Map<string, string[]>, actorId: string, projectId: string) => {+ byActorId.set(actorId, [...(byActorId.get(actorId) ?? []), projectId]);+};++export const collectProjectIdsByActor = (+ memberships: TProjectMembershipActor[],+ maps: {+ projectIdsByUserId?: Map<string, string[]>;+ projectIdsByIdentityId?: Map<string, string[]>;+ } = {}+) => {+ const projectIdsByUserId = maps.projectIdsByUserId ?? new Map<string, string[]>();+ const projectIdsByIdentityId = maps.projectIdsByIdentityId ?? new Map<string, string[]>();++ for (const membership of memberships) {+ if (membership.scopeProjectId) {+ if (membership.actorUserId) {+ $appendProjectId(projectIdsByUserId, membership.actorUserId, membership.scopeProjectId);+ } else if (membership.actorIdentityId) {+ $appendProjectId(projectIdsByIdentityId, membership.actorIdentityId, membership.scopeProjectId);+ }+ }+ }++ return { projectIdsByUserId, projectIdsByIdentityId };+};++const $collectOrphanedActorsByProject = (+ candidatesByActorId: Map<string, string[]>,+ stillReachable: Map<string, Set<string>>+) => {+ const actorsByProject = new Map<string, Set<string>>();++ for (const [actorId, candidates] of candidatesByActorId) {+ const reachable = stillReachable.get(actorId);+ for (const projectId of candidates) {+ if (!reachable?.has(projectId)) {+ const actors = actorsByProject.get(projectId);+ if (actors) {+ actors.add(actorId);+ } else {+ actorsByProject.set(projectId, new Set([actorId]));+ }+ }+ }+ }++ return actorsByProject;+};++/**+ * Deletes folder grants — and only folder grants, hence the `folderId` filter — for every+ * (actor, project) pair in the candidate maps that the actor no longer reaches, directly or through+ * another group. A grant is keyed on actor + project rather than on a membership, so nothing+ * cascades when a teardown removes an actor's last route into a project: the row survives and+ * reactivates if the actor is ever re-added.+ */+export const reapOrphanedFolderGrants = async (+ { userGroupMembershipDAL, identityGroupMembershipDAL, additionalPrivilegeDAL }: TReapOrphanedFolderGrantsDeps,+ { groupId, projectIdsByUserId, projectIdsByIdentityId }: TReapOrphanedFolderGrantsArg,+ tx: Knex+) => {+ const userIds = Array.from(projectIdsByUserId.keys());+ const userProjectIds = Array.from(new Set(Array.from(projectIdsByUserId.values()).flat()));++ if (userIds.length && userProjectIds.length) {+ const stillReachable = await userGroupMembershipDAL.filterProjectsByUserMembership(+ userIds,+ groupId,+ userProjectIds,+ tx+ );++ for (const [projectId, orphanedUserIds] of $collectOrphanedActorsByProject(projectIdsByUserId, stillReachable)) {+ for (const chunk of chunkArray(Array.from(orphanedUserIds), ACTOR_CHUNK_SIZE)) {+ // eslint-disable-next-line no-await-in-loop+ await additionalPrivilegeDAL.delete({ projectId, $in: { actorUserId: chunk }, $notNull: ["folderId"] }, tx);+ }+ }+ }++ const identityIds = Array.from(projectIdsByIdentityId.keys());+ const identityProjectIds = Array.from(new Set(Array.from(projectIdsByIdentityId.values()).flat()));++ if (identityIds.length && identityProjectIds.length) {+ const stillReachable = await identityGroupMembershipDAL.filterProjectsByIdentityMembership(+ identityIds,+ groupId,+ identityProjectIds,+ tx+ );++ for (const [projectId, orphanedIdentityIds] of $collectOrphanedActorsByProject(+ projectIdsByIdentityId,+ stillReachable+ )) {+ for (const chunk of chunkArray(Array.from(orphanedIdentityIds), ACTOR_CHUNK_SIZE)) {+ // eslint-disable-next-line no-await-in-loop+ await additionalPrivilegeDAL.delete({ projectId, $in: { actorIdentityId: chunk }, $notNull: ["folderId"] }, tx);+ }+ }+ }+};++type TReapDeletedGroupFolderGrantsDeps = Omit<+ TReapOrphanedFolderGrantsDeps,+ "userGroupMembershipDAL" | "identityGroupMembershipDAL"+> & {+ userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "filterProjectsByUserMembership" | "find">;+ identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "filterProjectsByIdentityMembership" | "find">;+ membershipGroupDAL: Pick<TMembershipGroupDALFactory, "find">;+};++/**+ * Reaps the folder grants of every member of [groupId] across the projects the group was on.+ * Deleting the group cascades its memberships away without touching the grants, so this has to run+ * while those memberships are still readable, i.e. before the group row is deleted.+ */+export const reapDeletedGroupFolderGrants = async (+ deps: TReapDeletedGroupFolderGrantsDeps,+ groupId: string,+ tx: Knex+) => {+ const [groupUsers, groupIdentities, groupProjectMemberships] = await Promise.all([+ deps.userGroupMembershipDAL.find({ groupId }, { tx }),+ deps.identityGroupMembershipDAL.find({ groupId }, { tx }),+ deps.membershipGroupDAL.find({ actorGroupId: groupId, scope: AccessScope.Project }, { tx })+ ]);++ const projectIds = Array.from(+ new Set(groupProjectMemberships.map((membership) => membership.scopeProjectId).filter(Boolean) as string[])+ );+ if (!projectIds.length) return;++ await reapOrphanedFolderGrants(+ deps,+ {+ groupId,+ projectIdsByUserId: new Map(groupUsers.map(({ userId }) => [userId, projectIds])),+ projectIdsByIdentityId: new Map(groupIdentities.map(({ identityId }) => [identityId, projectIds]))+ },+ tx+ );+};diff --git a/backend/src/ee/services/group/group-service.ts b/backend/src/ee/services/group/group-service.tsindex 1efe994bed..4d01419e06 100644--- a/backend/src/ee/services/group/group-service.ts+++ b/backend/src/ee/services/group/group-service.ts@@ -50,6 +50,11 @@ import {removeIdentitiesFromGroup,removeUsersFromGroupByUserIds} from "./group-fns";+import {+ collectProjectIdsByActor,+ reapDeletedGroupFolderGrants,+ reapOrphanedFolderGrants+} from "./group-folder-grant-fns";import {TAddMachineIdentityToGroupDTO,TAddUserToGroupDTO,@@ -359,7 +364,9 @@ export const groupServiceFactory = ({/*** After removing users/identities from a group, clean up their direct project memberships- * in any sub-orgs where the group is linked and the actor no longer has effective access.+ * in any sub-orgs where the group is linked and the actor no longer has effective access,+ * and reap folder grants on the projects the group carried there — including for actors+ * who only reached those projects through the group and have no direct membership row.*/const cleanUpSubOrgProjectMemberships = async ({groupId,@@ -376,7 +383,7 @@ export const groupServiceFactory = ({if (referencingSubOrgs.length === 0) return;await groupDAL.transaction(async (tx) => {- const collectIdsForSubOrg = async (subOrgId: string): Promise<string[]> => {+ const collectMembershipsForSubOrg = async (subOrgId: string) => {// Find remaining linked groups in this sub-org (excluding the one the user was removed from)const remainingOrgGroupMemberships = await membershipGroupDAL.find({ scopeOrgId: subOrgId, scope: AccessScope.Organization },@@ -439,11 +446,43 @@ export const groupServiceFactory = ({: []]);- return [...userProjectMemberships.map((pm) => pm.id), ...identityProjectMemberships.map((pm) => pm.id)];+ return [...userProjectMemberships, ...identityProjectMemberships];};- const idsPerSubOrg = await Promise.all(referencingSubOrgs.map((subOrg) => collectIdsForSubOrg(subOrg.orgId)));- await deleteMembershipsInBatch(idsPerSubOrg.flat(), tx);+ const [membershipsToDelete, groupProjectMemberships] = await Promise.all([+ Promise.all(referencingSubOrgs.map((subOrg) => collectMembershipsForSubOrg(subOrg.orgId))).then((rows) =>+ rows.flat()+ ),+ membershipGroupDAL.find(+ {+ actorGroupId: groupId,+ scope: AccessScope.Project,+ $in: { scopeOrgId: referencingSubOrgs.map((subOrg) => subOrg.orgId) }+ },+ { tx }+ )+ ]);++ // every removed actor loses the projects the linked group carried; actors whose last+ // org access is gone additionally lose the ones their own direct membership covered+ const groupProjectIds = Array.from(+ new Set(groupProjectMemberships.map((pm) => pm.scopeProjectId).filter(Boolean) as string[])+ );+ const { projectIdsByUserId, projectIdsByIdentityId } = collectProjectIdsByActor(membershipsToDelete, {+ projectIdsByUserId: new Map(userIds.map((userId) => [userId, [...groupProjectIds]])),+ projectIdsByIdentityId: new Map(identityIds.map((identityId) => [identityId, [...groupProjectIds]]))+ });++ await deleteMembershipsInBatch(+ membershipsToDelete.map((pm) => pm.id),+ tx+ );++ await reapOrphanedFolderGrants(+ { userGroupMembershipDAL, identityGroupMembershipDAL, additionalPrivilegeDAL },+ { groupId, projectIdsByUserId, projectIdsByIdentityId },+ tx+ );await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds }, tx);});@@ -532,41 +571,61 @@ export const groupServiceFactory = ({const usersToCleanUp = groupUserIds.filter((id) => !userIdsWithOtherMemberships.has(id));const identitiesToCleanUp = groupIdentityIds.filter((id) => !identityIdsWithOtherMemberships.has(id));- const [userProjectIdsToDelete, identityProjectIdsToDelete] = await Promise.all([+ const [userProjectMembershipsToDelete, identityProjectMembershipsToDelete] = await Promise.all([usersToCleanUp.length > 0- ? membershipGroupDAL- .find(- {- ...(usersToCleanUp.length === 1- ? { actorUserId: usersToCleanUp[0] }- : { $in: { actorUserId: usersToCleanUp } }),- scopeOrgId: actorOrgId,- scope: AccessScope.Project- },- { tx }- )- .then((rows) => rows.map((r) => r.id))+ ? membershipGroupDAL.find(+ {+ ...(usersToCleanUp.length === 1+ ? { actorUserId: usersToCleanUp[0] }+ : { $in: { actorUserId: usersToCleanUp } }),+ scopeOrgId: actorOrgId,+ scope: AccessScope.Project+ },+ { tx }+ ): [],identitiesToCleanUp.length > 0- ? membershipGroupDAL- .find(- {- ...(identitiesToCleanUp.length === 1- ? { actorIdentityId: identitiesToCleanUp[0] }- : { $in: { actorIdentityId: identitiesToCleanUp } }),- scopeOrgId: actorOrgId,- scope: AccessScope.Project- },- { tx }- )- .then((rows) => rows.map((r) => r.id))+ ? membershipGroupDAL.find(+ {+ ...(identitiesToCleanUp.length === 1+ ? { actorIdentityId: identitiesToCleanUp[0] }+ : { $in: { actorIdentityId: identitiesToCleanUp } }),+ scopeOrgId: actorOrgId,+ scope: AccessScope.Project+ },+ { tx }+ ): []]);- membershipIdsToDelete.push(...userProjectIdsToDelete, ...identityProjectIdsToDelete);+ membershipIdsToDelete.push(+ ...userProjectMembershipsToDelete.map((pm) => pm.id),+ ...identityProjectMembershipsToDelete.map((pm) => pm.id)+ );++ // every member loses the projects the group carried; the cleaned-up actors additionally lose+ // the ones their own direct membership covered+ const groupProjectIds = Array.from(+ new Set(groupProjectMemberships.map((pm) => pm.scopeProjectId).filter(Boolean) as string[])+ );+ const { projectIdsByUserId, projectIdsByIdentityId } = collectProjectIdsByActor(+ [...userProjectMembershipsToDelete, ...identityProjectMembershipsToDelete],+ {+ projectIdsByUserId: new Map(groupUserIds.map((userId) => [userId, [...groupProjectIds]])),+ projectIdsByIdentityId: new Map(groupIdentityIds.map((identityId) => [identityId, [...groupProjectIds]]))+ }+ );await deleteMembershipsInBatch(membershipIdsToDelete, tx);+ // must follow the delete: the actors' own direct memberships are among the rows removed, and+ // one still present reads as "still reaches"+ await reapOrphanedFolderGrants(+ { userGroupMembershipDAL, identityGroupMembershipDAL, additionalPrivilegeDAL },+ { groupId, projectIdsByUserId, projectIdsByIdentityId },+ tx+ );+await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ groupIds: [groupId] }, tx);});@@ -593,6 +652,13 @@ export const groupServiceFactory = ({tx);+ // must precede the delete: it cascades away the memberships the reap reads+ await reapDeletedGroupFolderGrants(+ { userGroupMembershipDAL, identityGroupMembershipDAL, membershipGroupDAL, additionalPrivilegeDAL },+ groupId,+ tx+ );+const [deletedGroup] = await groupDAL.delete({id: groupId,diff --git a/backend/src/ee/services/group/identity-group-membership-dal.ts b/backend/src/ee/services/group/identity-group-membership-dal.tsindex 20ec1de02f..02b201c980 100644--- a/backend/src/ee/services/group/identity-group-membership-dal.ts+++ b/backend/src/ee/services/group/identity-group-membership-dal.ts@@ -27,38 +27,33 @@ export const identityGroupMembershipDALFactory = (db: TDbClient) => {try {const knex = tx || db.replicaNode();- const rows = (await knex.queryBuilder().union([- (qb) => {- void qb- .from(TableName.Membership)- .where(`${TableName.Membership}.scope`, AccessScope.Project)- .whereIn(`${TableName.Membership}.actorIdentityId`, identityIds)- .whereIn(`${TableName.Membership}.scopeProjectId`, projectIds)- .select(- db.ref("actorIdentityId").withSchema(TableName.Membership).as("identityId"),- db.ref("scopeProjectId").withSchema(TableName.Membership).as("projectId")- );- },- (qb) => {- void qb- .from(TableName.IdentityGroupMembership)- .whereIn(`${TableName.IdentityGroupMembership}.identityId`, identityIds)- .whereNot(`${TableName.IdentityGroupMembership}.groupId`, groupId)- .join(- TableName.Membership,- `${TableName.IdentityGroupMembership}.groupId`,- `${TableName.Membership}.actorGroupId`- )- .where(`${TableName.Membership}.scope`, AccessScope.Project)- .whereIn(`${TableName.Membership}.scopeProjectId`, projectIds)- .select(- db.ref("identityId").withSchema(TableName.IdentityGroupMembership),- db.ref("scopeProjectId").withSchema(TableName.Membership).as("projectId")- );- }- ])) as { identityId: string; projectId: string }[];+ // Two queries instead of UNION: Knex compiles whereIn arrays inside+ // queryBuilder().union() as `IN $n` without parentheses, which Postgres rejects.+ const directRows = (await knex(TableName.Membership)+ .where(`${TableName.Membership}.scope`, AccessScope.Project)+ .whereIn(`${TableName.Membership}.actorIdentityId`, identityIds)+ .whereIn(`${TableName.Membership}.scopeProjectId`, projectIds)+ .select(+ db.ref("actorIdentityId").withSchema(TableName.Membership).as("identityId"),+ db.ref("scopeProjectId").withSchema(TableName.Membership).as("projectId")+ )) as { identityId: string; projectId: string }[];++ const viaOtherGroupRows = (await knex(TableName.IdentityGroupMembership)+ .whereIn(`${TableName.IdentityGroupMembership}.identityId`, identityIds)+ .whereNot(`${TableName.IdentityGroupMembership}.groupId`, groupId)+ .join(+ TableName.Membership,+ `${TableName.IdentityGroupMembership}.groupId`,+ `${TableName.Membership}.actorGroupId`+ )+ .where(`${TableName.Membership}.scope`, AccessScope.Project)+ .whereIn(`${TableName.Membership}.scopeProjectId`, projectIds)+ .select(+ db.ref("identityId").withSchema(TableName.IdentityGroupMembership),+ db.ref("scopeProjectId").withSchema(TableName.Membership).as("projectId")+ )) as { identityId: string; projectId: string }[];- for (const { identityId, projectId } of rows) {+ for (const { identityId, projectId } of [...directRows, ...viaOtherGroupRows]) {let projects = stillReach.get(identityId);if (!projects) {projects = new Set();diff --git a/backend/src/ee/services/group/user-group-membership-dal.ts b/backend/src/ee/services/group/user-group-membership-dal.tsindex aa2e29b57b..882a2b33ff 100644--- a/backend/src/ee/services/group/user-group-membership-dal.ts+++ b/backend/src/ee/services/group/user-group-membership-dal.ts@@ -27,38 +27,27 @@ export const userGroupMembershipDALFactory = (db: TDbClient) => {try {const knex = tx || db.replicaNode();- const rows = (await knex.queryBuilder().union([- (qb) => {- void qb- .from(TableName.Membership)- .where(`${TableName.Membership}.scope`, AccessScope.Project)- .whereIn(`${TableName.Membership}.actorUserId`, userIds)- .whereIn(`${TableName.Membership}.scopeProjectId`, projectIds)- .select(- db.ref("actorUserId").withSchema(TableName.Membership).as("userId"),- db.ref("scopeProjectId").withSchema(TableName.Membership).as("projectId")- );- },- (qb) => {- void qb- .from(TableName.UserGroupMembership)- .whereIn(`${TableName.UserGroupMembership}.userId`, userIds)- .whereNot(`${TableName.UserGroupMembership}.groupId`, groupId)- .join(- TableName.Membership,- `${TableName.UserGroupMembership}.groupId`,- `${TableName.Membership}.actorGroupId`- )- .where(`${TableName.Membership}.scope`, AccessScope.Project)- .whereIn(`${TableName.Membership}.scopeProjectId`, projectIds)- .select(- db.ref("userId").withSchema(TableName.UserGroupMembership),- db.ref("scopeProjectId").withSchema(TableName.Membership).as("projectId")- );- }- ])) as { userId: string; projectId: string }[];+ const directRows = (await knex(TableName.Membership)+ .where(`${TableName.Membership}.scope`, AccessScope.Project)+ .whereIn(`${TableName.Membership}.actorUserId`, userIds)+ .whereIn(`${TableName.Membership}.scopeProjectId`, projectIds)+ .select(+ db.ref("actorUserId").withSchema(TableName.Membership).as("userId"),+ db.ref("scopeProjectId").withSchema(TableName.Membership).as("projectId")+ )) as { userId: string; projectId: string }[];++ const viaOtherGroupRows = (await knex(TableName.UserGroupMembership)+ .whereIn(`${TableName.UserGroupMembership}.userId`, userIds)+ .whereNot(`${TableName.UserGroupMembership}.groupId`, groupId)+ .join(TableName.Membership, `${TableName.UserGroupMembership}.groupId`, `${TableName.Membership}.actorGroupId`)+ .where(`${TableName.Membership}.scope`, AccessScope.Project)+ .whereIn(`${TableName.Membership}.scopeProjectId`, projectIds)+ .select(+ db.ref("userId").withSchema(TableName.UserGroupMembership),+ db.ref("scopeProjectId").withSchema(TableName.Membership).as("projectId")+ )) as { userId: string; projectId: string }[];- for (const { userId, projectId } of rows) {+ for (const { userId, projectId } of [...directRows, ...viaOtherGroupRows]) {let projects = stillReach.get(userId);if (!projects) {projects = new Set();diff --git a/backend/src/ee/services/permission/permission-fns.ts b/backend/src/ee/services/permission/permission-fns.tsindex 5955fe6fdc..d358f3dbe4 100644--- a/backend/src/ee/services/permission/permission-fns.ts+++ b/backend/src/ee/services/permission/permission-fns.ts@@ -497,38 +497,35 @@ export const fetchFolderScopedPrivileges = async (additionalPrivilegeDAL,secretFolderDAL}: {- additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "findFolderScopedPrivileges" | "transaction">;+ additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "findFolderScopedPrivileges">;secretFolderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds">;}): Promise<TCachedFolderScopedPrivileges> => {- return additionalPrivilegeDAL.transaction(async (tx) => {- const rows = await additionalPrivilegeDAL.findFolderScopedPrivileges({ projectId, actorId, actorType: actor }, tx);- if (!rows.length) return { privileges: [] };-- const foldersWithPath = await secretFolderDAL.findSecretPathByFolderIds(- projectId,- rows.map((row) => row.folderId),- tx- );+ const rows = await additionalPrivilegeDAL.findFolderScopedPrivileges({ projectId, actorId, actorType: actor });+ if (!rows.length) return { privileges: [] };- return {- privileges: rows.flatMap((row, idx) => {- const folder = foldersWithPath[idx];- if (!folder || !row.role) return [];- return [- {- id: row.id,- folderId: row.folderId,- role: row.role,- environmentSlug: folder.environmentSlug,- secretPath: folder.path,- isTemporary: row.isTemporary,- temporaryAccessEndTime: row.temporaryAccessEndTime- }- ];- })- };- });+ const foldersWithPath = await secretFolderDAL.findSecretPathByFolderIds(+ projectId,+ rows.map((row) => row.folderId)+ );++ return {+ privileges: rows.flatMap((row, idx) => {+ const folder = foldersWithPath[idx];+ if (!folder || !row.role) return [];+ return [+ {+ id: row.id,+ folderId: row.folderId,+ role: row.role,+ environmentSlug: folder.environmentSlug,+ secretPath: folder.path,+ isTemporary: row.isTemporary,+ temporaryAccessEndTime: row.temporaryAccessEndTime+ }+ ];+ })+ };};export const buildFolderScopedPrivilegeRules = (diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.tsindex fa80912e0a..63eb5adc07 100644--- a/backend/src/ee/services/permission/permission-service.ts+++ b/backend/src/ee/services/permission/permission-service.ts@@ -304,7 +304,7 @@ type TPermissionServiceFactoryDep = {userDAL: Pick<TUserDALFactory, "findById">;identityDAL: Pick<TIdentityDALFactory, "findById">;roleDAL: Pick<TRoleDALFactory, "find">;- additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "find" | "findFolderScopedPrivileges" | "transaction">;+ additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "find" | "findFolderScopedPrivileges">;groupDAL: Pick<TGroupDALFactory, "find">;secretFolderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds">;};diff --git a/backend/src/ee/services/scim/scim-service.ts b/backend/src/ee/services/scim/scim-service.tsindex 489a89678f..2311fa4f65 100644--- a/backend/src/ee/services/scim/scim-service.ts+++ b/backend/src/ee/services/scim/scim-service.ts@@ -15,6 +15,8 @@ import {} from "@app/db/schemas";import { TGroupDALFactory } from "@app/ee/services/group/group-dal";import { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "@app/ee/services/group/group-fns";+import { reapDeletedGroupFolderGrants } from "@app/ee/services/group/group-folder-grant-fns";+import { TIdentityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";import { TScimDALFactory } from "@app/ee/services/scim/scim-dal";import { PgSqlLock } from "@app/keystore/keystore";@@ -114,6 +116,7 @@ type TScimServiceFactoryDep = {| "update">;membershipGroupDAL: Pick<TMembershipGroupDALFactory, "find" | "create">;+ identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find" | "filterProjectsByIdentityMembership">;membershipRoleDAL: TMembershipRoleDALFactory;userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory,@@ -155,6 +158,7 @@ export const scimServiceFactory = ({smtpService,externalGroupOrgRoleMappingDAL,membershipGroupDAL,+ identityGroupMembershipDAL,membershipUserDAL,membershipRoleDAL,additionalPrivilegeDAL,@@ -1548,6 +1552,12 @@ export const scimServiceFactory = ({tx);+ await reapDeletedGroupFolderGrants(+ { userGroupMembershipDAL, identityGroupMembershipDAL, membershipGroupDAL, additionalPrivilegeDAL },+ groupId,+ tx+ );+const deleted = await groupDAL.delete({ id: groupId, orgId }, tx);if (!deleted.length) return deleted;diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex ea690c0850..9eb092de91 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -1245,6 +1245,7 @@ export const registerRoutes = async (orgDAL,projectDAL,userGroupMembershipDAL,+ identityGroupMembershipDAL,projectKeyDAL,projectBotDAL,permissionService,diff --git a/backend/src/services/additional-privilege/additional-privilege-dal.ts b/backend/src/services/additional-privilege/additional-privilege-dal.tsindex ed8229d83d..2712525410 100644--- a/backend/src/services/additional-privilege/additional-privilege-dal.ts+++ b/backend/src/services/additional-privilege/additional-privilege-dal.ts@@ -83,7 +83,7 @@ export const additionalPrivilegeDALFactory = (db: TDbClient) => {}: { projectId: string; actorId: string; actorType: ActorType.USER | ActorType.IDENTITY },tx?: Knex) => {- const docs = await (tx || db.replicaNode())(TableName.AdditionalPrivilege)+ const docs = await (tx || db)(TableName.AdditionalPrivilege).where({ projectId }).whereNotNull("folderId").where(actorType === ActorType.IDENTITY ? { actorIdentityId: actorId } : { actorUserId: actorId })