Skip to content

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

57.4 KB
Raw Blame
import { ForbiddenError, MongoAbility } from "@casl/ability";
import slugify from "@sindresorhus/slugify";
import { Knex } from "knex";

import {
  AccessScope,
  OrganizationActionScope,
  OrgMembershipRole,
  OrgMembershipStatus,
  ProjectType,
  TableName,
  TOidcConfigs,
  TSamlConfigs
} from "@app/db/schemas";
import { bootstrapAgentVaultProject } from "@app/ee/services/agent-vault-project/agent-vault-project-bootstrap";
import { TAuditLogSettingsServiceFactory } from "@app/ee/services/audit-log/audit-log-settings-service";
import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { TLdapConfigDALFactory } from "@app/ee/services/ldap-config/ldap-config-dal";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TOidcConfigDALFactory } from "@app/ee/services/oidc/oidc-config-dal";
import { bootstrapPamProject } from "@app/ee/services/pam-project/pam-project-bootstrap";
import { terminatePamSessionsForUsers } from "@app/ee/services/pam-session/pam-session-access-fns";
import { TPamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";
import {
  OrgPermissionActions,
  OrgPermissionGroupActions,
  OrgPermissionMemberActions,
  OrgPermissionSecretShareAction,
  OrgPermissionSsoActions,
  OrgPermissionSubjects
} from "@app/ee/services/permission/org-permission";
import { assertRoleSetBoundary } from "@app/ee/services/permission/permission-fns";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { TSamlConfigDALFactory } from "@app/ee/services/saml-config/saml-config-dal";
import { bootstrapSecretScanningProject } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-project-bootstrap";
import { PgSqlLock } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import { generateUserSrpKeys } from "@app/lib/crypto/srp";
import { applyJitter } from "@app/lib/dates";
import { delay as delayMs } from "@app/lib/delay";
import {
  BadRequestError,
  ConflictError,
  ForbiddenRequestError,
  NotFoundError,
  UnauthorizedError
} from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TOrgMembershipDALFactory } from "@app/services/org-membership/org-membership-dal";
import { getDefaultOrgMembershipRoleForUpdateOrg } from "@app/services/org/org-role-fns";
import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";

import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
import { TokenType } from "../auth-token/auth-token-types";
import { TAuthLoginFactory } from "../auth/auth-login-service";
import {
  ActorAuthMethod,
  ActorType,
  AuthMethod,
  AuthModeJwtTokenPayload,
  AuthTokenType,
  SsoMfaTrust
} from "../auth/auth-type";
import { bootstrapCertManagerProject } from "../cert-manager-instance/cert-manager-project-bootstrap";
import { TCertificatePolicyDALFactory } from "../certificate-policy/certificate-policy-dal";
import { TEventEmitter } from "../event-outbox/event-outbox-types";
import { TIdentityMetadataDALFactory } from "../identity/identity-metadata-dal";
import { TMembershipUserDALFactory } from "../membership-user/membership-user-dal";
import { assertWillRetainOrgAdmin } from "../membership-user/membership-user-fns";
import { TMembershipDALFactory } from "../membership/membership-dal";
import { resolveMembershipRoleSlugs, roleNeedsPrivilegeBoundary } from "../membership/membership-fns";
import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";
import { TProjectAccessRevokeServiceFactory } from "../membership/project-access-revoke-service";
import { TProjectBotServiceFactory } from "../project-bot/project-bot-service";
import { TProjectMembershipDALFactory } from "../project-membership/project-membership-dal";
import { TProjectDALFactory } from "../project/project-dal";
import { TReminderServiceFactory } from "../reminder/reminder-types";
import { TRoleDALFactory } from "../role/role-dal";
import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
import { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-dal";
import { TSecretDALFactory } from "../secret/secret-dal";
import { fnDeleteProjectSecretReminders } from "../secret/secret-fns";
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
import { TUserDALFactory } from "../user/user-dal";
import { TIncidentContactsDALFactory } from "./incident-contacts-dal";
import { TOrgDALFactory } from "./org-dal";
import { deleteOrgMembershipsFn } from "./org-fns";
import {
  TDeleteOrgMembershipDTO,
  TDeleteOrgMembershipsDTO,
  TFindAllOrgMembersDTO,
  TFindAllWorkspacesDTO,
  TFindOrgMembersByEmailDTO,
  TGetOrgGroupsDTO,
  TGetOrgMembershipDTO,
  TListProjectMembershipsByOrgMembershipIdDTO,
  TOrgWithSubOrgs,
  TResendOrgMemberInvitationDTO,
  TUpdateOrgDTO,
  TUpdateOrgMembershipDTO,
  TUpgradePrivilegeSystemDTO,
  TVerifyUserToOrgDTO
} from "./org-types";

type TOrgServiceFactoryDep = {
  userAliasDAL: Pick<TUserAliasDALFactory, "delete">;
  secretDAL: Pick<TSecretDALFactory, "find">;
  secretV2BridgeDAL: Pick<TSecretV2BridgeDALFactory, "find" | "invalidateSecretCacheByProjectId">;
  folderDAL: Pick<TSecretFolderDALFactory, "findByProjectId">;
  orgDAL: TOrgDALFactory;
  roleDAL: TRoleDALFactory;
  userDAL: TUserDALFactory;
  groupDAL: TGroupDALFactory;
  projectDAL: TProjectDALFactory;
  identityMetadataDAL: Pick<TIdentityMetadataDALFactory, "delete" | "insertMany" | "transaction">;
  membershipUserDAL: TMembershipUserDALFactory;
  membershipDAL: TMembershipDALFactory;
  projectMembershipDAL: Pick<
    TProjectMembershipDALFactory,
    "findProjectMembershipsByUserId" | "findProjectMembershipsByUserIds"
  >;
  orgMembershipDAL: Pick<
    TOrgMembershipDALFactory,
    "findOrgMembershipById" | "findRecentInvitedMemberships" | "updateLastInvitedAtByIds"
  >;
  membershipRoleDAL: TMembershipRoleDALFactory;
  incidentContactDAL: TIncidentContactsDALFactory;
  samlConfigDAL: Pick<TSamlConfigDALFactory, "findOne">;
  oidcConfigDAL: Pick<TOidcConfigDALFactory, "findOne">;
  ldapConfigDAL: Pick<TLdapConfigDALFactory, "findOne">;
  smtpService: TSmtpService;
  tokenService: TAuthTokenServiceFactory;
  permissionService: TPermissionServiceFactory;
  licenseService: Pick<
    TLicenseServiceFactory,
    "getPlan" | "updateSubscriptionOrgMemberCount" | "cancelOrgSubscription"
  >;
  projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;
  loginService: Pick<TAuthLoginFactory, "generateUserTokens">;
  reminderService: Pick<TReminderServiceFactory, "deleteReminderBySecretId">;
  userGroupMembershipDAL: TUserGroupMembershipDALFactory;
  projectAccessRevokeService: Pick<TProjectAccessRevokeServiceFactory, "revokeActorsInOrgs">;
  auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
  pamSessionDAL: Pick<TPamSessionDALFactory, "findLiveByOrgAndUserIds" | "update">;
  gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
  certificatePolicyDAL: Pick<TCertificatePolicyDALFactory, "create">;
  usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;
  auditLogSettingsService: Pick<TAuditLogSettingsServiceFactory, "invalidateCache">;
  eventEmitter: TEventEmitter;
};

export type TOrgServiceFactory = ReturnType<typeof orgServiceFactory>;

export const orgServiceFactory = ({
  userAliasDAL,
  orgDAL,
  secretDAL,
  secretV2BridgeDAL,
  folderDAL,
  userDAL,
  groupDAL,
  roleDAL,
  incidentContactDAL,
  permissionService,
  smtpService,
  projectDAL,
  projectMembershipDAL,
  orgMembershipDAL,
  tokenService,
  licenseService,
  samlConfigDAL,
  oidcConfigDAL,
  ldapConfigDAL,
  identityMetadataDAL,
  projectBotService,
  loginService,
  reminderService,
  membershipRoleDAL,
  membershipUserDAL,
  membershipDAL,
  userGroupMembershipDAL,
  projectAccessRevokeService,
  auditLogService,
  certificatePolicyDAL,
  usageMeteringService,
  pamSessionDAL,
  gatewayV2Service,
  auditLogSettingsService,
  eventEmitter
}: TOrgServiceFactoryDep) => {
  /*
   * Get organization details by the organization id
   * */
  const findOrganizationById = async ({
    userId,
    orgId,
    actorAuthMethod,
    rootOrgId,
    actorOrgId
  }: {
    userId: string;
    orgId: string;
    actorAuthMethod: ActorAuthMethod;
    rootOrgId: string;
    actorOrgId: string;
  }) => {
    await permissionService.getOrgPermission({
      actor: ActorType.USER,
      actorId: userId,
      orgId,
      actorAuthMethod,
      actorOrgId,
      scope: OrganizationActionScope.Any
    });
    const appCfg = getConfig();
    const hasSubOrg = rootOrgId !== actorOrgId;

    const org = await requestMemoize(requestMemoKeys.orgFindOrgById(rootOrgId), () => orgDAL.findOrgById(rootOrgId));
    if (!org) throw new NotFoundError({ message: `Organization with ID '${rootOrgId}' not found` });

    let subOrg;
    if (hasSubOrg) {
      subOrg = await orgDAL.findOne({ rootOrgId, id: actorOrgId });

      if (!subOrg) throw new NotFoundError({ message: `Sub-organization with ID '${actorOrgId}' not found` });
    }

    const data = hasSubOrg && subOrg ? subOrg : org;

    const pamProjects = await projectDAL.find(
      { orgId: data.id, type: ProjectType.PAM },
      { sort: [["createdAt", "desc"]], limit: 1 }
    );

    const agentVaultProjects = await projectDAL.find(
      { orgId: data.id, type: ProjectType.AgentVault },
      { sort: [["createdAt", "desc"]], limit: 1 }
    );

    return {
      ...data,
      userTokenExpiration: data.userTokenExpiration || appCfg.JWT_REFRESH_LIFETIME,
      pamProjectId: pamProjects[0]?.id ?? null,
      agentVaultProjectId: agentVaultProjects[0]?.id ?? null
    };
  };

  /*
   * Get all organization a user part of
   * */
  const findAllOrganizationOfUser = async (userId: string) => {
    const orgs = await orgDAL.findAllOrgsByUserId(userId);

    // Filter out orgs where the membership object is an invitation
    return orgs.filter((org) => org.userStatus !== "invited");
  };

  const findAllAccessibleOrganizationsWithSubOrgs = async (userId: string): Promise<TOrgWithSubOrgs[]> => {
    return orgDAL.listOrganizationsWithSubOrgs({ actorId: userId });
  };

  /*
   * Get all organization an identity is part of
   * */
  const findIdentityOrganization = async (identityId: string) => {
    const org = await orgDAL.findIdentityOrganization(identityId);

    return org;
  };
  /*
   * Get all organization members
   * */
  const findAllOrgMembers = async ({ actor, actorId, orgId, actorAuthMethod, actorOrgId }: TFindAllOrgMembersDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId,
      scope: OrganizationActionScope.Any
    });

    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionMemberActions.Read, OrgPermissionSubjects.Member);

    const members = await orgDAL.findAllOrgMembers(orgId);
    return members;
  };

  // Group names and roles only go to callers who can read groups; the list itself just needs member read.
  const listOrgUserAccess = async ({ actor, actorId, orgId, actorAuthMethod, actorOrgId }: TFindAllOrgMembersDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId,
      scope: OrganizationActionScope.Any
    });

    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionMemberActions.Read, OrgPermissionSubjects.Member);
    const canReadGroups = permission.can(OrgPermissionGroupActions.Read, OrgPermissionSubjects.Groups);

    const [members, groupAccess] = await Promise.all([
      orgDAL.findAllOrgMembers(orgId),
      orgDAL.findAllOrgGroupUserAccess(orgId)
    ]);

    const groupsByUserId = new Map(groupAccess.map(({ user, groups }) => [user.id, groups]));
    const groupsFor = (userId: string) => (canReadGroups ? (groupsByUserId.get(userId) ?? []) : []);
    const directUserIds = new Set(members.map((member) => member.user.id));

    return [
      ...members.map(({ user, ...membership }) => ({
        user,
        membership: { ...membership, status: membership.status || OrgMembershipStatus.Accepted },
        groups: groupsFor(user.id)
      })),
      ...groupAccess
        .filter(({ user }) => !directUserIds.has(user.id))
        .map(({ user }) => ({ user, membership: null, groups: groupsFor(user.id) }))
    ];
  };

  const getOrgGroups = async ({ actor, actorId, orgId, actorAuthMethod, actorOrgId }: TGetOrgGroupsDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId,
      scope: OrganizationActionScope.Any
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGroupActions.Read, OrgPermissionSubjects.Groups);
    const groups = await groupDAL.findByOrgId(orgId);
    return groups;
  };

  const findOrgMembersByUsername = async ({
    actor,
    actorId,
    actorOrgId,
    actorAuthMethod,
    orgId,
    emails
  }: TFindOrgMembersByEmailDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId,
      scope: OrganizationActionScope.Any
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionMemberActions.Read, OrgPermissionSubjects.Member);

    const members = await orgDAL.findOrgMembersByUsername(orgId, emails);

    return members;
  };

  const findOrgBySlug = async (slug: string) => {
    const org = await orgDAL.findOrgBySlug(slug);
    if (!org) {
      throw new NotFoundError({ message: `Organization with slug '${slug}' not found` });
    }

    return org;
  };

  const findAllWorkspaces = async ({ actor, actorId, orgId }: TFindAllWorkspacesDTO) => {
    if (actor === ActorType.USER) {
      const workspaces = await projectDAL.findUserProjects(actorId, orgId);
      return workspaces;
    }

    if (actor === ActorType.IDENTITY) {
      const workspaces = await projectDAL.findIdentityProjects(actorId, orgId);
      return workspaces;
    }

    throw new BadRequestError({ message: "Invalid actor type" });
  };

  const addGhostUser = async (orgId: string, tx?: Knex) => {
    const email = `sudo-${alphaNumericNanoId(16)}-${orgId}@infisical.com`; // We add a nanoid because the email is unique. And we have to create a new ghost user each time, so we can have access to the private key.

    const password = crypto.randomBytes(128).toString("hex");

    const user = await userDAL.create(
      {
        isGhost: true,
        authMethods: [AuthMethod.EMAIL],
        username: email,
        email,
        isAccepted: true
      },
      tx
    );

    const encKeys = await generateUserSrpKeys(email, password);

    await userDAL.upsertUserEncryptionKey(
      user.id,
      {
        encryptionVersion: 2,
        publicKey: encKeys.publicKey
      },
      tx
    );

    const createMembershipData = {
      scopeOrgId: orgId,
      scope: AccessScope.Organization,
      actorUserId: user.id,
      status: OrgMembershipStatus.Accepted,
      isActive: true
    };

    const membership = await orgDAL.createMembership(createMembershipData, tx);
    await membershipRoleDAL.create(
      {
        membershipId: membership.id,
        role: OrgMembershipRole.Admin
      },
      tx
    );

    return {
      user,
      keys: encKeys
    };
  };

  const upgradePrivilegeSystem = async ({
    actorId,
    actorOrgId,
    actorAuthMethod,
    orgId
  }: TUpgradePrivilegeSystemDTO) => {
    const { hasRole } = await permissionService.getOrgPermission({
      actor: ActorType.USER,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId,
      scope: OrganizationActionScope.ParentOrganization
    });

    if (!hasRole(OrgMembershipRole.Admin)) {
      throw new ForbiddenRequestError({
        message: "Insufficient privileges - only the organization admin can upgrade the privilege system."
      });
    }

    const upgradedOrg = await orgDAL.transaction(async (tx) => {
      const org = await orgDAL.findById(actorOrgId, tx);
      if (org.shouldUseNewPrivilegeSystem) {
        throw new BadRequestError({
          message: "Privilege system already upgraded"
        });
      }

      const user = await userDAL.findById(actorId, tx);
      if (!user) {
        throw new NotFoundError({ message: `User with ID '${actorId}' not found` });
      }

      return orgDAL.updateById(
        actorOrgId,
        {
          shouldUseNewPrivilegeSystem: true,
          privilegeUpgradeInitiatedAt: new Date(),
          privilegeUpgradeInitiatedByUsername: user.username
        },
        tx
      );
    });

    // Denials only get recorded on the new privilege system, so bust the cache or denials right
    // after upgrading get missed. Never throws, since the upgrade has already committed.
    await auditLogSettingsService.invalidateCache(actorOrgId);

    return upgradedOrg;
  };

  /*
   * Update organization details
   * */
  const updateOrg = async ({
    actor,
    actorId,
    actorOrgId,
    actorAuthMethod,
    orgId,
    data: {
      name,
      slug,
      authEnforced,
      googleSsoAuthEnforced,
      scimEnabled,
      defaultMembershipRoleSlug,
      enforceMfa,
      selectedMfaMethod,
      ssoMfaTrust,
      allowSecretSharingOutsideOrganization,
      bypassOrgAuthEnabled,
      userTokenExpiration,
      secretsProductEnabled,
      pkiProductEnabled,
      kmsProductEnabled,
      scannerProductEnabled,
      shareSecretsProductEnabled,
      maxSharedSecretLifetime,
      maxSharedSecretViewLimit,
      blockDuplicateSecretSyncDestinations,
      allowCrossProjectSecretSharing,
      requireGatewayPools,
      secretShareBrandConfig
    }
  }: TUpdateOrgDTO) => {
    const appCfg = getConfig();
    const { permission } = await permissionService.getOrgPermission({
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId,
      scope: OrganizationActionScope.ParentOrganization
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);

    if (allowSecretSharingOutsideOrganization !== undefined) {
      ForbiddenError.from(permission).throwUnlessCan(
        OrgPermissionSecretShareAction.ManageSettings,
        OrgPermissionSubjects.SecretShare
      );
    }

    if (secretShareBrandConfig !== undefined) {
      ForbiddenError.from(permission).throwUnlessCan(
        OrgPermissionSecretShareAction.ManageSettings,
        OrgPermissionSubjects.SecretShare
      );
    }

    const plan = await licenseService.getPlan(orgId);
    const currentOrg = await requestMemoize(requestMemoKeys.orgFindOrgById(actorOrgId), () =>
      orgDAL.findOrgById(actorOrgId)
    );

    if (secretShareBrandConfig !== undefined) {
      if (!plan.secretShareExternalBranding) {
        throw new BadRequestError({
          message:
            "Failed to update secret share branding due to plan restriction. Upgrade plan to configure custom branding."
        });
      }
    }

    if (requireGatewayPools) {
      if (!plan.gatewayPool) {
        throw new BadRequestError({
          message:
            "Failed to require gateway pools due to plan restriction. Upgrade to Infisical Enterprise to use gateway pools."
        });
      }
    }

    if (enforceMfa !== undefined) {
      if (!plan.enforceMfa) {
        throw new BadRequestError({
          message: "Failed to enforce user MFA due to plan restriction. Upgrade plan to enforce/un-enforce MFA."
        });
      }

      if (!appCfg.isSmtpConfigured) {
        throw new BadRequestError({
          message: "Failed to enforce user MFA due to missing instance SMTP configuration."
        });
      }
    }

    if (ssoMfaTrust !== undefined) {
      ForbiddenError.from(permission).throwUnlessCan(OrgPermissionSsoActions.Edit, OrgPermissionSubjects.Sso);
    }

    if (ssoMfaTrust !== undefined && ssoMfaTrust !== SsoMfaTrust.None && !plan.enforceMfa) {
      throw new BadRequestError({
        message:
          "Failed to update MFA for SSO logins due to plan restriction. Upgrade plan to trust identity provider MFA."
      });
    }

    if (authEnforced !== undefined) {
      if (!plan?.samlSSO && !plan.oidcSSO)
        throw new BadRequestError({
          message: "Failed to enforce/un-enforce SSO due to plan restriction. Upgrade plan to enforce/un-enforce SSO."
        });
      ForbiddenError.from(permission).throwUnlessCan(OrgPermissionSsoActions.Edit, OrgPermissionSubjects.Sso);
    }

    if (scimEnabled !== undefined) {
      if (!plan?.scim)
        throw new BadRequestError({
          message:
            "Failed to enable/disable SCIM provisioning due to plan restriction. Upgrade plan to enable/disable SCIM provisioning."
        });
      ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Scim);
      if (scimEnabled && !currentOrg.orgAuthMethod) {
        throw new BadRequestError({
          message: "Cannot enable SCIM when neither SAML or OIDC is configured."
        });
      }
    }

    if (googleSsoAuthEnforced !== undefined) {
      if (!plan.enforceGoogleSSO) {
        throw new BadRequestError({
          message: "Failed to enforce Google SSO due to plan restriction. Upgrade plan to enforce Google SSO."
        });
      }
      ForbiddenError.from(permission).throwUnlessCan(OrgPermissionSsoActions.Edit, OrgPermissionSubjects.Sso);
    }

    if (authEnforced && googleSsoAuthEnforced) {
      throw new BadRequestError({
        message: "SAML/OIDC auth enforcement and Google SSO auth enforcement cannot be enabled at the same time."
      });
    }

    let samlCfg: TSamlConfigs | undefined;
    let oidcCfg: TOidcConfigs | undefined;
    if (authEnforced || googleSsoAuthEnforced) {
      samlCfg = await samlConfigDAL.findOne({
        orgId,
        isActive: true
      });
      oidcCfg = await oidcConfigDAL.findOne({
        orgId,
        isActive: true
      });
    }

    if (authEnforced) {
      if (!samlCfg && !oidcCfg)
        throw new NotFoundError({
          message: `SAML or OIDC configuration for organization with ID '${orgId}' not found`
        });

      if (samlCfg && !samlCfg.lastUsed) {
        throw new BadRequestError({
          message:
            "To apply the new SAML auth enforcement, please log in via SAML at least once. This step is required to enforce SAML-based authentication."
        });
      }

      if (oidcCfg && !oidcCfg.lastUsed) {
        throw new BadRequestError({
          message:
            "To apply the new OIDC auth enforcement, please log in via OIDC at least once. This step is required to enforce OIDC-based authentication."
        });
      }
    }

    if (slug) {
      const existingOrg = await orgDAL.findOne({ slug, rootOrgId: null });
      if (existingOrg && existingOrg?.id !== orgId)
        throw new BadRequestError({ message: `Organization with slug ${slug} already exists` });
    }

    if (googleSsoAuthEnforced) {
      if (googleSsoAuthEnforced && currentOrg.authEnforced) {
        throw new BadRequestError({
          message: "Google SSO auth enforcement cannot be enabled when SAML/OIDC auth enforcement is enabled."
        });
      }

      if (samlCfg) {
        throw new BadRequestError({
          message:
            "Cannot enable Google OAuth enforcement while SAML SSO is configured. Disable SAML SSO to enforce Google OAuth."
        });
      }

      if (oidcCfg) {
        throw new BadRequestError({
          message:
            "Cannot enable Google OAuth enforcement while OIDC SSO is configured. Disable OIDC SSO to enforce Google OAuth."
        });
      }

      const ldapCfg = await ldapConfigDAL.findOne({
        orgId,
        isActive: true
      });

      if (ldapCfg) {
        throw new BadRequestError({
          message:
            "Cannot enable Google OAuth enforcement while LDAP SSO is configured. Disable LDAP SSO to enforce Google OAuth."
        });
      }

      if (!currentOrg.googleSsoAuthLastUsed) {
        throw new BadRequestError({
          message:
            "Google SSO auth enforcement cannot be enabled because Google SSO has not been used yet. Please log in via Google SSO at least once before enforcing it for your organization."
        });
      }
    }

    let defaultMembershipRole: string | undefined;
    if (defaultMembershipRoleSlug) {
      defaultMembershipRole = await getDefaultOrgMembershipRoleForUpdateOrg({
        membershipRoleSlug: defaultMembershipRoleSlug,
        orgId,
        roleDAL,
        plan
      });
    }

    const org = await orgDAL.updateById(orgId, {
      name,
      slug: slug ? slugify(slug) : undefined,
      authEnforced,
      googleSsoAuthEnforced,
      scimEnabled,
      defaultMembershipRole,
      enforceMfa,
      selectedMfaMethod,
      ssoMfaTrust,
      allowSecretSharingOutsideOrganization,
      bypassOrgAuthEnabled,
      userTokenExpiration,
      secretsProductEnabled,
      pkiProductEnabled,
      kmsProductEnabled,
      scannerProductEnabled,
      shareSecretsProductEnabled,
      maxSharedSecretLifetime,
      maxSharedSecretViewLimit,
      blockDuplicateSecretSyncDestinations,
      allowCrossProjectSecretSharing,
      requireGatewayPools,
      secretShareBrandConfig
    });
    if (!org) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });

    if (allowCrossProjectSecretSharing !== undefined) {
      const projectIds = await projectDAL.findOrgProjectIds(orgId);
      await Promise.all(projectIds.map((id) => secretV2BridgeDAL.invalidateSecretCacheByProjectId(id)));
    }

    return org;
  };
  /*
   * Create organization
   * */
  const createOrganization = async (
    {
      userId,
      orgName,
      blockIfUserHasCreatedOrg
    }: {
      userId?: string;
      orgName: string;
      // Set by the user-facing create-org endpoint, and only on cloud.
      blockIfUserHasCreatedOrg?: boolean;
    },
    trx?: Knex
  ) => {
    const createOrg = async (tx: Knex) => {
      // Serializes concurrent creates so two requests cannot both read a count of zero. Tried rather
      // than waited on, so the loser answers immediately instead of holding one of the ten pool
      // connections until the winner commits.
      if (blockIfUserHasCreatedOrg && userId) {
        const lock = await tx.raw<{ rows: { lock_acquired: boolean }[] }>(
          "SELECT pg_try_advisory_xact_lock(?) as lock_acquired",
          [PgSqlLock.CreateOrganization(userId)]
        );
        if (!lock?.rows[0]?.lock_acquired) {
          throw new ConflictError({
            message: "Another organization is already being created for your account. Try again in a moment."
          });
        }

        const createdOrgs = await orgDAL.countJoinedRootOrgsCreatedByUserId(userId, tx);
        if (createdOrgs > 0) {
          throw new ConflictError({
            message:
              "You have already created an organization. Ask an administrator of an existing organization to invite you."
          });
        }
      }

      // akhilmhdh: for now this is auto created. in future we can input from user and for previous users just modifiy
      const org = await orgDAL.create(
        { name: orgName, slug: slugify(`${orgName}-${alphaNumericNanoId(4)}`), createdByUserId: userId },
        tx
      );
      if (userId) {
        const membership = await orgDAL.createMembership(
          {
            scope: AccessScope.Organization,
            actorUserId: userId,
            scopeOrgId: org.id,
            status: OrgMembershipStatus.Accepted,
            isActive: true
          },
          tx
        );
        await membershipRoleDAL.create(
          {
            membershipId: membership.id,
            role: OrgMembershipRole.Admin
          },
          tx
        );
      }

      await bootstrapCertManagerProject(
        {
          orgId: org.id,
          adminUserIds: userId ? [userId] : []
        },
        { projectDAL, membershipDAL, membershipRoleDAL, certificatePolicyDAL },
        tx
      );

      await bootstrapPamProject(
        {
          orgId: org.id,
          adminUserIds: userId ? [userId] : []
        },
        { projectDAL, membershipDAL, membershipRoleDAL },
        tx
      );

      await bootstrapAgentVaultProject(
        {
          orgId: org.id,
          adminUserIds: userId ? [userId] : []
        },
        { projectDAL, membershipDAL, membershipRoleDAL },
        tx
      );

      // Orgs created from the admin console have no creator; their admins are invited afterwards, so the
      // project is left to the lazy resolver, which makes every org admin a project admin.
      if (userId) {
        await bootstrapSecretScanningProject(
          {
            orgId: org.id,
            adminUserIds: [userId]
          },
          { projectDAL, membershipDAL, membershipRoleDAL },
          tx
        );
      }

      return org;
    };

    const organization = await (trx ? createOrg(trx) : orgDAL.transaction(createOrg));

    await licenseService.updateSubscriptionOrgMemberCount(organization.id, trx);

    usageMeteringService.emit(organization.id, PamIdentities.key);
    usageMeteringService.emit(organization.id, AgentVaultIdentities.key);

    return organization;
  };

  /*
   * Delete organization by id
   * */
  const deleteOrganizationById = async ({
    userId,
    authorizationHeader,
    userAgentHeader,
    ipAddress,
    orgId,
    actorAuthMethod,
    actorOrgId
  }: {
    userId: string;
    authorizationHeader?: string;
    userAgentHeader?: string;
    ipAddress: string;
    orgId: string;
    actorAuthMethod: ActorAuthMethod;
    actorOrgId: string;
  }) => {
    const { hasRole } = await permissionService.getOrgPermission({
      actor: ActorType.USER,
      actorId: userId,
      orgId,
      actorAuthMethod,
      actorOrgId,
      scope: OrganizationActionScope.Any
    });
    if (!hasRole(OrgMembershipRole.Admin)) {
      throw new ForbiddenRequestError({
        name: "DeleteOrganizationById",
        message: "Insufficient privileges"
      });
    }

    if (!authorizationHeader) {
      throw new UnauthorizedError({ name: "Authorization header not set on request." });
    }

    if (!userAgentHeader) {
      throw new BadRequestError({ name: "User agent not set on request." });
    }

    const cfg = getConfig();
    const authToken = authorizationHeader.replace("Bearer ", "");

    const decodedToken = crypto.jwt().verify(authToken, cfg.AUTH_SECRET) as AuthModeJwtTokenPayload;
    if (!decodedToken.authMethod) throw new UnauthorizedError({ name: "Auth method not found on existing token" });

    const org = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
    if (!org) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
    // if root org null = this is a root org then cancel the subscription.
    if (!org.rootOrgId) {
      await licenseService.cancelOrgSubscription(orgId);
    }

    // Outside the transaction: the cleanup runs its own queries per project, and inside it each
    // concurrent delete would hold one pooled connection while waiting on a second.
    const projects = await projectDAL.find({ orgId });
    for await (const project of projects) {
      await fnDeleteProjectSecretReminders(project.id, {
        secretDAL,
        reminderService,
        projectBotService,
        folderDAL
      });
    }

    const response = await orgDAL.transaction(async (tx) => {
      const deletedOrg = await orgDAL.deleteById(orgId, tx);

      // Generate new tokens without the organization ID present
      const user = await userDAL.findById(userId, tx);
      const { access: accessToken, refresh: refreshToken } = await loginService.generateUserTokens(
        {
          userId: user.id,
          authMethod: decodedToken.authMethod,
          issuingRootOrgId: decodedToken.issuingRootOrgId,
          ip: ipAddress,
          userAgent: userAgentHeader,
          isMfaVerified: decodedToken.isMfaVerified,
          mfaMethod: decodedToken.mfaMethod,
          idpMfaOrgId: decodedToken.idpMfaOrgId
        },
        tx
      );

      return {
        organization: deletedOrg,
        tokens: {
          accessToken,
          refreshToken
        }
      };
    });

    return response;
  };
  /*
   * Org membership management
   * Not another service because it has close ties with how an org works doesn't make sense to seperate them
   * */
  const updateOrgMembership = async ({
    role,
    isActive,
    orgId,
    actor,
    actorId,
    membershipId,
    actorAuthMethod,
    actorOrgId,
    metadata
  }: TUpdateOrgMembershipDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId,
      scope: OrganizationActionScope.Any
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionMemberActions.Edit, OrgPermissionSubjects.Member);

    const foundMembership = await membershipUserDAL.findOne({
      id: membershipId,
      scope: AccessScope.Organization,
      scopeOrgId: actorOrgId
    });
    if (!foundMembership?.actorUserId)
      throw new NotFoundError({ message: `Organization membership with ID '${membershipId}' not found` });
    if (foundMembership.scopeOrgId !== orgId)
      throw new UnauthorizedError({ message: "Updated org member doesn't belong to the organization" });
    if (actor === ActorType.USER && foundMembership.actorUserId === actorId)
      throw new UnauthorizedError({ message: "Cannot update own organization membership" });

    const { shouldUseNewPrivilegeSystem } = await requestMemoize(requestMemoKeys.orgFindById(orgId), () =>
      orgDAL.findById(orgId)
    );

    const targetOps: { opAction: OrgPermissionMemberActions; baseMessage: string }[] = [];
    if (role !== undefined || metadata !== undefined)
      targetOps.push({
        opAction: OrgPermissionMemberActions.GrantPrivileges,
        baseMessage: "Failed to change the roles or attributes of this org member"
      });
    if (isActive !== undefined)
      targetOps.push({
        opAction: OrgPermissionMemberActions.Edit,
        baseMessage: "Failed to change the activation status of this org member"
      });

    if (targetOps.length) {
      const targetRoles = resolveMembershipRoleSlugs(await membershipRoleDAL.findRolesByMembershipIds([membershipId]));
      const targetPermissions = await permissionService.getOrgPermissionByRoles(targetRoles, orgId, {
        ignoreUnresolvedRoles: true
      });

      for (const { opAction, baseMessage } of targetOps) {
        assertRoleSetBoundary({
          shouldUseNewPrivilegeSystem,
          opActions: opAction,
          opSubject: OrgPermissionSubjects.Member,
          actorPermission: permission,
          targetPermissions,
          baseMessage
        });
      }
    }

    const isCustomRole = !Object.values(OrgMembershipRole).includes(role as OrgMembershipRole);
    let userRole = role;
    let userRoleId: string | null = null;
    if (role && isCustomRole) {
      const customRole = await roleDAL.findOne({ slug: role, orgId });
      if (!customRole) throw new BadRequestError({ name: "UpdateMembership", message: "Organization role not found" });

      const plan = await licenseService.getPlan(orgId);
      if (!plan?.rbac)
        throw new BadRequestError({
          message: "Failed to assign custom role due to RBAC restriction. Upgrade plan to assign custom role to member."
        });

      userRole = OrgMembershipRole.Custom;
      userRoleId = customRole.id;
    }

    if (role && roleNeedsPrivilegeBoundary(role)) {
      const permissionRoles = await permissionService.getOrgPermissionByRoles([role], orgId);
      assertRoleSetBoundary({
        shouldUseNewPrivilegeSystem,
        opActions: OrgPermissionMemberActions.GrantPrivileges,
        opSubject: OrgPermissionSubjects.Member,
        actorPermission: permission,
        targetPermissions: permissionRoles,
        baseMessage: "Failed to assign the requested role to an org member"
      });
    }

    const updatesToActiveAdmin = role === OrgMembershipRole.Admin && isActive !== false;
    const noRoleOrActivationChange = role === undefined && (isActive === undefined || isActive === true);

    let sendPamCancellations = () => {};

    const membership = await orgDAL.transaction(async (tx) => {
      if (!updatesToActiveAdmin && !noRoleOrActivationChange) {
        await assertWillRetainOrgAdmin({
          scopeOrgId: orgId,
          excludeMembershipIds: [membershipId],
          dal: membershipUserDAL,
          tx
        });
      }

      // this is because if isActive is undefined then this would fail due to knexjs error
      const [updatedOrgMembership] =
        typeof isActive === "undefined"
          ? [foundMembership]
          : await orgDAL.updateMembership(
              { id: membershipId, scopeOrgId: orgId, scope: AccessScope.Organization },
              { isActive },
              tx
            );
      if (userRole) {
        await membershipRoleDAL.delete({ membershipId }, tx);
        await membershipRoleDAL.create(
          {
            membershipId,
            role: userRole,
            customRoleId: userRoleId
          },
          tx
        );
      }

      if (metadata) {
        await identityMetadataDAL.delete({ userId: updatedOrgMembership.actorUserId, orgId }, tx);
        if (metadata.length) {
          await identityMetadataDAL.insertMany(
            metadata.map(({ key, value }) => ({
              userId: updatedOrgMembership.actorUserId as string,
              orgId,
              key,
              value
            })),
            tx
          );
        }
      }

      if (isActive === false && updatedOrgMembership.actorUserId) {
        const childOrgs = await orgDAL.find({ rootOrgId: orgId }, { tx });
        sendPamCancellations = await terminatePamSessionsForUsers({
          orgIds: [orgId, ...childOrgs.map((el) => el.id)],
          userIds: [updatedOrgMembership.actorUserId],
          pamSessionDAL,
          gatewayV2Service,
          tx
        });
      }

      return updatedOrgMembership;
    });

    sendPamCancellations();

    return membership;
  };

  const $getEnforcedSsoLoginUrl = async (orgId: string, orgSlug: string) => {
    const appCfg = getConfig();

    const [oidcConfig, samlConfig] = await Promise.all([
      oidcConfigDAL.findOne({ orgId, isActive: true }).catch(() => null),
      samlConfigDAL.findOne({ orgId, isActive: true }).catch(() => null)
    ]);

    if (oidcConfig) {
      return `${appCfg.SITE_URL}/api/v1/sso/oidc/login?orgSlug=${encodeURIComponent(orgSlug)}`;
    }
    if (samlConfig) {
      return `${appCfg.SITE_URL}/api/v1/sso/redirect/saml2/organizations/${encodeURIComponent(orgSlug)}`;
    }
    // LDAP is credential-based with no SSO redirect endpoint (and a safe fallback for any other
    // enforced method) — send invitees to the login page to sign in with their org credentials.
    return `${appCfg.SITE_URL}/login`;
  };

  const resendOrgMemberInvitation = async ({
    orgId,
    actorId,
    actor,
    actorAuthMethod,
    actorOrgId,
    membershipId
  }: TResendOrgMemberInvitationDTO) => {
    const appCfg = getConfig();
    const { permission } = await permissionService.getOrgPermission({
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId,
      scope: OrganizationActionScope.ParentOrganization
    });

    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionMemberActions.Create, OrgPermissionSubjects.Member);

    const invitingUser = await userDAL.findOne({ id: actorId });

    const org = await requestMemoize(requestMemoKeys.orgFindOrgById(orgId), () => orgDAL.findOrgById(orgId));

    const [inviteeOrgMembership] = await orgDAL.findMembership({
      [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,
      [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization,
      [`${TableName.Membership}.id` as "id"]: membershipId
    });

    if (inviteeOrgMembership.status !== OrgMembershipStatus.Invited) {
      throw new BadRequestError({
        message: "Organization invitation already accepted"
      });
    }

    if (org?.authEnforced) {
      const ssoLoginUrl = await $getEnforcedSsoLoginUrl(org.id, org.slug);

      if (!appCfg.isSmtpConfigured) {
        return {
          signupToken: {
            email: inviteeOrgMembership.email as string,
            link: ssoLoginUrl
          }
        };
      }

      await smtpService.sendMail({
        template: SmtpTemplates.OrgInvite,
        subjectLine: "Infisical organization invitation",
        recipients: [inviteeOrgMembership.email as string],
        substitutions: {
          inviterFirstName: invitingUser.firstName,
          inviterUsername: invitingUser.email,
          organizationName: org?.name,
          callback_url: ssoLoginUrl
        }
      });

      await membershipUserDAL.updateById(inviteeOrgMembership.id, {
        lastInvitedAt: new Date()
      });

      return { signupToken: undefined };
    }

    const token = await tokenService.createTokenForUser({
      type: TokenType.TOKEN_EMAIL_ORG_INVITATION,
      userId: inviteeOrgMembership.actorUserId as string,
      orgId
    });

    if (!appCfg.isSmtpConfigured) {
      return {
        signupToken: {
          email: inviteeOrgMembership.email as string,
          link: `${appCfg.SITE_URL}/signupinvite?token=${token}&to=${inviteeOrgMembership.email}&organization_id=${org?.id}`
        }
      };
    }

    await smtpService.sendMail({
      template: SmtpTemplates.OrgInvite,
      subjectLine: "Infisical organization invitation",
      recipients: [inviteeOrgMembership.email as string],
      substitutions: {
        inviterFirstName: invitingUser.firstName,
        inviterUsername: invitingUser.email,
        organizationName: org?.name,
        callback_url: `${appCfg.SITE_URL}/signupinvite?token=${token}&to=${encodeURIComponent(
          inviteeOrgMembership.email as string
        )}&organization_id=${org?.id}`
      }
    });

    await membershipUserDAL.updateById(inviteeOrgMembership.id, {
      lastInvitedAt: new Date()
    });

    return { signupToken: undefined };
  };

  /**
   * Organization invitation step 2: Verify that code [code] was sent to email [email] as part of
   * magic link and issue a temporary signup token for user to complete setting up their account
   */
  const verifyUserToOrg = async ({ orgId, email, code }: TVerifyUserToOrgDTO) => {
    const user = await userDAL.findOne({ username: email });
    if (!user) {
      throw new NotFoundError({ message: "User not found" });
    }

    const [orgMembership] = await orgDAL.findMembership({
      [`${TableName.Membership}.actorUserId` as "actorUserId"]: user.id,
      scope: AccessScope.Organization,
      status: OrgMembershipStatus.Invited,
      [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId
    });

    if (!orgMembership) {
      // Check if user is already a member
      const [acceptedMembership] = await orgDAL.findMembership({
        [`${TableName.Membership}.actorUserId` as "actorUserId"]: user.id,
        scope: AccessScope.Organization,
        status: OrgMembershipStatus.Accepted,
        [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId
      });

      if (acceptedMembership) {
        throw new BadRequestError({
          message: "User is already a member of this organization"
        });
      }

      throw new NotFoundError({
        message: "No pending invitation found"
      });
    }

    await tokenService.validateTokenForUser({
      type: TokenType.TOKEN_EMAIL_ORG_INVITATION,
      userId: user.id,
      orgId: orgMembership.scopeOrgId,
      code
    });

    const organization = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));

    await userDAL.updateById(user.id, {
      isEmailVerified: true
    });

    // If user already completed signup, they'll be promoted to Accepted
    // when they authenticate via selectOrganization or processProviderCallback
    if (user.isAccepted) {
      return { user, organizationName: organization.name };
    }

    const membershipRole = await membershipRoleDAL.findOne({ membershipId: orgMembership.id });
    if (
      organization.authEnforced &&
      !(organization.bypassOrgAuthEnabled && membershipRole.role === OrgMembershipRole.Admin)
    ) {
      return { user, organizationName: organization.name };
    }

    const appCfg = getConfig();
    const token = crypto.jwt().sign(
      {
        authTokenType: AuthTokenType.SIGNUP_TOKEN,
        userId: user.id,
        // the invite this signup was started from, so completing the account can attribute it to
        // this org rather than guess among every org that invited the user
        organizationId: orgMembership.scopeOrgId
      },
      appCfg.AUTH_SECRET,
      {
        expiresIn: appCfg.JWT_SIGNUP_LIFETIME
      }
    );

    return { token, user, organizationName: organization.name };
  };

  const getOrgMembership = async ({
    membershipId,
    orgId,
    actor,
    actorId,
    actorAuthMethod,
    actorOrgId
  }: TGetOrgMembershipDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      scope: OrganizationActionScope.Any,
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionMemberActions.Read, OrgPermissionSubjects.Member);

    const membership = await orgMembershipDAL.findOrgMembershipById(membershipId);
    if (!membership) {
      throw new NotFoundError({ message: `Organization membership with ID '${membershipId}' not found` });
    }
    // Answered like an unknown id, so another org's membership ids cannot be probed.
    if (membership.orgId !== orgId) {
      throw new NotFoundError({ message: `Organization membership with ID '${membershipId}' not found` });
    }

    return membership;
  };

  const $assertMembershipRemovalBoundary = async ({
    membershipIds,
    orgId,
    permission
  }: {
    membershipIds: string[];
    orgId: string;
    permission: MongoAbility;
  }) => {
    const targetRoles = resolveMembershipRoleSlugs(await membershipRoleDAL.findRolesByMembershipIds(membershipIds));
    const targetPermissions = await permissionService.getOrgPermissionByRoles(targetRoles, orgId, {
      ignoreUnresolvedRoles: true
    });
    const { shouldUseNewPrivilegeSystem } = await requestMemoize(requestMemoKeys.orgFindById(orgId), () =>
      orgDAL.findById(orgId)
    );

    assertRoleSetBoundary({
      shouldUseNewPrivilegeSystem,
      opActions: OrgPermissionMemberActions.Delete,
      opSubject: OrgPermissionSubjects.Member,
      actorPermission: permission,
      targetPermissions,
      baseMessage: "Failed to remove this member from the organization"
    });
  };

  const deleteOrgMembership = async ({
    orgId,
    actor,
    actorId,
    membershipId,
    actorAuthMethod,
    actorOrgId
  }: TDeleteOrgMembershipDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId,
      scope: OrganizationActionScope.Any
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionMemberActions.Delete, OrgPermissionSubjects.Member);

    const membershipToDelete = await membershipUserDAL.findOne({
      id: membershipId,
      scope: AccessScope.Organization,
      scopeOrgId: orgId
    });
    if (!membershipToDelete?.actorUserId)
      throw new NotFoundError({ message: `Organization membership with ID '${membershipId}' not found` });

    await $assertMembershipRemovalBoundary({ membershipIds: [membershipId], orgId, permission });

    const [deletedMembership] = await deleteOrgMembershipsFn({
      orgMembershipIds: [membershipId],
      orgId,
      orgDAL,
      userAliasDAL,
      licenseService,
      userId: actor === ActorType.USER ? actorId : undefined,
      membershipUserDAL,
      userGroupMembershipDAL,
      projectAccessRevokeService,
      auditLogService,
      eventEmitter
    });

    // Removing an org member cascades their project + group memberships, changing the identity meters.
    usageMeteringService.emit(orgId, SecretIdentities.key);
    usageMeteringService.emit(orgId, PamIdentities.key);
    usageMeteringService.emit(orgId, AgentVaultIdentities.key);
    return deletedMembership;
  };

  const bulkDeleteOrgMemberships = async ({
    orgId,
    actor,
    actorId,
    membershipIds,
    actorAuthMethod,
    actorOrgId
  }: TDeleteOrgMembershipsDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId,
      scope: OrganizationActionScope.Any
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionMemberActions.Delete, OrgPermissionSubjects.Member);

    const membershipsToDelete = await membershipUserDAL.find({
      scope: AccessScope.Organization,
      scopeOrgId: orgId,
      $in: { id: membershipIds },
      $notNull: ["actorUserId"]
    });
    const foundMembershipIds = new Set(membershipsToDelete.map((el) => el.id));
    const missingMembershipIds = membershipIds.filter((id) => !foundMembershipIds.has(id));
    if (missingMembershipIds.length)
      throw new NotFoundError({
        message: `Organization membership with ID '${missingMembershipIds.join("', '")}' not found`
      });

    await $assertMembershipRemovalBoundary({ membershipIds, orgId, permission });

    const deletedMemberships = await deleteOrgMembershipsFn({
      orgMembershipIds: membershipIds,
      orgId,
      orgDAL,
      userAliasDAL,
      licenseService,
      userId: actor === ActorType.USER ? actorId : undefined,
      membershipUserDAL,
      userGroupMembershipDAL,
      projectAccessRevokeService,
      auditLogService,
      eventEmitter
    });

    // Removing org members cascades their project + group memberships, changing the identity meters.
    usageMeteringService.emit(orgId, SecretIdentities.key);
    usageMeteringService.emit(orgId, PamIdentities.key);
    usageMeteringService.emit(orgId, AgentVaultIdentities.key);
    return deletedMemberships;
  };

  const listProjectMembershipsByOrgMembershipId = async ({
    orgMembershipId,
    orgId,
    actor,
    actorId,
    actorAuthMethod,
    actorOrgId
  }: TListProjectMembershipsByOrgMembershipIdDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      scope: OrganizationActionScope.Any,
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionMemberActions.Read, OrgPermissionSubjects.Member);

    const membership = await orgMembershipDAL.findOrgMembershipById(orgMembershipId);
    if (!membership) {
      throw new NotFoundError({ message: `Organization membership with ID '${orgMembershipId}' not found` });
    }
    if (membership.orgId !== orgId) throw new NotFoundError({ message: "Failed to find organization membership" });

    const projectMemberships = await projectMembershipDAL.findProjectMembershipsByUserId(orgId, membership.user.id);

    return projectMemberships;
  };

  /*
   * CRUD operations of incident contacts
   * */
  const findIncidentContacts = async (
    userId: string,
    orgId: string,
    actorAuthMethod: ActorAuthMethod,
    actorOrgId: string
  ) => {
    const { permission } = await permissionService.getOrgPermission({
      actor: ActorType.USER,
      actorId: userId,
      orgId,
      actorAuthMethod,
      actorOrgId,
      scope: OrganizationActionScope.Any
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.IncidentAccount);
    const incidentContacts = await incidentContactDAL.findByOrgId(orgId);
    return incidentContacts;
  };

  const createIncidentContact = async (
    userId: string,
    orgId: string,
    email: string,
    actorAuthMethod: ActorAuthMethod,
    actorOrgId: string
  ) => {
    const { permission } = await permissionService.getOrgPermission({
      actor: ActorType.USER,
      actorId: userId,
      orgId,
      actorAuthMethod,
      actorOrgId,
      scope: OrganizationActionScope.ParentOrganization
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Create, OrgPermissionSubjects.IncidentAccount);
    const doesIncidentContactExist = await incidentContactDAL.findOne(orgId, { email });
    if (doesIncidentContactExist) {
      throw new BadRequestError({
        message: "Incident contact already exists",
        name: "Incident contact exist"
      });
    }

    const incidentContact = await incidentContactDAL.create(orgId, email);
    return incidentContact;
  };

  const deleteIncidentContact = async (
    userId: string,
    orgId: string,
    id: string,
    actorAuthMethod: ActorAuthMethod,
    actorOrgId: string
  ) => {
    const { permission } = await permissionService.getOrgPermission({
      actor: ActorType.USER,
      actorId: userId,
      orgId,
      actorAuthMethod,
      actorOrgId,
      scope: OrganizationActionScope.ParentOrganization
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Delete, OrgPermissionSubjects.IncidentAccount);

    const incidentContact = await incidentContactDAL.deleteById(id, orgId);
    return incidentContact;
  };

  /**
   * Re-send emails to users who haven't accepted an invite yet
   */
  const notifyInvitedUsers = async () => {
    logger.info(`daily-resource-cleanup: notify invited users started`);

    const invitedUsers = await orgMembershipDAL.findRecentInvitedMemberships();
    const appCfg = getConfig();

    const orgCache: Record<
      string,
      { name: string; id: string; slug: string; authEnforced?: boolean | null } | undefined
    > = {};
    const notifiedUsers: string[] = [];

    const resolvedInvites: {
      invitedUser: (typeof invitedUsers)[number];
      org: { name: string; id: string; slug: string; authEnforced?: boolean | null };
    }[] = [];
    for (const invitedUser of invitedUsers) {
      let org = orgCache[invitedUser.scopeOrgId];
      if (!org) {
        // eslint-disable-next-line no-await-in-loop
        org = await requestMemoize(requestMemoKeys.orgFindById(invitedUser.scopeOrgId), () =>
          orgDAL.findById(invitedUser.scopeOrgId)
        );
        orgCache[invitedUser.scopeOrgId] = org;
      }

      if (org && invitedUser.actorUserId && invitedUser.inviteEmail) {
        resolvedInvites.push({ invitedUser, org });
      }
    }

    const ssoLoginUrlByOrg = new Map<string, string>();
    await Promise.all(
      [...new Map(resolvedInvites.map(({ org }) => [org.id, org])).values()]
        .filter((org) => org.authEnforced)
        .map(async (org) => {
          ssoLoginUrlByOrg.set(org.id, await $getEnforcedSsoLoginUrl(org.id, org.slug));
        })
    );

    const tokens = await tokenService.createTokensForUsers(
      resolvedInvites
        .filter(({ org }) => !org.authEnforced)
        .map(({ invitedUser, org }) => ({
          type: TokenType.TOKEN_EMAIL_ORG_INVITATION,
          userId: invitedUser.actorUserId as string,
          orgId: org.id
        }))
    );
    const tokenByUserOrg = new Map(tokens.map((t) => [`${t.userId}:${t.orgId}`, t.token]));

    await Promise.all(
      resolvedInvites.map(async ({ invitedUser, org }) => {
        let callbackUrl: string;
        if (org.authEnforced) {
          const ssoLoginUrl = ssoLoginUrlByOrg.get(org.id);
          if (!ssoLoginUrl) return;
          callbackUrl = ssoLoginUrl;
        } else {
          const token = tokenByUserOrg.get(`${invitedUser.actorUserId}:${org.id}`);
          if (!token) return;
          callbackUrl = `${appCfg.SITE_URL}/signupinvite?token=${token}&to=${encodeURIComponent(
            invitedUser.inviteEmail as string
          )}&organization_id=${org.id}`;
        }

        await delayMs(Math.max(0, applyJitter(0, 2000)));

        try {
          await smtpService.sendMail({
            template: SmtpTemplates.OrgInvite,
            subjectLine: `Reminder: You have been invited to ${org.name} on Infisical`,
            recipients: [invitedUser.inviteEmail as string],
            substitutions: {
              organizationName: org.name,
              callback_url: callbackUrl
            }
          });
          notifiedUsers.push(invitedUser.id);
        } catch (err) {
          logger.error(err, `daily-resource-cleanup: notify invited users failed to send email`);
        }
      })
    );

    await orgMembershipDAL.updateLastInvitedAtByIds(notifiedUsers);

    logger.info(`daily-resource-cleanup: notify invited users completed`);
  };

  return {
    findOrganizationById,
    findAllOrgMembers,
    listOrgUserAccess,
    findAllOrganizationOfUser,
    findIdentityOrganization,
    verifyUserToOrg,
    updateOrg,
    findOrgMembersByUsername,
    createOrganization,
    deleteOrganizationById,
    getOrgMembership,
    deleteOrgMembership,
    findAllWorkspaces,
    addGhostUser,
    updateOrgMembership,
    findAllAccessibleOrganizationsWithSubOrgs,
    // incident contacts
    findIncidentContacts,
    createIncidentContact,
    deleteIncidentContact,
    getOrgGroups,
    listProjectMembershipsByOrgMembershipId,
    findOrgBySlug,
    resendOrgMemberInvitation,
    upgradePrivilegeSystem,
    notifyInvitedUsers,
    bulkDeleteOrgMemberships
  };
};