Skip to content

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

36.5 KB
Raw Blame
import { ForbiddenError } from "@casl/ability";
import { Knex } from "knex";

import {
  AccessScope,
  OrganizationActionScope,
  OrgMembershipStatus,
  TableName,
  TLdapConfigsUpdate,
  TUsers
} from "@app/db/schemas";
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 { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "@app/ee/services/group/group-fns";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { getEnforcedIdentityLimit, throwOnPlanSeatLimitReached } from "@app/ee/services/license/license-fns";
import { TPamAccountDALFactory } from "@app/ee/services/pam-account/pam-account-dal";
import { TPamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";
import { getConfig } from "@app/lib/config/env";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import {
  AuthAttemptAuthMethod,
  AuthAttemptAuthResult,
  authAttemptCounter,
  recordAuthAttemptMetric,
  recordSsoConfigChangeMetric,
  SsoConfigAction,
  SsoProvider
} from "@app/lib/telemetry/metrics";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { sanitizeEmail, validateEmail } from "@app/lib/validator/validate-email";
import { TAdditionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";
import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { TokenType } from "@app/services/auth-token/auth-token-types";
import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";
import { AuthMethod } from "@app/services/auth/auth-type";
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 { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TMembershipGroupDALFactory } from "@app/services/membership-group/membership-group-dal";
import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { getDefaultOrgMembershipRole } from "@app/services/org/org-role-fns";
import { TProjectBotDALFactory } from "@app/services/project-bot/project-bot-dal";
import { TProjectKeyDALFactory } from "@app/services/project-key/project-key-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
import { getServerCfg } from "@app/services/super-admin/super-admin-service";
import { LoginMethod } from "@app/services/super-admin/super-admin-types";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";
import { ensureSsoAccountVerified, isStaleSsoAlias, syncSsoUserProfile } from "@app/services/user-alias/user-alias-fns";
import { UserAliasType } from "@app/services/user-alias/user-alias-types";
import { TUserDALFactory } from "@app/services/user/user-dal";

import { TEmailDomainDALFactory } from "../email-domain/email-domain-dal";
import { isIdpAuthoritativeForDomain, verifyEmailDomainOwnership } from "../email-domain/email-domain-fns";
import { TLicenseServiceFactory } from "../license/license-service";
import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission";
import { TPermissionServiceFactory } from "../permission/permission-service-types";
import { TLdapConfigDALFactory } from "./ldap-config-dal";
import {
  TCreateLdapCfgDTO,
  TCreateLdapGroupMapDTO,
  TDeleteLdapGroupMapDTO,
  TGetLdapCfgDTO,
  TGetLdapGroupMapsDTO,
  TLdapLoginDTO,
  TTestLdapConnectionDTO,
  TUpdateLdapCfgDTO
} from "./ldap-config-types";
import { buildLdapTlsOptions, searchGroups, testLDAPConfig } from "./ldap-fns";
import { TLdapGroupMapDALFactory } from "./ldap-group-map-dal";

type TLdapConfigServiceFactoryDep = {
  ldapConfigDAL: Pick<TLdapConfigDALFactory, "create" | "update" | "findOne" | "transaction">;
  auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
  ldapGroupMapDAL: Pick<TLdapGroupMapDALFactory, "find" | "create" | "delete" | "findLdapGroupMapsByLdapConfigId">;
  orgDAL: Pick<
    TOrgDALFactory,
    | "createMembership"
    | "updateMembershipById"
    | "findMembership"
    | "findOrgById"
    | "findOne"
    | "updateById"
    | "lockActorsForOrgAccess"
  >;
  groupDAL: Pick<TGroupDALFactory, "find" | "findOne" | "findGroupOrgIds">;
  membershipGroupDAL: Pick<TMembershipGroupDALFactory, "find">;
  membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActors">;
  membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create" | "find">;
  projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "findLatestProjectKey" | "insertMany" | "delete">;
  alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;
  eventEmitter: TEventEmitter;
  projectDAL: Pick<TProjectDALFactory, "findProjectGhostUser" | "findById">;
  projectBotDAL: Pick<TProjectBotDALFactory, "findOne">;
  userGroupMembershipDAL: Pick<
    TUserGroupMembershipDALFactory,
    "find" | "transaction" | "insertMany" | "filterProjectsByUserMembership" | "delete"
  >;
  userDAL: Pick<
    TUserDALFactory,
    | "create"
    | "findOne"
    | "findById"
    | "transaction"
    | "updateById"
    | "findUserEncKeyByUserIdsBatch"
    | "find"
    | "findUserEncKeyByUserId"
  >;
  userAliasDAL: Pick<TUserAliasDALFactory, "create" | "findOne" | "updateById">;
  permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
  additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "delete">;
  licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getOrgSeatUsage" | "updateSubscriptionOrgMemberCount">;
  tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser">;
  smtpService: Pick<TSmtpService, "sendMail">;
  kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
  loginService: Pick<TAuthLoginFactory, "processProviderCallback">;
  emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;
  telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
  usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;
  pamAccountDAL: Pick<TPamAccountDALFactory, "find">;
  pamSessionDAL: Pick<TPamSessionDALFactory, "find" | "update">;
  gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
};

export type TLdapConfigServiceFactory = ReturnType<typeof ldapConfigServiceFactory>;

export const ldapConfigServiceFactory = ({
  ldapConfigDAL,
  auditLogService,
  ldapGroupMapDAL,
  orgDAL,
  groupDAL,
  membershipGroupDAL,
  membershipDAL,
  membershipRoleDAL,
  projectKeyDAL,
  alertChannelRecipientDAL,
  eventEmitter,
  projectDAL,
  projectBotDAL,
  userGroupMembershipDAL,
  userDAL,
  userAliasDAL,
  additionalPrivilegeDAL,
  permissionService,
  licenseService,
  tokenService,
  smtpService,
  kmsService,
  loginService,
  emailDomainDAL,
  telemetryService,
  usageMeteringService,
  pamAccountDAL,
  pamSessionDAL,
  gatewayV2Service
}: TLdapConfigServiceFactoryDep) => {
  const createLdapCfg = async ({
    actor,
    actorId,
    orgId,
    actorOrgId,
    actorAuthMethod,
    isActive,
    url,
    bindDN,
    bindPass,
    uniqueUserAttribute,
    searchBase,
    searchFilter,
    groupSearchBase,
    groupSearchFilter,
    caCert,
    clientCertificate,
    clientKeyCertificate
  }: TCreateLdapCfgDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      scope: OrganizationActionScope.ParentOrganization,
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Create, OrgPermissionSubjects.Ldap);

    const plan = await licenseService.getPlan(orgId);
    if (!plan.ldap)
      throw new BadRequestError({
        message:
          "Failed to create LDAP configuration due to plan restriction. Upgrade plan to create LDAP configuration."
      });

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

    if (!org) {
      throw new NotFoundError({ message: `Could not find organization with ID "${orgId}"` });
    }

    if (org.googleSsoAuthEnforced && isActive) {
      throw new BadRequestError({
        message:
          "You cannot enable LDAP SSO while Google OAuth is enforced. Disable Google OAuth enforcement to enable LDAP SSO."
      });
    }

    await blockLocalAndPrivateIpAddresses(url);

    if (Boolean(clientCertificate) !== Boolean(clientKeyCertificate)) {
      throw new BadRequestError({
        message: "clientCertificate and clientKeyCertificate must be provided together for mTLS."
      });
    }

    const { encryptor } = await kmsService.createCipherPairWithDataKey({
      type: KmsDataKey.Organization,
      orgId
    });

    const isConnected = await testLDAPConfig({
      bindDN,
      bindPass,
      caCert,
      clientCertificate,
      clientKeyCertificate,
      url
    });

    if (!isConnected) {
      throw new BadRequestError({
        message: "Failed to establish connection to LDAP directory. Please verify that your credentials are correct."
      });
    }

    const ldapConfig = await ldapConfigDAL.create({
      orgId,
      isActive,
      url,
      uniqueUserAttribute,
      searchBase,
      searchFilter,
      groupSearchBase,
      groupSearchFilter,
      encryptedLdapCaCertificate: encryptor({ plainText: Buffer.from(caCert) }).cipherTextBlob,
      encryptedLdapBindDN: encryptor({ plainText: Buffer.from(bindDN) }).cipherTextBlob,
      encryptedLdapBindPass: encryptor({ plainText: Buffer.from(bindPass) }).cipherTextBlob,
      encryptedLdapClientCertificate: clientCertificate
        ? encryptor({ plainText: Buffer.from(clientCertificate) }).cipherTextBlob
        : null,
      encryptedLdapClientKeyCertificate: clientKeyCertificate
        ? encryptor({ plainText: Buffer.from(clientKeyCertificate) }).cipherTextBlob
        : null
    });

    recordSsoConfigChangeMetric({ provider: SsoProvider.Ldap, action: SsoConfigAction.Create, orgId });

    return ldapConfig;
  };

  const getLdapCfg = async (filter: { orgId: string; isActive?: boolean; id?: string }, tx?: Knex) => {
    const ldapConfig = await ldapConfigDAL.findOne(filter, tx);
    if (!ldapConfig) {
      throw new NotFoundError({
        message: `Failed to find organization LDAP data in organization with ID '${filter.orgId}'`
      });
    }

    const { decryptor } = await kmsService.createCipherPairWithDataKey({
      type: KmsDataKey.Organization,
      orgId: ldapConfig.orgId
    });

    let bindDN = "";
    if (ldapConfig.encryptedLdapBindDN) {
      bindDN = decryptor({ cipherTextBlob: ldapConfig.encryptedLdapBindDN }).toString();
    }

    let bindPass = "";
    if (ldapConfig.encryptedLdapBindPass) {
      bindPass = decryptor({ cipherTextBlob: ldapConfig.encryptedLdapBindPass }).toString();
    }

    let caCert = "";
    if (ldapConfig.encryptedLdapCaCertificate) {
      caCert = decryptor({ cipherTextBlob: ldapConfig.encryptedLdapCaCertificate }).toString();
    }

    let clientCertificate = "";
    if (ldapConfig.encryptedLdapClientCertificate) {
      clientCertificate = decryptor({ cipherTextBlob: ldapConfig.encryptedLdapClientCertificate }).toString();
    }

    let clientKeyCertificate = "";
    if (ldapConfig.encryptedLdapClientKeyCertificate) {
      clientKeyCertificate = decryptor({ cipherTextBlob: ldapConfig.encryptedLdapClientKeyCertificate }).toString();
    }

    return {
      id: ldapConfig.id,
      organization: ldapConfig.orgId,
      isActive: ldapConfig.isActive,
      url: ldapConfig.url,
      bindDN,
      bindPass,
      uniqueUserAttribute: ldapConfig.uniqueUserAttribute,
      searchBase: ldapConfig.searchBase,
      searchFilter: ldapConfig.searchFilter,
      groupSearchBase: ldapConfig.groupSearchBase,
      groupSearchFilter: ldapConfig.groupSearchFilter,
      caCert,
      clientCertificate,
      clientKeyCertificate
    };
  };

  const updateLdapCfg = async ({
    actor,
    actorId,
    orgId,
    actorOrgId,
    isActive,
    actorAuthMethod,
    url,
    bindDN,
    bindPass,
    uniqueUserAttribute,
    searchBase,
    searchFilter,
    groupSearchBase,
    groupSearchFilter,
    caCert,
    clientCertificate,
    clientKeyCertificate
  }: TUpdateLdapCfgDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      scope: OrganizationActionScope.ParentOrganization,
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Ldap);

    const plan = await licenseService.getPlan(orgId);
    if (!plan.ldap)
      throw new BadRequestError({
        message:
          "Failed to update LDAP configuration due to plan restriction. Upgrade plan to update LDAP configuration."
      });

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

    if (!org) {
      throw new NotFoundError({ message: `Could not find organization with ID "${orgId}"` });
    }

    if (org.googleSsoAuthEnforced && isActive) {
      throw new BadRequestError({
        message:
          "You cannot enable LDAP SSO while Google OAuth is enforced. Disable Google OAuth enforcement to enable LDAP SSO."
      });
    }

    if (url) {
      await blockLocalAndPrivateIpAddresses(url);
    }

    const updateQuery: TLdapConfigsUpdate = {
      isActive,
      url,
      searchBase,
      searchFilter,
      groupSearchBase,
      groupSearchFilter,
      uniqueUserAttribute
    };

    const { encryptor } = await kmsService.createCipherPairWithDataKey({
      type: KmsDataKey.Organization,
      orgId
    });

    if (bindDN !== undefined) {
      updateQuery.encryptedLdapBindDN = encryptor({ plainText: Buffer.from(bindDN) }).cipherTextBlob;
    }

    if (bindPass !== undefined) {
      updateQuery.encryptedLdapBindPass = encryptor({ plainText: Buffer.from(bindPass) }).cipherTextBlob;
    }

    if (caCert !== undefined) {
      updateQuery.encryptedLdapCaCertificate = encryptor({ plainText: Buffer.from(caCert) }).cipherTextBlob;
    }

    if (clientCertificate !== undefined) {
      updateQuery.encryptedLdapClientCertificate = clientCertificate
        ? encryptor({ plainText: Buffer.from(clientCertificate) }).cipherTextBlob
        : null;
    }

    if (clientKeyCertificate !== undefined) {
      updateQuery.encryptedLdapClientKeyCertificate = clientKeyCertificate
        ? encryptor({ plainText: Buffer.from(clientKeyCertificate) }).cipherTextBlob
        : null;
    }

    const config = await ldapConfigDAL.transaction(async (tx) => {
      const [updatedLdapCfg] = await ldapConfigDAL.update({ orgId }, updateQuery, tx);
      const decryptedLdapCfg = await getLdapCfg({ orgId }, tx);

      if (Boolean(decryptedLdapCfg.clientCertificate) !== Boolean(decryptedLdapCfg.clientKeyCertificate)) {
        throw new BadRequestError({
          message: "clientCertificate and clientKeyCertificate must be provided together for mTLS."
        });
      }

      const isSoftDeletion = !decryptedLdapCfg.url && !decryptedLdapCfg.bindDN && !decryptedLdapCfg.bindPass;
      if (!isSoftDeletion) {
        const isConnected = await testLDAPConfig(decryptedLdapCfg);
        if (!isConnected) {
          throw new BadRequestError({
            message:
              "Failed to establish connection to LDAP directory. Please verify that your credentials are correct."
          });
        }
      }

      return updatedLdapCfg;
    });

    recordSsoConfigChangeMetric({ provider: SsoProvider.Ldap, action: SsoConfigAction.Update, orgId });

    return config;
  };

  const getLdapCfgWithPermissionCheck = async ({
    actor,
    actorId,
    orgId,
    actorAuthMethod,
    actorOrgId
  }: TGetLdapCfgDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      scope: OrganizationActionScope.ParentOrganization,
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Ldap);
    const ldap = await getLdapCfg({ orgId });
    const { clientKeyCertificate, ...rest } = ldap;
    return {
      ...rest,
      hasClientKeyCertificate: Boolean(clientKeyCertificate)
    };
  };

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

    const ldapConfig = await getLdapCfg({
      orgId: organization.id,
      isActive: true
    });

    const tlsOptions = buildLdapTlsOptions(ldapConfig);
    const opts = {
      server: {
        url: ldapConfig.url,
        bindDN: ldapConfig.bindDN,
        bindCredentials: ldapConfig.bindPass,
        uniqueUserAttribute: ldapConfig.uniqueUserAttribute,
        searchBase: ldapConfig.searchBase,
        searchFilter: ldapConfig.searchFilter || "(uid={{username}})",
        // searchAttributes: ["uid", "uidNumber", "givenName", "sn", "mail"],
        ...(tlsOptions ? { tlsOptions } : {})
      },
      passReqToCallback: true
    };

    return { opts, ldapConfig };
  };

  const ldapLoginInner = async ({
    ldapConfigId,
    externalId,
    firstName,
    lastName,
    email,
    groups,
    orgId,
    ip,
    userAgent,
    callbackPort
  }: TLdapLoginDTO) => {
    const serverCfg = await getServerCfg();

    if (serverCfg.enabledLoginMethods && !serverCfg.enabledLoginMethods.includes(LoginMethod.LDAP)) {
      throw new ForbiddenRequestError({
        message: "Login with LDAP is disabled by administrator."
      });
    }

    const ownedDomain = await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL });
    const sanitizedEmail = sanitizeEmail(email);
    validateEmail(sanitizedEmail);

    let userAlias = await userAliasDAL.findOne({
      externalId,
      orgId,
      aliasType: UserAliasType.LDAP
    });

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

    // The IdP is authoritative only when the org enforces SSO and owns the asserted domain. The
    // instance-level trustLdapEmails flag is a server admin's own decision to skip verification and
    // is kept apart from it.
    const isIdpAuthoritative = isIdpAuthoritativeForDomain({ isAuthEnforced: organization.authEnforced, ownedDomain });
    const skipEmailVerification = isIdpAuthoritative || Boolean(serverCfg.trustLdapEmails);

    // A stale, still-unverified alias may point at another user's account. Don't mutate that
    // account's org membership / group state until the IdP proves control of it (the
    // email-verification fallback below issues no session). Resolved against the existing alias
    // before any mutation; freshly created aliases are never stale.
    let isStaleAlias = false;
    if (userAlias) {
      // Verify the existing user's stored email domain + cross-org check
      const existingUser = await userDAL.findOne({ id: userAlias.userId });
      if (existingUser) {
        await verifyEmailDomainOwnership({
          email: existingUser.username,
          orgId,
          emailDomainDAL
        });
        isStaleAlias = isStaleSsoAlias({ user: existingUser, userAlias, assertedEmail: sanitizedEmail });
      }
      if (!isStaleAlias)
        await userDAL.transaction(async (tx) => {
          const [orgMembership] = await orgDAL.findMembership(
            {
              [`${TableName.Membership}.actorUserId` as "actorUserId"]: userAlias.userId,
              [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,
              [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization
            },
            { tx }
          );
          if (!orgMembership) {
            const { role, roleId } = await getDefaultOrgMembershipRole(organization.defaultMembershipRole);

            const membership = await orgDAL.createMembership(
              {
                actorUserId: userAlias.userId,
                scopeOrgId: orgId,
                scope: AccessScope.Organization,
                status: OrgMembershipStatus.Invited,
                isActive: true
              },
              tx
            );
            await membershipRoleDAL.create(
              {
                membershipId: membership.id,
                role,
                customRoleId: roleId
              },
              tx
            );
          } else if (!orgMembership.isActive) {
            throw new ForbiddenRequestError({ message: "User organization membership is inactive" });
          }
        });
    } else {
      let isNewUser = false;
      const identityLimit = getEnforcedIdentityLimit(await licenseService.getPlan(orgId));
      userAlias = await userDAL.transaction(async (tx) => {
        let newUser: TUsers | undefined;

        newUser = await userDAL.findOne({ username: sanitizedEmail }, tx);

        if (!newUser) {
          newUser = await userDAL.create(
            {
              username: sanitizedEmail,
              email: sanitizedEmail,
              firstName,
              lastName,
              authMethods: [],
              isGhost: false,
              isEmailVerified: skipEmailVerification,
              isAccepted: skipEmailVerification
            },
            tx
          );
          isNewUser = true;
        } else if (!newUser.firstName && firstName) {
          newUser = await userDAL.updateById(newUser.id, { firstName, ...(lastName ? { lastName } : {}) }, tx);
        }

        const newUserAlias = await userAliasDAL.create(
          {
            userId: newUser.id,
            username: sanitizedEmail,
            aliasType: UserAliasType.LDAP,
            externalId,
            emails: [sanitizedEmail],
            orgId,
            isEmailVerified: skipEmailVerification
          },
          tx
        );

        const [orgMembership] = await orgDAL.findMembership(
          {
            [`${TableName.Membership}.actorUserId` as "actorUserId"]: newUserAlias.userId,
            [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,
            [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization
          },
          { tx }
        );

        if (!orgMembership) {
          await throwOnPlanSeatLimitReached({
            licenseService,
            orgId,
            identityLimit,
            tx,
            aliasType: UserAliasType.LDAP
          });

          const { role, roleId } = await getDefaultOrgMembershipRole(organization.defaultMembershipRole);
          const membership = await orgDAL.createMembership(
            {
              actorUserId: newUser.id,
              scopeOrgId: orgId,
              scope: AccessScope.Organization,
              status: OrgMembershipStatus.Invited,
              isActive: true,
              inviteEmail: sanitizedEmail
            },
            tx
          );
          await membershipRoleDAL.create(
            {
              membershipId: membership.id,
              role,
              customRoleId: roleId
            },
            tx
          );
          // Only update the membership to Accepted if the user account is already completed.
        }

        return newUserAlias;
      });

      if (isNewUser) {
        void telemetryService.sendPostHogEvents({
          event: PostHogEventTypes.UserSignedUp,
          distinctId: sanitizedEmail,
          organizationId: orgId,
          properties: {
            username: sanitizedEmail,
            email: sanitizedEmail,
            signupMethod: "ldap"
          }
        });
      }
    }
    await licenseService.updateSubscriptionOrgMemberCount(organization.id);

    const pamCancellations: (() => void)[] = [];
    let user = await userDAL.transaction(async (tx) => {
      const newUser = await userDAL.findOne({ id: userAlias.userId }, tx);
      if (groups && !isStaleAlias) {
        const allLdapGroupMaps = await ldapGroupMapDAL.find({ ldapConfigId }, { tx });

        // cn equality in LDAP is case-insensitive (caseIgnoreMatch).
        const userLdapGroupCns = new Set(groups.map((group) => group.cn.toLowerCase()));
        const ldapGroupIdsToBePartOf = allLdapGroupMaps
          .filter((groupMap) => userLdapGroupCns.has(groupMap.ldapGroupCN.toLowerCase()))
          .map((groupMap) => groupMap.groupId);

        const groupsToBePartOf = await groupDAL.find(
          {
            orgId,
            $in: {
              id: ldapGroupIdsToBePartOf
            }
          },
          { tx }
        );
        const toBePartOfGroupIdsSet = new Set(groupsToBePartOf.map((groupToBePartOf) => groupToBePartOf.id));

        const ldapGroupIdsCurrentlyPartOf = (
          await userGroupMembershipDAL.find(
            {
              userId: newUser.id,
              $in: {
                groupId: allLdapGroupMaps.map((groupMap) => groupMap.groupId)
              }
            },
            { tx }
          )
        ).map((userGroupMembership) => userGroupMembership.groupId);

        const userGroupMembershipGroupIdsSet = new Set(ldapGroupIdsCurrentlyPartOf);

        for await (const group of groupsToBePartOf) {
          if (!userGroupMembershipGroupIdsSet.has(group.id)) {
            // add user to group that they should be part of
            await addUsersToGroupByUserIds({
              group,
              userIds: [newUser.id],
              userDAL,
              userGroupMembershipDAL,
              orgDAL,
              projectKeyDAL,
              projectDAL,
              projectBotDAL,
              membershipGroupDAL,
              usageMeteringService,
              tx
            });
          }
        }

        const groupsCurrentlyPartOf = await groupDAL.find(
          {
            orgId,
            $in: {
              id: ldapGroupIdsCurrentlyPartOf
            }
          },
          { tx }
        );

        for await (const group of groupsCurrentlyPartOf) {
          if (!toBePartOfGroupIdsSet.has(group.id)) {
            // remove user from group that they should no longer be part of
            const { sendPamCancellations } = await removeUsersFromGroupByUserIds({
              group,
              userIds: [newUser.id],
              userDAL,
              userGroupMembershipDAL,
              membershipGroupDAL,
              groupDAL,
              projectKeyDAL,
              additionalPrivilegeDAL,
              usageMeteringService,
              alertChannelRecipientDAL,
              eventEmitter,
              membershipDAL,
              membershipRoleDAL,
              pamAccountDAL,
              pamSessionDAL,
              gatewayV2Service,
              tx
            });
            pamCancellations.push(sendPamCancellations);
          }
        }
      }

      return newUser;
    });
    pamCancellations.forEach((send) => send());

    // When SSO is enforced, mark the user + alias as verified/accepted before issuing a session.
    if (skipEmailVerification) {
      ({ user, userAlias } = await ensureSsoAccountVerified({
        user,
        userAlias,
        assertedEmail: sanitizedEmail,
        userDAL,
        userAliasDAL
      }));
    }

    user = await syncSsoUserProfile({
      user,
      userAlias,
      assertedEmail: sanitizedEmail,
      assertedFirstName: firstName,
      assertedLastName: lastName,
      orgId,
      isIdpAuthoritative,
      userDAL,
      userAliasDAL,
      emailDomainDAL,
      auditLogService
    });

    if (user.email && (!userAlias.isEmailVerified || !user.isAccepted)) {
      const token = await tokenService.createTokenForUser({
        type: TokenType.TOKEN_EMAIL_VERIFICATION,
        userId: user.id,
        aliasId: userAlias.id
      });

      await smtpService.sendMail({
        template: SmtpTemplates.EmailVerification,
        subjectLine: `Infisical confirmation code: ${token}`,
        recipients: [user.email],
        substitutions: {
          code: token
        }
      });
    }

    const callbackResult = await loginService.processProviderCallback({
      user,
      authMethod: AuthMethod.LDAP,
      isEmailVerified: Boolean(userAlias.isEmailVerified),
      aliasId: userAlias.id,
      ip,
      userAgent,
      organizationId: organization.id,
      callbackPort
    });

    return callbackResult;
  };

  const ldapLogin = async (dto: TLdapLoginDTO) => {
    const authMetricStartTime = performance.now();
    const appCfg = getConfig();
    try {
      const callbackResult = await ldapLoginInner(dto);

      if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
        authAttemptCounter.add(1, {
          "infisical.user.email": dto.email,
          "infisical.organization.id": dto.orgId,
          "infisical.auth.method": AuthAttemptAuthMethod.LDAP,
          "infisical.auth.result": AuthAttemptAuthResult.SUCCESS,
          "client.address": dto.ip,
          "user_agent.original": dto.userAgent
        });
      }

      recordAuthAttemptMetric({
        startTime: authMetricStartTime,
        method: AuthAttemptAuthMethod.LDAP,
        result: AuthAttemptAuthResult.SUCCESS,
        orgId: dto.orgId
      });

      return callbackResult;
    } catch (error) {
      if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
        authAttemptCounter.add(1, {
          "infisical.user.email": dto.email,
          "infisical.organization.id": dto.orgId,
          "infisical.auth.method": AuthAttemptAuthMethod.LDAP,
          "infisical.auth.result": AuthAttemptAuthResult.FAILURE,
          "client.address": dto.ip,
          "user_agent.original": dto.userAgent
        });
      }

      recordAuthAttemptMetric({
        startTime: authMetricStartTime,
        method: AuthAttemptAuthMethod.LDAP,
        result: AuthAttemptAuthResult.FAILURE,
        orgId: dto.orgId,
        error
      });

      throw error;
    }
  };

  const getLdapGroupMaps = async ({
    ldapConfigId,
    actor,
    actorId,
    orgId,
    actorAuthMethod,
    actorOrgId
  }: TGetLdapGroupMapsDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      scope: OrganizationActionScope.ParentOrganization,
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Ldap);

    const ldapConfig = await ldapConfigDAL.findOne({
      id: ldapConfigId,
      orgId
    });

    if (!ldapConfig) {
      throw new NotFoundError({
        message: `Failed to find organization LDAP data with ID '${ldapConfigId}' in organization with ID ${orgId}`
      });
    }

    const groupMaps = await ldapGroupMapDAL.findLdapGroupMapsByLdapConfigId(ldapConfigId);

    return groupMaps;
  };

  const createLdapGroupMap = async ({
    ldapConfigId,
    ldapGroupCN,
    groupSlug,
    actor,
    actorId,
    orgId,
    actorAuthMethod,
    actorOrgId
  }: TCreateLdapGroupMapDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      scope: OrganizationActionScope.ParentOrganization,
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Create, OrgPermissionSubjects.Ldap);

    const plan = await licenseService.getPlan(orgId);
    if (!plan.ldap)
      throw new BadRequestError({
        message: "Failed to create LDAP group map due to plan restriction. Upgrade plan to create LDAP group map."
      });

    const ldapConfig = await getLdapCfg({
      orgId,
      id: ldapConfigId
    });

    if (!ldapConfig.groupSearchBase) {
      throw new BadRequestError({
        message: "Configure a group search base in your LDAP configuration in order to proceed."
      });
    }

    const groupSearchFilter = `(cn=${ldapGroupCN})`;
    const groups = await searchGroups(ldapConfig, groupSearchFilter, ldapConfig.groupSearchBase);

    // cn equality in LDAP is case-insensitive (caseIgnoreMatch). Prefer an exact-case
    // match; fall back to a case-variant only when it is unambiguous, since distinct
    // groups in different containers can have CNs differing only by case.
    const candidateGroups = groups.filter((g) => g.cn.toLowerCase() === ldapGroupCN.toLowerCase());
    const distinctCns = new Set(candidateGroups.map((g) => g.cn));
    const matchedGroup =
      candidateGroups.find((g) => g.cn === ldapGroupCN) ?? (distinctCns.size === 1 ? candidateGroups[0] : undefined);
    if (!matchedGroup) {
      if (distinctCns.size > 1) {
        throw new BadRequestError({
          message: `Multiple LDAP groups match CN '${ldapGroupCN}' case-insensitively: ${[...distinctCns].join(", ")}. Enter the exact CN of the intended group.`
        });
      }
      throw new NotFoundError({
        message: "Failed to find LDAP Group CN"
      });
    }

    const group = await groupDAL.findOne({ slug: groupSlug, orgId });
    if (!group) {
      throw new NotFoundError({
        message: `Failed to find group with slug '${groupSlug}' in organization with ID '${orgId}'`
      });
    }

    const groupMap = await ldapGroupMapDAL.create({
      ldapConfigId,
      ldapGroupCN: matchedGroup.cn,
      groupId: group.id
    });

    return groupMap;
  };

  const deleteLdapGroupMap = async ({
    ldapConfigId,
    ldapGroupMapId,
    actor,
    actorId,
    orgId,
    actorAuthMethod,
    actorOrgId
  }: TDeleteLdapGroupMapDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      scope: OrganizationActionScope.ParentOrganization,
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Delete, OrgPermissionSubjects.Ldap);

    const plan = await licenseService.getPlan(orgId);
    if (!plan.ldap)
      throw new BadRequestError({
        message: "Failed to delete LDAP group map due to plan restriction. Upgrade plan to delete LDAP group map."
      });

    const ldapConfig = await ldapConfigDAL.findOne({
      id: ldapConfigId,
      orgId
    });

    if (!ldapConfig) {
      throw new NotFoundError({
        message: `Failed to find organization LDAP data with ID '${ldapConfigId}' in organization with ID ${orgId}`
      });
    }

    const [deletedGroupMap] = await ldapGroupMapDAL.delete({
      ldapConfigId: ldapConfig.id,
      id: ldapGroupMapId
    });

    return deletedGroupMap;
  };

  const testLDAPConnection = async ({
    actor,
    actorId,
    orgId,
    actorAuthMethod,
    actorOrgId,
    bindDN,
    bindPass,
    caCert,
    clientCertificate,
    clientKeyCertificate,
    url
  }: TTestLdapConnectionDTO) => {
    const { permission } = await permissionService.getOrgPermission({
      scope: OrganizationActionScope.ParentOrganization,
      actor,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId
    });
    ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Create, OrgPermissionSubjects.Ldap);

    const plan = await licenseService.getPlan(orgId);
    if (!plan.ldap)
      throw new BadRequestError({
        message: "Failed to test LDAP connection due to plan restriction. Upgrade plan to test the LDAP connection."
      });

    try {
      await blockLocalAndPrivateIpAddresses(url);
    } catch (error) {
      if (error instanceof BadRequestError) throw error;
      // an unresolvable host fails the same way the connection itself would
      return false;
    }

    if (Boolean(clientCertificate) !== Boolean(clientKeyCertificate)) {
      throw new BadRequestError({
        message: "clientCertificate and clientKeyCertificate must be provided together for mTLS."
      });
    }

    return testLDAPConfig({
      bindDN,
      bindPass,
      caCert,
      clientCertificate,
      clientKeyCertificate,
      url
    });
  };

  return {
    createLdapCfg,
    updateLdapCfg,
    getLdapCfgWithPermissionCheck,
    getLdapCfg,
    // getLdapPassportOpts,
    ldapLogin,
    bootLdap,
    getLdapGroupMaps,
    createLdapGroupMap,
    deleteLdapGroupMap,
    testLDAPConnection
  };
};