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
also emit on github sync
Thiago Araujo da Silvaa2638fc9b4eb
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 567ae2621a..01a4037d57 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -889,7 +889,8 @@ itself whether the actor still reaches the org.- **Every removal of an org path emits a fact event in the same tx.** Four of them,`com.infisical.organization.<entity>.removed.v1`:- `group-membership`: `groupId`, `orgIds`, the `members` who left. From the removal helpers in- `group-fns.ts` (manual route plus SCIM, LDAP, OIDC and SAML sync).+ `group-fns.ts` (manual route plus SCIM, LDAP, OIDC and SAML sync) and GitHub org sync, which removes team+ members itself at login and on a manual sync.- `group-link`: `orgId`, `groupId`, the group's `members`. From `membershipGroupService.detachGroupFromOrg`.- `group`: `groupId`, `orgIds`, all `members`. From owned and SCIM group deletes, read with`groupDAL.findGroupActorsAndOrgs` before the cascade.@@ -910,7 +911,7 @@ itself whether the actor still reaches the org.It runs in the caller's tx and hands back the PAM cancellation sender for after commit. Don't add anothercopy of that list.- **Removing a user from an org tears down synchronously; for an identity it depends on the path.** `deleteOrgMembershipsFn`- (org member removal, bulk removal, SCIM deprovision) drops the user's org rows in the sub-orgs, their+ (org member removal, bulk removal, SCIM deprovision, the instance admin panel) drops the user's org rows in the sub-orgs, theirgroups there and calls `revokeActorsInOrgs` for the org plus its sub-orgs in the same tx; its event onlylets the consumer confirm nothing's left. `membershipIdentityService.deleteMembership` just writes therevocation marker and emits, so the consumer does all the project cleanup there. `identityService.deleteIdentity`@@ -936,8 +937,8 @@ itself whether the actor still reaches the org.- **`orgDAL.lockActorsForOrgAccess`** (advisory xact locks, one statement over the sorted ids so callerscan't deadlock) serializes everything that grants against the consumer, so access granted between itscheck and its deletes doesn't get reaped or outlive it. Two kinds of caller take it:- - The add-to-group helpers in `group-fns.ts` (the SSO and SCIM services only pass it through). Take it in- any new path that grants an org path outside them.+ - The add-to-group helpers in `group-fns.ts` (the SSO and SCIM services only pass it through) and GitHub org+ sync, which adds team members itself. Take it in any new path that grants an org path outside them.- Every path that writes a project or resource membership for a user or identity, through`lockAndAssertActiveOrgAccess` (`services/org/org-access-fns.ts`), which locks and rechecks`findActorsWithActiveOrgAccess` inside the write's own transaction: the generic user and identitydiff --git a/backend/e2e-test/routes/v1/org-access-reconcile.spec.ts b/backend/e2e-test/routes/v1/org-access-reconcile.spec.tsindex f4769b7374..5d192217be 100644--- a/backend/e2e-test/routes/v1/org-access-reconcile.spec.ts+++ b/backend/e2e-test/routes/v1/org-access-reconcile.spec.ts@@ -320,6 +320,41 @@ describe("Org access reconcile", () => {expect(await projectRows(agentVaultProjectId, { actorUserId: userId })).toHaveLength(1);});+ test("removing a member from the instance admin panel tears down their access like org member removal", async () => {+ const groupId = await createLinkedGroup("reconcile-admin-panel");+ const { userId } = await createRootUserWithProjects("reconcile-admin-panel-user", [groupId]);+ await addUserMembership({ userId, orgId: subOrgId, role: OrgMembershipRole.Member });+ await testDb(TableName.AdditionalPrivilege).insert({+ name: "reconcile-admin-panel-priv",+ actorUserId: userId,+ projectId: subOrgProjectId,+ permissions: JSON.stringify([])+ });+ const orgMembership = (await testDb(TableName.Membership)+ .where({ scope: AccessScope.Organization, scopeOrgId: rootOrgId, actorUserId: userId })+ .first("id")) as { id: string };++ // The seed user is the instance admin.+ const res = await testServer.inject({+ method: "DELETE",+ url: `/api/v1/admin/organization-management/organizations/${rootOrgId}/memberships/${orgMembership.id}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` }+ });+ expect(res.statusCode).toBe(200);++ // Read from the DB because the API can't list a removed member's leftover rows: the teardown is synchronous,+ // so nothing may survive in either org, and the group no longer gives them a way back in.+ expect(await testDb(TableName.Membership).where({ actorUserId: userId })).toHaveLength(0);+ expect(await testDb(TableName.UserGroupMembership).where({ userId })).toHaveLength(0);+ expect(await testDb(TableName.AdditionalPrivilege).where({ actorUserId: userId })).toHaveLength(0);+ expect(+ await testDb(TableName.EventOutbox)+ .where({ consumer: ORG_ACCESS_RECONCILE_CONSUMER })+ .whereRaw(`payload->>'actorId' = ?`, [userId])+ .whereRaw(`payload->>'orgId' = ?`, [rootOrgId])+ ).toHaveLength(1);+ });+// The sweep query, against real rows: a project or resource row with no path into the org is an orphan,// any path clears it. Resource-only rows (like a group-derived PAM admin's folder row) count too.test("the sweep query finds an actor with a project or resource row and no path into the org, and nothing else", async () => {diff --git a/backend/src/ee/services/github-org-sync/github-org-sync-reconcile.test.ts b/backend/src/ee/services/github-org-sync/github-org-sync-reconcile.test.tsnew file mode 100644index 0000000000..e06b0915bc--- /dev/null+++ b/backend/src/ee/services/github-org-sync/github-org-sync-reconcile.test.ts@@ -0,0 +1,240 @@+import { createMongoAbility } from "@casl/ability";+import { Knex } from "knex";+import { beforeEach, describe, expect, test, vi } from "vitest";++import { AuditLogInfo } from "@app/ee/services/audit-log/audit-log-types";+import { ActorType } from "@app/services/auth/auth-type";+import { GROUP_MEMBERSHIP_REMOVED_EVENT } from "@app/services/org/org-membership-events";++import { githubOrgSyncServiceFactory } from "./github-org-sync-service";++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }+}));++// The service builds its GitHub clients itself, so the fakes stand in for the SDK classes.+const github = vi.hoisted(() => ({ userTeams: [] as string[], orgTeams: [] as { name: string; logins: string[] }[] }));++// Constructors that return an object, since `new` on them yields that object.+vi.mock("@octokit/rest", () => ({+ Octokit: vi.fn(function OctokitRest() {+ return {+ rest: {+ orgs: {+ get: async () => ({}),+ getMembershipForAuthenticatedUser: async () => ({ data: { user: { login: "gh-user" } } })+ },+ users: { getAuthenticated: async () => ({}) }+ }+ };+ })+}));++vi.mock("@octokit/core", () => {+ const page = <T>(nodes: T[]) => ({+ totalCount: nodes.length,+ edges: nodes.map((node) => ({ node })),+ pageInfo: { hasNextPage: false, endCursor: null }+ });+ const Octokit = Object.assign(+ vi.fn(function OctokitCore() {+ return {+ graphql: async () => ({+ organization: {+ teams: page(+ github.orgTeams.map(({ name, logins }) => ({+ slug: name,+ name,+ description: null,+ members: page(logins.map((login) => ({ login, databaseId: Number(login.slice(1)) })))+ }))+ )+ }+ })+ };+ }),+ {+ plugin: () =>+ vi.fn(function OctokitWithPaginate() {+ return {+ graphql: {+ paginate: async () => ({+ organization: { teams: page(github.userTeams.map((name) => ({ name, description: "" }))) }+ })+ }+ };+ })+ }+ );+ return { Octokit };+});++const ORG_ID = "org-1";+const SUB_ORG_ID = "sub-org-1";+const TX = { sentinel: "tx" } as unknown as Knex;+const auditLogInfo = {} as AuditLogInfo;++const createService = () => {+ const lockActorsForOrgAccess = vi.fn().mockResolvedValue(undefined);+ const emit = vi.fn().mockResolvedValue(undefined);+ const insertMany = vi.fn(async (rows: unknown[]) => rows);+ const groupDAL = {+ transaction: vi.fn(async (cb: (tx: Knex) => Promise<unknown>) => cb(TX)),+ find: vi.fn(),+ insertMany: vi.fn(async (rows: { name: string }[]) => rows.map((row) => ({ ...row, id: `new-${row.name}` }))),+ findGroupOrgIds: vi.fn(async () => [ORG_ID, SUB_ORG_ID])+ };+ const orgMembershipDAL = { findOrgMembershipsWithUsersByOrgId: vi.fn() };+ const userAliasDAL = { find: vi.fn() };+ const userGroupMembershipDAL = {+ find: vi.fn(),+ findGroupMembershipsByUserIdInOrg: vi.fn(),+ findGroupMembershipsByGroupIdInOrg: vi.fn(),+ insertMany,+ delete: vi.fn().mockResolvedValue([])+ };++ const service = githubOrgSyncServiceFactory({+ githubOrgSyncDAL: {+ findOne: vi.fn().mockResolvedValue({ isActive: true, githubOrgName: "acme", encryptedGithubOrgAccessToken: "x" })+ } as never,+ permissionService: {+ getOrgPermission: vi+ .fn()+ .mockResolvedValue({ permission: createMongoAbility([{ action: "manage", subject: "all" }]) })+ } as never,+ kmsService: {+ createCipherPairWithDataKey: vi.fn().mockResolvedValue({ decryptor: () => Buffer.from("token") })+ } as never,+ userGroupMembershipDAL: userGroupMembershipDAL as never,+ groupDAL: groupDAL as never,+ membershipRoleDAL: { insertMany: vi.fn().mockResolvedValue([]) } as never,+ membershipGroupDAL: {+ insertMany: vi.fn(async (rows: unknown[]) => rows.map((row, index) => ({ ...(row as object), id: `m-${index}` })))+ } as never,+ licenseService: { getPlan: vi.fn().mockResolvedValue({ githubOrgSync: true }) } as never,+ orgMembershipDAL: orgMembershipDAL as never,+ userAliasDAL: userAliasDAL as never,+ usageMeteringService: { emit: vi.fn() } as never,+ alertChannelRecipientDAL: { pruneOutOfScopeRecipients: vi.fn().mockResolvedValue(undefined) } as never,+ auditLogService: { createAuditLog: vi.fn().mockResolvedValue(undefined) } as never,+ orgDAL: { lockActorsForOrgAccess },+ eventEmitter: { emit }+ });++ return {+ service,+ groupDAL,+ userGroupMembershipDAL,+ orgMembershipDAL,+ userAliasDAL,+ lockActorsForOrgAccess,+ emit,+ insertMany+ };+};++describe("GitHub org sync and org access reconcile", () => {+ beforeEach(() => vi.clearAllMocks());++ test("login sync emits a group membership removal per group the user left, and locks before adding", async () => {+ const { service, groupDAL, userGroupMembershipDAL, lockActorsForOrgAccess, emit, insertMany } = createService();+ github.userTeams = ["kept", "existing", "brand-new"];+ userGroupMembershipDAL.findGroupMembershipsByUserIdInOrg.mockResolvedValue([+ { groupId: "g-kept", groupName: "kept" },+ { groupId: "g-left", groupName: "left" }+ ]);+ groupDAL.find.mockResolvedValue([{ id: "g-existing", name: "existing" }]);++ await service.syncUserGroups({+ orgId: ORG_ID,+ userId: "user-1",+ username: "[email protected]",+ accessToken: "token",+ auditLogInfo+ });++ expect(emit).toHaveBeenCalledTimes(1);+ expect(emit).toHaveBeenCalledWith(+ {+ eventType: GROUP_MEMBERSHIP_REMOVED_EVENT,+ payload: {+ groupId: "g-left",+ orgIds: [ORG_ID, SUB_ORG_ID],+ members: [{ actorType: ActorType.USER, actorId: "user-1" }]+ }+ },+ TX+ );+ expect(groupDAL.findGroupOrgIds).toHaveBeenCalledWith("g-left", TX);++ // One add for the new group, one for the existing group, each behind the lock.+ expect(insertMany).toHaveBeenCalledTimes(2);+ expect(lockActorsForOrgAccess).toHaveBeenCalledTimes(2);+ lockActorsForOrgAccess.mock.calls.forEach(([actorIds, tx]) => {+ expect(actorIds).toEqual(["user-1"]);+ expect(tx).toBe(TX);+ });+ lockActorsForOrgAccess.mock.invocationCallOrder.forEach((lockOrder, index) => {+ expect(lockOrder).toBeLessThan(insertMany.mock.invocationCallOrder[index]);+ });+ });++ test("manual sync emits the removed members of each team, and locks the added ones", async () => {+ const {+ service,+ groupDAL,+ userGroupMembershipDAL,+ orgMembershipDAL,+ userAliasDAL,+ lockActorsForOrgAccess,+ emit,+ insertMany+ } = createService();+ // GitHub ids match the user ids' digits: u1 stays, u2 left the team, u3 joined it.+ github.orgTeams = [{ name: "team", logins: ["u1", "u3"] }];+ orgMembershipDAL.findOrgMembershipsWithUsersByOrgId.mockResolvedValue(+ ["1", "2", "3"].map((n) => ({+ id: `om-${n}`,+ status: "accepted",+ isActive: true,+ user: { id: `user-${n}`, username: `user-${n}@example.com`, email: `user-${n}@example.com` }+ }))+ );+ userAliasDAL.find.mockResolvedValue(+ ["1", "2", "3"].map((n) => ({ externalId: n, userId: `user-${n}`, isEmailVerified: true }))+ );+ groupDAL.find.mockResolvedValue([{ id: "g-team", name: "team" }]);+ userGroupMembershipDAL.find.mockResolvedValue([+ { groupId: "g-team", userId: "user-1" },+ { groupId: "g-team", userId: "user-2" }+ ]);+ userGroupMembershipDAL.findGroupMembershipsByGroupIdInOrg.mockResolvedValue([+ { id: "ugm-1", groupId: "g-team", groupName: "team", orgMembershipId: "om-1" },+ { id: "ugm-2", groupId: "g-team", groupName: "team", orgMembershipId: "om-2" }+ ]);++ await service.syncAllTeams({+ orgPermission: { type: ActorType.USER, id: "actor-1", orgId: ORG_ID, authMethod: null },+ auditLogInfo+ } as never);++ expect(userGroupMembershipDAL.delete).toHaveBeenCalledWith({ $in: { id: ["ugm-2"] } }, TX);+ expect(emit).toHaveBeenCalledTimes(1);+ expect(emit).toHaveBeenCalledWith(+ {+ eventType: GROUP_MEMBERSHIP_REMOVED_EVENT,+ payload: {+ groupId: "g-team",+ orgIds: [ORG_ID, SUB_ORG_ID],+ members: [{ actorType: ActorType.USER, actorId: "user-2" }]+ }+ },+ TX+ );++ expect(lockActorsForOrgAccess).toHaveBeenCalledTimes(1);+ expect(lockActorsForOrgAccess).toHaveBeenCalledWith(["user-3"], TX);+ expect(lockActorsForOrgAccess.mock.invocationCallOrder[0]).toBeLessThan(insertMany.mock.invocationCallOrder[0]);+ });+});diff --git a/backend/src/ee/services/github-org-sync/github-org-sync-service.ts b/backend/src/ee/services/github-org-sync/github-org-sync-service.tsindex 4904186785..f07398232e 100644--- a/backend/src/ee/services/github-org-sync/github-org-sync-service.ts+++ b/backend/src/ee/services/github-org-sync/github-org-sync-service.ts@@ -12,12 +12,15 @@ import { groupBy } from "@app/lib/fn";import { logger } from "@app/lib/logger";import { retryWithBackoff } from "@app/lib/retry";import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";+import { TEventEmitter } from "@app/services/event-outbox/event-outbox-types";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";import { TMembershipGroupDALFactory } from "@app/services/membership-group/membership-group-dal";+import { TOrgDALFactory } from "@app/services/org/org-dal";+import { emitGroupMembershipRemoved, toOrgMembershipActors } from "@app/services/org/org-membership-events";import { TOrgMembershipDALFactory } from "@app/services/org-membership/org-membership-dal";import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";import { UserAliasType } from "@app/services/user-alias/user-alias-types";@@ -369,7 +372,7 @@ type TGithubOrgSyncServiceFactoryDep = {TUserGroupMembershipDALFactory,"find" | "findGroupMembershipsByUserIdInOrg" | "findGroupMembershipsByGroupIdInOrg" | "insertMany" | "delete">;- groupDAL: Pick<TGroupDALFactory, "insertMany" | "transaction" | "find">;+ groupDAL: Pick<TGroupDALFactory, "insertMany" | "transaction" | "find" | "findGroupOrgIds">;membershipRoleDAL: Pick<TMembershipRoleDALFactory, "insertMany">;membershipGroupDAL: Pick<TMembershipGroupDALFactory, "insertMany">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;@@ -378,6 +381,8 @@ type TGithubOrgSyncServiceFactoryDep = {usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;+ orgDAL: Pick<TOrgDALFactory, "lockActorsForOrgAccess">;+ eventEmitter: TEventEmitter;};export type TGithubOrgSyncServiceFactory = ReturnType<typeof githubOrgSyncServiceFactory>;@@ -395,7 +400,9 @@ export const githubOrgSyncServiceFactory = ({membershipGroupDAL,usageMeteringService,alertChannelRecipientDAL,- auditLogService+ auditLogService,+ orgDAL,+ eventEmitter}: TGithubOrgSyncServiceFactoryDep) => {const createGithubOrgSync = async ({githubOrgName,@@ -697,6 +704,7 @@ export const githubOrgSyncServiceFactory = ({tx);+ await orgDAL.lockActorsForOrgAccess([userId], tx);await userGroupMembershipDAL.insertMany(insertedGroups.map((el) => ({groupId: el.id,@@ -727,6 +735,7 @@ export const githubOrgSyncServiceFactory = ({if (updateTeams.length) {const groupsToUpdate = updateTeams.map((teamName) => githubUserTeamOnInfisicalGroupByName[teamName][0]);await groupDAL.transaction(async (tx) => {+ await orgDAL.lockActorsForOrgAccess([userId], tx);await userGroupMembershipDAL.insertMany(groupsToUpdate.map((group) => ({groupId: group.id,@@ -760,6 +769,18 @@ export const githubOrgSyncServiceFactory = ({);await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds: [userId] }, tx);++ for await (const { groupId } of removeFromTeams) {+ await emitGroupMembershipRemoved(+ eventEmitter,+ {+ groupId,+ orgIds: await groupDAL.findGroupOrgIds(groupId, tx),+ actors: toOrgMembershipActors({ userIds: [userId] })+ },+ tx+ );+ }});await createGithubOrgSyncAuditLogs({@@ -1120,6 +1141,7 @@ export const githubOrgSyncServiceFactory = ({const { usersToAdd, membershipsToRemove } = resolveMembershipChanges(latestMemberships);if (usersToAdd.length > 0) {+ await orgDAL.lockActorsForOrgAccess(usersToAdd, tx);await userGroupMembershipDAL.insertMany(usersToAdd.map((userId) => ({userId,@@ -1144,6 +1166,15 @@ export const githubOrgSyncServiceFactory = ({.map((membership) => activeMembersById.get(membership.orgMembershipId)?.user?.id).filter(Boolean) as string[];await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds: removedUserIds }, tx);+ await emitGroupMembershipRemoved(+ eventEmitter,+ {+ groupId: team.id,+ orgIds: await groupDAL.findGroupOrgIds(team.id, tx),+ actors: toOrgMembershipActors({ userIds: removedUserIds })+ },+ tx+ );updatedTeams.add(teamName);}diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 08fcc7c071..83ae3804c1 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -1515,7 +1515,9 @@ export const registerRoutes = async (membershipGroupDAL,usageMeteringService,alertChannelRecipientDAL,- auditLogService+ auditLogService,+ orgDAL,+ eventEmitter: eventOutboxService});// gitHubAppService is created after gatewayPoolService (below) due to dependency on gateway services@@ -1779,7 +1781,10 @@ export const registerRoutes = async (usageMeteringService,alertChannelRecipientDAL,pamSessionDAL,- gatewayV2Service: deferredGatewayV2Service+ gatewayV2Service: deferredGatewayV2Service,+ userGroupMembershipDAL,+ projectAccessRevokeService,+ eventEmitter: eventOutboxService});const offlineUsageReportService = offlineUsageReportServiceFactory({diff --git a/backend/src/services/super-admin/super-admin-service.ts b/backend/src/services/super-admin/super-admin-service.tsindex c325158ed4..30b54bf757 100644--- a/backend/src/services/super-admin/super-admin-service.ts+++ b/backend/src/services/super-admin/super-admin-service.ts@@ -10,6 +10,7 @@ import {import { TEmailDomainDALFactory } from "@app/ee/services/email-domain/email-domain-dal";import { EmailDomainStatus } from "@app/ee/services/email-domain/email-domain-types";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";import { getEnforcedIdentityLimit } from "@app/ee/services/license/license-fns";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { terminatePamSessionsForUsers } from "@app/ee/services/pam-session/pam-session-access-fns";@@ -49,6 +50,7 @@ import { TAlertChannelRecipientDALFactory } from "../alert/alert-channel-recipieimport { AlertPrincipalType } from "../alert/alert-types";import { TAuthLoginFactory } from "../auth/auth-login-service";import { ActorType, AuthMethod } from "../auth/auth-type";+import { TEventEmitter } from "../event-outbox/event-outbox-types";import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TIdentityTokenAuthDALFactory } from "../identity-token-auth/identity-token-auth-dal";import { KMS_ROOT_CONFIG_UUID } from "../kms/kms-fns";@@ -56,10 +58,12 @@ import { TKmsRootConfigDALFactory } from "../kms/kms-root-config-dal";import { TKmsServiceFactory } from "../kms/kms-service";import { RootKeyEncryptionStrategy } from "../kms/kms-types";import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";+import { TProjectAccessRevokeServiceFactory } from "../membership/project-access-revoke-service";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";import { TMembershipUserDALFactory } from "../membership-user/membership-user-dal";import { TMicrosoftTeamsServiceFactory } from "../microsoft-teams/microsoft-teams-service";import { TOrgDALFactory } from "../org/org-dal";+import { deleteOrgMembershipsFn } from "../org/org-fns";import { TOrgServiceFactory } from "../org/org-service";import { TUserDALFactory } from "../user/user-dal";import { TUserAliasDALFactory } from "../user-alias/user-alias-dal";@@ -97,7 +101,10 @@ type TSuperAdminServiceFactoryDep = {alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients" | "deleteByPrincipals">;pamSessionDAL: Pick<TPamSessionDALFactory, "findLiveByOrgAndUserIds" | "update">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;- userAliasDAL: Pick<TUserAliasDALFactory, "findOne">;+ userAliasDAL: Pick<TUserAliasDALFactory, "findOne" | "delete">;+ userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "delete">;+ projectAccessRevokeService: Pick<TProjectAccessRevokeServiceFactory, "revokeActorsInOrgs">;+ eventEmitter: TEventEmitter;emailDomainDAL: TEmailDomainDALFactory;authService: Pick<TAuthLoginFactory, "generateUserTokens">;kmsService: Pick<TKmsServiceFactory, "encryptWithRootKey" | "decryptWithRootKey" | "updateEncryptionStrategy">;@@ -178,7 +185,10 @@ export const superAdminServiceFactory = ({usageMeteringService,alertChannelRecipientDAL,pamSessionDAL,- gatewayV2Service+ gatewayV2Service,+ userGroupMembershipDAL,+ projectAccessRevokeService,+ eventEmitter}: TSuperAdminServiceFactoryDep) => {const initServerCfg = async () => {// TODO(akhilmhdh): bad pattern time less change this later to me itself@@ -1081,23 +1091,22 @@ export const superAdminServiceFactory = ({if (!membershipRole) {throw new NotFoundError({ name: "Membership Role", message: "Membership role not found" });}- const organizationMembership = await membershipUserDAL.transaction(async (tx) => {- const [deletedMembership] = await membershipUserDAL.delete(- {- scopeOrgId: organizationId,- scope: AccessScope.Organization,- id: membershipId- },- tx- );-- if (deletedMembership?.actorUserId) {- await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds: [deletedMembership.actorUserId] }, tx);- }-- return deletedMembership;+ const [organizationMembership] = await deleteOrgMembershipsFn({+ orgMembershipIds: [membershipId],+ orgId: organizationId,+ orgDAL,+ userAliasDAL,+ licenseService,+ userId: actorType === ActorType.USER ? actorId : undefined,+ membershipUserDAL,+ userGroupMembershipDAL,+ projectAccessRevokeService,+ eventEmitter});+ usageMeteringService.emit(organizationId, SecretIdentities.key);+ usageMeteringService.emit(organizationId, PamIdentities.key);+ usageMeteringService.emit(organizationId, AgentVaultIdentities.key);return { ...organizationMembership, role: membershipRole.role, orgId: organizationId };};