Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

26.1 KB
Raw Blame
import { Knex } from "knex";

import { AccessScope, ProjectVersion, SecretKeyEncoding, TableName, TUsers } from "@app/db/schemas";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, ForbiddenRequestError, NotFoundError, ScimRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";
import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";
import { lockMembershipsById } from "@app/services/membership/membership-dal";
import { emitGroupMembershipRemoved, toOrgMembershipActors } from "@app/services/org/org-membership-events";

import { terminatePamSessionsLosingGroupAccess } from "../pam-session/pam-session-access-fns";
import {
  TAddIdentitiesToGroup,
  TAddUsersToGroup,
  TAddUsersToGroupByUserIds,
  TConvertPendingGroupAdditionsToGroupMemberships,
  TRemoveIdentitiesFromGroup,
  TRemoveUsersFromGroupByUserIds
} from "./group-types";

const addAcceptedUsersToGroup = async ({
  userIds,
  group,
  userGroupMembershipDAL,
  userDAL,
  membershipGroupDAL,
  projectKeyDAL,
  projectDAL,
  projectBotDAL,
  tx
}: TAddUsersToGroup) => {
  const users = await userDAL.findUserEncKeyByUserIdsBatch(
    {
      userIds
    },
    tx
  );
  if (!users.length) return;

  await userGroupMembershipDAL.insertMany(
    users.map((user) => ({
      userId: user.id,
      groupId: group.id,
      isPending: false
    })),
    tx
  );

  // check which projects the group is part of
  const projectIds = Array.from(
    new Set(
      (
        await membershipGroupDAL.find(
          {
            actorGroupId: group.id,
            scopeOrgId: group.orgId,
            scope: AccessScope.Project
          },
          { tx }
        )
      ).map((gp) => gp.scopeProjectId as string)
    )
  );

  const keys = await projectKeyDAL.find(
    {
      $in: {
        projectId: projectIds,
        receiverId: users.map((u) => u.id)
      }
    },
    { tx }
  );

  const userKeysSet = new Set(keys.map((k) => `${k.projectId}-${k.receiverId}`));

  for await (const projectId of projectIds) {
    const project = await projectDAL.findById(projectId, tx);
    if (!project) {
      throw new NotFoundError({
        message: `Failed to find project with ID '${projectId}'`
      });
    }

    if (project.version !== ProjectVersion.V1 && project.version !== ProjectVersion.V2) {
      // eslint-disable-next-line no-continue
      continue;
    }

    const usersMissingProjectKey = users.filter((u) => !userKeysSet.has(`${projectId}-${u.id}`));

    // SSO-only users never get a key pair, and nothing shares the key later, so failing here would lock them
    // out of the whole org (or roll back the login) over one legacy project they could not use anyway.
    const usersToAddProjectKeyFor = usersMissingProjectKey.filter((u) => {
      if (u.publicKey) return true;
      logger.warn(
        `Skipping legacy project key share for a user without a public key [userId=${u.id}] [projectId=${projectId}] [groupId=${group.id}]`
      );
      return false;
    });

    if (usersToAddProjectKeyFor.length) {
      // there are users who need to be shared keys
      // process adding bulk users to projects for each project individually
      const ghostUser = await projectDAL.findProjectGhostUser(projectId, tx);

      if (!ghostUser) {
        throw new NotFoundError({
          message: `Failed to find project owner of project with ID '${projectId}'`
        });
      }

      const ghostUserLatestKey = await projectKeyDAL.findLatestProjectKey(ghostUser.id, projectId, tx);

      if (!ghostUserLatestKey) {
        throw new NotFoundError({
          message: `Failed to find project owner's latest key in project with ID '${projectId}'`
        });
      }

      if (!ghostUserLatestKey.sender.publicKey) {
        throw new NotFoundError({
          message: `Failed to find project owner's public key in project with ID '${projectId}'`
        });
      }

      const bot = await projectBotDAL.findOne({ projectId }, tx);

      if (!bot) {
        throw new NotFoundError({
          message: `Failed to find project bot in project with ID '${projectId}'`
        });
      }

      recordLegacyRootKeyUsageMetric({ operation: "decrypt", surface: "project_bot" });
      logger.info(`Legacy root key used to read a project bot key for group sync [projectId=${project.id}]`);
      const botPrivateKey = crypto
        .encryption()
        .symmetric()
        .decryptWithRootEncryptionKey({
          keyEncoding: bot.keyEncoding as SecretKeyEncoding,
          iv: bot.iv,
          tag: bot.tag,
          ciphertext: bot.encryptedPrivateKey
        });

      const plaintextProjectKey = crypto.encryption().asymmetric().decrypt({
        ciphertext: ghostUserLatestKey.encryptedKey,
        nonce: ghostUserLatestKey.nonce,
        publicKey: ghostUserLatestKey.sender.publicKey,
        privateKey: botPrivateKey
      });

      const projectKeysToAdd = usersToAddProjectKeyFor.map((user) => {
        const { ciphertext: encryptedKey, nonce } = crypto
          .encryption()
          .asymmetric()
          .encrypt(plaintextProjectKey, user.publicKey as string, botPrivateKey);
        return {
          encryptedKey,
          nonce,
          senderId: ghostUser.id,
          receiverId: user.id,
          projectId
        };
      });

      await projectKeyDAL.insertMany(projectKeysToAdd, tx);
    }
  }
};

/**
 * Add users with user ids [userIds] to group [group].
 * - Users may or may not have finished completing their accounts; this function will
 * handle both adding users to groups directly and via pending group additions.
 * @param {group} group - group to add user(s) to
 * @param {string[]} userIds - id(s) of user(s) to add to group
 */
export const addUsersToGroupByUserIds = async ({
  group,
  userIds,
  userDAL,
  userGroupMembershipDAL,
  orgDAL,
  projectKeyDAL,
  projectDAL,
  projectBotDAL,
  tx: outerTx,
  membershipGroupDAL,
  shouldFailOnMissingMembers = true,
  usageMeteringService
}: TAddUsersToGroupByUserIds) => {
  const processAddition = async (tx: Knex) => {
    if (userIds.length === 0) {
      return [];
    }

    const foundMembers = await userDAL.find(
      {
        $in: {
          id: userIds
        }
      },
      { tx }
    );

    const foundMembersIdsSet = new Set(foundMembers.map((member) => member.id));

    const isCompleteMatch = userIds.every((userId) => foundMembersIdsSet.has(userId));

    if (!isCompleteMatch) {
      throw new ScimRequestError({
        detail: "Members not found",
        status: 404
      });
    }

    // check if user(s) group membership(s) already exists
    const existingUserGroupMemberships = await userGroupMembershipDAL.find(
      {
        groupId: group.id,
        $in: {
          userId: userIds
        }
      },
      { tx }
    );

    const existingUserGroupMembershipsUserIdsSet = new Set(existingUserGroupMemberships.map((m) => m.userId));

    // Track which userIds we're actually processing (may be filtered for idempotent operations)
    let userIdsToProcess = userIds;

    if (existingUserGroupMemberships.length) {
      if (shouldFailOnMissingMembers) {
        throw new BadRequestError({
          message: `User(s) are already part of the group ${group.slug}`
        });
      }
      // filter out users already in group for idempotent operation
      const filteredFoundMembers = foundMembers.filter((m) => !existingUserGroupMembershipsUserIdsSet.has(m.id));
      if (filteredFoundMembers.length === 0) {
        return [];
      }
      // continue with filtered list
      foundMembers.length = 0;
      foundMembers.push(...filteredFoundMembers);
      userIdsToProcess = filteredFoundMembers.map((m) => m.id);
    }

    // check if all user(s) are part of the organization
    const existingUserOrgMemberships = await orgDAL.findMembership(
      {
        [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: group.orgId,
        scope: AccessScope.Organization,
        $in: {
          [`${TableName.Membership}.actorUserId` as "actorUserId"]: userIdsToProcess
        }
      },
      { tx }
    );

    const existingUserOrgMembershipsUserIdsSet = new Set(
      existingUserOrgMemberships.map((u) => u.actorUserId as string)
    );

    userIdsToProcess.forEach((userId) => {
      if (!existingUserOrgMembershipsUserIdsSet.has(userId))
        throw new ForbiddenRequestError({
          message: `User with id ${userId} is not part of the organization`
        });
    });

    await orgDAL.lockActorsForOrgAccess({ orgId: group.orgId, actorIds: foundMembers.map((member) => member.id) }, tx);

    const membersToAddToGroupNonPending: TUsers[] = [];
    const membersToAddToGroupPending: TUsers[] = [];

    foundMembers.forEach((member) => {
      if (member.isAccepted) {
        // add accepted member to group
        membersToAddToGroupNonPending.push(member);
      } else {
        // add incomplete member to pending group addition
        membersToAddToGroupPending.push(member);
      }
    });

    if (membersToAddToGroupNonPending.length) {
      await addAcceptedUsersToGroup({
        userIds: membersToAddToGroupNonPending.map((member) => member.id),
        group,
        userDAL,
        userGroupMembershipDAL,
        membershipGroupDAL,
        projectKeyDAL,
        projectDAL,
        projectBotDAL,
        tx
      });
    }

    if (membersToAddToGroupPending.length) {
      await userGroupMembershipDAL.insertMany(
        membersToAddToGroupPending.map((member) => ({
          userId: member.id,
          groupId: group.id,
          isPending: true
        })),
        tx
      );
    }

    // These users may now be in a secret-manager or PAM project through this group.
    usageMeteringService?.emit(group.orgId, SecretIdentities.key);
    usageMeteringService?.emit(group.orgId, PamIdentities.key);
    usageMeteringService?.emit(group.orgId, AgentVaultIdentities.key);
    return membersToAddToGroupNonPending.concat(membersToAddToGroupPending);
  };

  if (outerTx) {
    return processAddition(outerTx);
  }
  return userDAL.transaction(async (tx) => {
    return processAddition(tx);
  });
};

/**
 * Add identities with identity ids [identityIds] to group [group].
 * @param {group} group - group to add identity(s) to
 * @param {string[]} identityIds - id(s) of organization scoped identity(s) to add to group
 * @returns {Promise<{ id: string }[]>} - id(s) of added identity(s)
 */
export const addIdentitiesToGroup = async ({
  group,
  identityIds,
  identityDAL,
  identityGroupMembershipDAL,
  membershipDAL,
  orgDAL,
  usageMeteringService
}: TAddIdentitiesToGroup) => {
  const identityIdsSet = new Set(identityIds);
  const identityIdsArray = Array.from(identityIdsSet);

  // ensure all identities exist and belong to the org via org scoped membership
  const foundIdentitiesMemberships = await membershipDAL.find({
    scope: AccessScope.Organization,
    scopeOrgId: group.orgId,
    $in: {
      actorIdentityId: identityIdsArray
    }
  });

  const existingIdentityOrgMembershipsIdentityIdsSet = new Set(
    foundIdentitiesMemberships.map((u) => u.actorIdentityId as string)
  );

  identityIdsArray.forEach((identityId) => {
    if (!existingIdentityOrgMembershipsIdentityIdsSet.has(identityId)) {
      throw new ForbiddenRequestError({
        message: `Identity with id ${identityId} is not part of the organization`
      });
    }
  });

  // check if identity group membership already exists
  const existingIdentityGroupMemberships = await identityGroupMembershipDAL.find({
    groupId: group.id,
    $in: {
      identityId: identityIdsArray
    }
  });

  if (existingIdentityGroupMemberships.length) {
    throw new BadRequestError({
      message: `${identityIdsArray.length > 1 ? `Identities are` : `Identity is`} already part of the group ${group.slug}`
    });
  }

  return identityDAL.transaction(async (tx) => {
    await orgDAL.lockActorsForOrgAccess({ orgId: group.orgId, actorIds: identityIdsArray }, tx);

    await identityGroupMembershipDAL.insertMany(
      foundIdentitiesMemberships.map((membership) => ({
        identityId: membership.actorIdentityId as string,
        groupId: group.id
      })),
      tx
    );

    // These identities may now be in a secret-manager or PAM project through this group.
    usageMeteringService?.emit(group.orgId, SecretIdentities.key);
    usageMeteringService?.emit(group.orgId, PamIdentities.key);
    usageMeteringService?.emit(group.orgId, AgentVaultIdentities.key);
    return identityIdsArray.map((identityId) => ({ id: identityId }));
  });
};

/**
 * Remove users with user ids [userIds] from group [group].
 * - Users may be part of the group (non-pending + pending);
 * this function will handle both cases.
 * - Fire the returned sendPamCancellations once the transaction holding the removal commits.
 * @param {group} group - group to remove user(s) from
 * @param {string[]} userIds - id(s) of user(s) to remove from group
 * Cleans up projects in every org the group reaches, not just its home org.
 */
export const removeUsersFromGroupByUserIds = async ({
  group,
  userIds,
  actorId,
  userDAL,
  userGroupMembershipDAL,
  projectKeyDAL,
  additionalPrivilegeDAL,
  tx: outerTx,
  membershipGroupDAL,
  groupDAL,
  shouldFailOnMissingMembers = true,
  usageMeteringService,
  alertChannelRecipientDAL,
  eventEmitter,
  membershipDAL,
  membershipRoleDAL,
  pamAccountDAL,
  pamSessionDAL,
  gatewayV2Service
}: TRemoveUsersFromGroupByUserIds) => {
  const processRemoval = async (tx: Knex) => {
    if (userIds.length === 0) {
      return { users: [], sendPamCancellations: () => {} };
    }

    const foundMembers = await userDAL.find(
      {
        $in: {
          id: userIds
        }
      },
      { tx }
    );

    const foundMembersIdsSet = new Set(foundMembers.map((member) => member.id));

    const isCompleteMatch = userIds.every((userId) => foundMembersIdsSet.has(userId));

    if (!isCompleteMatch) {
      throw new ScimRequestError({
        detail: "Members not found",
        status: 404
      });
    }

    // check if user group membership already exists
    const existingUserGroupMemberships = await userGroupMembershipDAL.find(
      {
        groupId: group.id,
        $in: {
          userId: userIds
        }
      },
      { tx }
    );

    const existingUserGroupMembershipsUserIdsSet = new Set(existingUserGroupMemberships.map((u) => u.userId));

    const usersNotInGroup = userIds.filter((userId) => !existingUserGroupMembershipsUserIdsSet.has(userId));

    if (usersNotInGroup.length > 0) {
      if (shouldFailOnMissingMembers) {
        throw new ForbiddenRequestError({
          message: `User(s) are not part of the group ${group.slug}`
        });
      }
      // filter out users not in group for idempotent operation
      const filteredFoundMembers = foundMembers.filter((m) => existingUserGroupMembershipsUserIdsSet.has(m.id));
      if (filteredFoundMembers.length === 0) {
        return { users: [], sendPamCancellations: () => {} };
      }
      // continue with filtered list
      foundMembers.length = 0;
      foundMembers.push(...filteredFoundMembers);
    }

    const membersToRemoveFromGroupNonPending: TUsers[] = [];
    const membersToRemoveFromGroupPending: TUsers[] = [];

    foundMembers.forEach((member) => {
      if (member.isAccepted) {
        // remove accepted member from group
        membersToRemoveFromGroupNonPending.push(member);
      } else {
        // remove incomplete member from pending group addition
        membersToRemoveFromGroupPending.push(member);
      }
    });

    const groupProjectMemberships = await membershipGroupDAL.find(
      {
        scope: AccessScope.Project,
        actorGroupId: group.id
      },
      { tx }
    );
    const projectIds = Array.from(
      new Set(groupProjectMemberships.map((membership) => membership.scopeProjectId as string))
    );
    const lockedMemberships = await lockMembershipsById(
      groupProjectMemberships.map((membership) => membership.id),
      tx
    );
    const lockedProjectIds = new Set(
      lockedMemberships.flatMap((membership) => (membership.scopeProjectId ? [membership.scopeProjectId] : []))
    );

    if (membersToRemoveFromGroupNonPending.length) {
      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(
            {
              receiverId: userId,
              $in: {
                projectId: projectsToDeleteKeyFor
              }
            },
            tx
          );

          // additional privileges are keyed on actor + project, not membership, so leaving the
          // user's last route into these projects must reap them or they reactivate if the user
          // is ever re-added. Skip a project whose group membership was not locked: that row is
          // already gone, and deleting privileges for it would wipe a grant written after re-add.
          const projectsToDeletePrivilegesFor = projectsToDeleteKeyFor.filter((projectId) =>
            lockedProjectIds.has(projectId)
          );
          if (projectsToDeletePrivilegesFor.length) {
            await additionalPrivilegeDAL.delete(
              {
                actorUserId: userId,
                $in: {
                  projectId: projectsToDeletePrivilegesFor
                }
              },
              tx
            );
          }
        }

        await userGroupMembershipDAL.delete(
          {
            groupId: group.id,
            userId
          },
          tx
        );
      }
    }

    if (membersToRemoveFromGroupPending.length) {
      const pendingUserIds = membersToRemoveFromGroupPending.map((member) => member.id);
      const stillReach = await userGroupMembershipDAL.filterProjectsByUserMembership(
        pendingUserIds,
        group.id,
        projectIds,
        tx
      );

      for await (const userId of pendingUserIds) {
        const reachable = stillReach.get(userId);
        const projectsToReapGrantsFor = projectIds.filter((projectId) => !reachable?.has(projectId));

        const projectsToReapPrivilegesFor = projectsToReapGrantsFor.filter((projectId) =>
          lockedProjectIds.has(projectId)
        );
        if (projectsToReapPrivilegesFor.length) {
          await additionalPrivilegeDAL.delete(
            {
              actorUserId: userId,
              $in: {
                projectId: projectsToReapPrivilegesFor
              },
              $notNull: ["folderId"]
            },
            tx
          );
        }
      }

      await userGroupMembershipDAL.delete(
        {
          groupId: group.id,
          $in: {
            userId: pendingUserIds
          }
        },
        tx
      );
    }

    await alertChannelRecipientDAL.pruneOutOfScopeRecipients({ userIds: foundMembers.map((m) => m.id) }, tx);

    await emitGroupMembershipRemoved(
      eventEmitter,
      {
        groupId: group.id,
        orgIds: await groupDAL.findGroupOrgIds(group.id, tx),
        actors: toOrgMembershipActors({ userIds: foundMembers.map((m) => m.id) })
      },
      tx
    );

    const sendPamCancellations = await terminatePamSessionsLosingGroupAccess({
      userIds: foundMembers.map((m) => m.id),
      actorId,
      membershipDAL,
      membershipRoleDAL,
      pamAccountDAL,
      pamSessionDAL,
      userDAL,
      gatewayV2Service,
      tx
    });

    // These users may have left a secret-manager or PAM project they only reached through this group.
    usageMeteringService?.emit(group.orgId, SecretIdentities.key);
    usageMeteringService?.emit(group.orgId, PamIdentities.key);
    usageMeteringService?.emit(group.orgId, AgentVaultIdentities.key);
    return { users: membersToRemoveFromGroupNonPending.concat(membersToRemoveFromGroupPending), sendPamCancellations };
  };

  if (outerTx) {
    return processRemoval(outerTx);
  }
  return userDAL.transaction(async (tx) => {
    return processRemoval(tx);
  });
};

/**
 * Remove identities with identity ids [identityIds] from group [group].
 * @param {group} group - group to remove identity(s) from
 * @param {string[]} identityIds - id(s) of identity(s) to remove from group
 * @returns {Promise<{ id: string }[]>} - id(s) of removed identity(s)
 */
export const removeIdentitiesFromGroup = async ({
  group,
  identityIds,
  actorId,
  identityDAL,
  membershipDAL,
  groupDAL,
  identityGroupMembershipDAL,
  additionalPrivilegeDAL,
  usageMeteringService,
  eventEmitter,
  membershipRoleDAL,
  pamAccountDAL,
  pamSessionDAL,
  userDAL,
  gatewayV2Service
}: TRemoveIdentitiesFromGroup) => {
  const identityIdsSet = new Set(identityIds);
  const identityIdsArray = Array.from(identityIdsSet);

  // ensure all identities exist and belong to the org via org scoped membership
  const foundIdentitiesMemberships = await membershipDAL.find({
    scope: AccessScope.Organization,
    scopeOrgId: group.orgId,
    $in: {
      actorIdentityId: identityIdsArray
    }
  });

  const foundIdentitiesMembershipsIdentityIdsSet = new Set(
    foundIdentitiesMemberships.map((u) => u.actorIdentityId as string)
  );

  if (foundIdentitiesMembershipsIdentityIdsSet.size !== identityIdsArray.length) {
    throw new NotFoundError({
      message: `Machine identities not found`
    });
  }

  // check if identity group membership already exists
  const existingIdentityGroupMemberships = await identityGroupMembershipDAL.find({
    groupId: group.id,
    $in: {
      identityId: identityIdsArray
    }
  });

  const existingIdentityGroupMembershipsIdentityIdsSet = new Set(
    existingIdentityGroupMemberships.map((u) => u.identityId)
  );

  identityIdsArray.forEach((identityId) => {
    if (!existingIdentityGroupMembershipsIdentityIdsSet.has(identityId)) {
      throw new ForbiddenRequestError({
        message: `Machine identities are not part of the group ${group.slug}`
      });
    }
  });
  return identityDAL.transaction(async (tx) => {
    const projectIds = Array.from(
      new Set(
        (
          await membershipDAL.find(
            {
              scope: AccessScope.Project,
              actorGroupId: group.id
            },
            { tx }
          )
        ).map((gp) => gp.scopeProjectId as string)
      )
    );

    const stillReach = await identityGroupMembershipDAL.filterProjectsByIdentityMembership(
      identityIdsArray,
      group.id,
      projectIds,
      tx
    );

    for await (const identityId of identityIdsArray) {
      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 the
        // identity's last route into these projects must reap them or they reactivate if the
        // identity is ever re-added
        await additionalPrivilegeDAL.delete(
          {
            actorIdentityId: identityId,
            $in: {
              projectId: projectsToReapPrivilegesFor
            }
          },
          tx
        );
      }
    }

    await identityGroupMembershipDAL.delete(
      {
        groupId: group.id,
        $in: {
          identityId: identityIdsArray
        }
      },
      tx
    );

    await emitGroupMembershipRemoved(
      eventEmitter,
      {
        groupId: group.id,
        orgIds: await groupDAL.findGroupOrgIds(group.id, tx),
        actors: toOrgMembershipActors({ identityIds: identityIdsArray })
      },
      tx
    );

    const sendPamCancellations = await terminatePamSessionsLosingGroupAccess({
      userIds: [],
      identityIds: identityIdsArray,
      actorId,
      membershipDAL,
      membershipRoleDAL,
      pamAccountDAL,
      pamSessionDAL,
      userDAL,
      gatewayV2Service,
      tx
    });

    // These identities may have left a secret-manager or PAM project they only reached through this group.
    usageMeteringService?.emit(group.orgId, SecretIdentities.key);
    usageMeteringService?.emit(group.orgId, PamIdentities.key);
    usageMeteringService?.emit(group.orgId, AgentVaultIdentities.key);
    return { identities: identityIdsArray.map((identityId) => ({ id: identityId })), sendPamCancellations };
  });
};

/**
 * Convert pending group additions for users with ids [userIds] to group memberships.
 * @param {string[]} userIds - id(s) of user(s) to try to convert pending group additions to group memberships
 */
export const convertPendingGroupAdditionsToGroupMemberships = async ({
  userIds,
  userDAL,
  userGroupMembershipDAL,
  projectKeyDAL,
  projectDAL,
  projectBotDAL,
  tx: outerTx,
  membershipGroupDAL
}: TConvertPendingGroupAdditionsToGroupMemberships) => {
  const processConversion = async (tx: Knex) => {
    const users = await userDAL.find(
      {
        $in: {
          id: userIds
        }
      },
      { tx }
    );

    const usersUserIdsSet = new Set(users.map((u) => u.id));
    userIds.forEach((userId) => {
      if (!usersUserIdsSet.has(userId)) {
        throw new NotFoundError({
          message: `Failed to find user with id ${userId}`
        });
      }
    });

    users.forEach((user) => {
      if (!user.isAccepted) {
        throw new BadRequestError({
          message: `Failed to convert pending group additions to group memberships for user ${user.username} because they have not confirmed their account`
        });
      }
    });

    const pendingGroupAdditions = await userGroupMembershipDAL.deletePendingUserGroupMembershipsByUserIds(userIds, tx);

    for await (const pendingGroupAddition of pendingGroupAdditions) {
      await addAcceptedUsersToGroup({
        userIds: [pendingGroupAddition.user.id],
        group: pendingGroupAddition.group,
        userDAL,
        userGroupMembershipDAL,
        membershipGroupDAL,
        projectKeyDAL,
        projectDAL,
        projectBotDAL,
        tx
      });
    }
  };

  if (outerTx) {
    return processConversion(outerTx);
  }
  return userDAL.transaction(async (tx) => {
    await processConversion(tx);
  });
};