Skip to content

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

41.5 KB
Raw Blame
import { ForbiddenError, subject } from "@casl/ability";
import { requestContext } from "@fastify/request-context";

import { AccessScope, ActionProjectType, IdentityAuthMethod, OrganizationActionScope } from "@app/db/schemas";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import {
  BadRequestError,
  ForbiddenRequestError,
  NotFoundError,
  RateLimitError,
  UnauthorizedError
} from "@app/lib/errors";
import { checkIPAgainstBlocklist, extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";
import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import {
  AuthAttemptAuthMethod,
  AuthAttemptAuthResult,
  authAttemptCounter,
  recordAuthAttemptMetric
} from "@app/lib/telemetry/metrics";
import { TEventEmitter } from "@app/services/event-outbox/event-outbox-types";
import {
  emitIdentityAuthMethodChanged,
  IdentityAuthMethodChange
} from "@app/services/identity/identity-auth-method-events";

import { ActorType } from "../auth/auth-type";
import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";
import { assertIdentityAuthAccessAllowed } from "../identity/identity-auth-permission-fns";
import { TIdentityDALFactory } from "../identity/identity-dal";
import {
  clearIdentityLockoutsForAuthMethod,
  clearIdentityLockoutState,
  getIdentityLockoutState,
  identityLockoutLockKey,
  persistIdentityLockoutState
} from "../identity/identity-fns";
import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";
import { recordIdentityLastLogin, shouldRecordIdentityLastLogin } from "../membership-identity/membership-identity-fns";
import { TOrgDALFactory } from "../org/org-dal";
import { validateIdentityUpdateForSuperAdminPrivileges } from "../super-admin/super-admin-fns";
import { TIdentityUaClientSecretDALFactory } from "./identity-ua-client-secret-dal";
import { TIdentityUaDALFactory } from "./identity-ua-dal";
import {
  TAttachUaDTO,
  TClearUaLockoutsDTO,
  TCreateUaClientSecretDTO,
  TGetUaClientSecretsDTO,
  TGetUaDTO,
  TGetUniversalAuthClientSecretByIdDTO,
  TLoginUaDTO,
  TRevokeUaClientSecretDTO,
  TRevokeUaDTO,
  TUpdateUaDTO
} from "./identity-ua-types";

type TIdentityUaServiceFactoryDep = {
  identityDAL: Pick<TIdentityDALFactory, "findById">;
  identityUaDAL: TIdentityUaDALFactory;
  identityUaClientSecretDAL: TIdentityUaClientSecretDALFactory;
  membershipIdentityDAL: TMembershipIdentityDALFactory;
  permissionService: Pick<
    TPermissionServiceFactory,
    "getOrgPermission" | "getProjectPermission" | "getActorGrantAbilities"
  >;
  licenseService: Pick<TLicenseServiceFactory, "getPlan">;
  orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;
  identityAccessTokenService: Pick<
    TIdentityAccessTokenServiceFactory,
    | "issueIdentityAccessToken"
    | "revokeTokensForIdentityAuthMethod"
    | "revokeAllTokensForClientSecret"
    | "invalidateTrustedIpsCache"
  >;
  keyStore: Pick<
    TKeyStoreFactory,
    | "setItemWithExpiryNX"
    | "getItemPrimary"
    | "setIndexedItemWithExpiry"
    | "deleteIndexedItems"
    | "sortedSetMembersPrimary"
    | "acquireLock"
  >;
  eventEmitter: TEventEmitter;
};

export type TIdentityUaServiceFactory = ReturnType<typeof identityUaServiceFactory>;

// debounce per-secret usage writes so login bursts on one unlimited secret don't pile up on its row lock
const UA_CLIENT_SECRET_USAGE_DEBOUNCE_SECONDS = 10;

export const identityUaServiceFactory = ({
  identityUaDAL,
  identityUaClientSecretDAL,
  membershipIdentityDAL,
  permissionService,
  licenseService,
  orgDAL,
  keyStore,
  identityDAL,
  identityAccessTokenService,
  eventEmitter
}: TIdentityUaServiceFactoryDep) => {
  const login = async ({ clientId, clientSecret, ip, organizationSlug }: TLoginUaDTO) => {
    const authMetricStartTime = performance.now();
    const appCfg = getConfig();
    const identityUa = await identityUaDAL.findOne({ clientId });
    if (!identityUa) {
      throw new UnauthorizedError({
        message: "Invalid credentials",
        detail: { reasonCode: "client_id_not_found" }
      });
    }

    const identity = await requestMemoize(requestMemoKeys.identityFindById(identityUa.identityId), () =>
      identityDAL.findById(identityUa.identityId)
    );
    const org = await requestMemoize(requestMemoKeys.orgFindById(identity.orgId), () =>
      orgDAL.findById(identity.orgId)
    );
    const isSubOrgIdentity = Boolean(org.rootOrgId);

    // If the identity is a sub-org identity, then the scope is always the org.id, and if it's a root org identity, then we need to resolve the scope if a subOrganizationName is specified
    let subOrganizationId = isSubOrgIdentity ? org.id : null;

    try {
      checkIPAgainstBlocklist({
        ipAddress: ip,
        trustedIps: identityUa.clientSecretTrustedIps as TIp[]
      });

      const lockoutSelector = {
        identityId: identityUa.identityId,
        authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
        slug: clientId
      };

      let lockout = await getIdentityLockoutState(lockoutSelector, keyStore);

      if (lockout && lockout.lockedOut && identityUa.lockoutEnabled) {
        throw new UnauthorizedError({
          message: "This identity auth method is temporarily locked, please try again later",
          detail: {
            reasonCode: "temporarily_locked",
            identityId: identityUa.identityId,
            orgId: identity.orgId,
            identityName: identity.name
          }
        });
      }

      const clientSecretPrefix = clientSecret.slice(0, 4);
      const clientSecretInfo = await identityUaClientSecretDAL.find({
        identityUAId: identityUa.id,
        isClientSecretRevoked: false,
        clientSecretPrefix
      });

      let validClientSecretInfo: (typeof clientSecretInfo)[0] | null = null;
      for await (const info of clientSecretInfo) {
        const isMatch = await crypto.hashing().compareHash(clientSecret, info.clientSecretHash);

        if (isMatch) {
          validClientSecretInfo = info;
          break;
        }
      }

      if (!validClientSecretInfo) {
        if (identityUa.lockoutEnabled) {
          let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | undefined;
          try {
            lock = await keyStore.acquireLock(
              [identityLockoutLockKey(identityUa.identityId, IdentityAuthMethod.UNIVERSAL_AUTH, clientId)],
              300,
              {
                retryCount: 3,
                retryDelay: 300,
                retryJitter: 100
              }
            );

            // Re-fetch the latest lockout data while holding the lock
            lockout = (await getIdentityLockoutState(lockoutSelector, keyStore)) ?? {
              lockedOut: false,
              failedAttempts: 0
            };

            if (lockout.lockedOut) {
              throw new UnauthorizedError({
                message: "This identity auth method is temporarily locked, please try again later",
                detail: {
                  reasonCode: "temporarily_locked",
                  identityId: identityUa.identityId,
                  orgId: identity.orgId,
                  identityName: identity.name
                }
              });
            }

            lockout.failedAttempts += 1;
            if (lockout.failedAttempts >= identityUa.lockoutThreshold) {
              lockout.lockedOut = true;
            }

            await persistIdentityLockoutState(
              {
                ...lockoutSelector,
                expiryInSeconds: lockout.lockedOut
                  ? identityUa.lockoutDurationSeconds
                  : identityUa.lockoutCounterResetSeconds
              },
              lockout,
              keyStore
            );
          } catch (e) {
            if (lock === undefined) {
              logger.info(
                `identity login failed to acquire lock [identityId=${identityUa.identityId}] [authMethod=${IdentityAuthMethod.UNIVERSAL_AUTH}]`
              );
              throw new RateLimitError({ message: "Failed to acquire lock: rate limit exceeded" });
            }
            throw e;
          } finally {
            if (lock) {
              await lock.release();
            }
          }
        }

        throw new UnauthorizedError({
          message: "Invalid credentials",
          detail: {
            reasonCode: "invalid_client_secret",
            identityId: identityUa.identityId,
            orgId: identity.orgId,
            identityName: identity.name
          }
        });
      } else if (lockout) {
        // If credentials are valid, clear any existing lockout record
        await clearIdentityLockoutState(lockoutSelector, keyStore);
      }

      const { clientSecretTTL, clientSecretNumUses, clientSecretNumUsesLimit } = validClientSecretInfo;
      if (Number(clientSecretTTL) > 0) {
        const clientSecretCreated = new Date(validClientSecretInfo.createdAt);
        const ttlInMilliseconds = Number(clientSecretTTL) * 1000;
        const currentDate = new Date();
        const expirationTime = new Date(clientSecretCreated.getTime() + ttlInMilliseconds);

        if (currentDate > expirationTime) {
          await identityUaClientSecretDAL.updateById(validClientSecretInfo.id, {
            isClientSecretRevoked: true
          });

          throw new UnauthorizedError({
            message: "Access denied due to expired client secret",
            detail: {
              reasonCode: "client_secret_expired",
              identityId: identityUa.identityId,
              orgId: identity.orgId,
              identityName: identity.name
            }
          });
        }
      }

      if (Number(clientSecretNumUsesLimit) > 0 && Number(clientSecretNumUses) >= Number(clientSecretNumUsesLimit)) {
        // number of times client secret can be used for
        // a login operation reached
        await identityUaClientSecretDAL.updateById(validClientSecretInfo.id, {
          isClientSecretRevoked: true
        });
        throw new UnauthorizedError({
          message: "Access denied due to client secret usage limit reached",
          detail: {
            reasonCode: "client_secret_usage_limit_reached",
            identityId: identityUa.identityId,
            orgId: identity.orgId,
            identityName: identity.name
          }
        });
      }

      if (organizationSlug && org.slug !== organizationSlug) {
        if (!isSubOrgIdentity) {
          const subOrg = await orgDAL.findOne({ rootOrgId: org.id, slug: organizationSlug });

          if (!subOrg) {
            throw new NotFoundError({ message: `Sub organization with name ${organizationSlug} not found` });
          }

          // Allow access if identity has direct org membership or access via a group (e.g. root-org group linked to sub-org)
          const subOrgMembership = await orgDAL.findEffectiveOrgMembership({
            actorType: ActorType.IDENTITY,
            actorId: identity.id,
            orgId: subOrg.id
          });

          if (!subOrgMembership) {
            throw new UnauthorizedError({
              message: `Identity not authorized to access sub organization ${organizationSlug}`,
              detail: {
                reasonCode: "sub_org_unauthorized",
                identityId: identityUa.identityId,
                orgId: identity.orgId,
                identityName: identity.name
              }
            });
          }

          subOrganizationId = subOrg.id;
        }
      }

      const clientSecretId = validClientSecretInfo.id;

      const [shouldIncrementUsage, shouldRecordLastLogin] = await Promise.all([
        clientSecretNumUsesLimit > 0
          ? // finite usage limit: count must stay exact, so increment synchronously (low-frequency, no contention)
            Promise.resolve(true)
          : // unlimited secret: numUses is informational, so collapse a login storm to one row write per window
            keyStore
              .setItemWithExpiryNX(
                KeyStorePrefixes.IdentityUaClientSecretUsageDebounce(clientSecretId),
                UA_CLIENT_SECRET_USAGE_DEBOUNCE_SECONDS,
                "1"
              )
              .then(Boolean),
        shouldRecordIdentityLastLogin(keyStore, identity.id)
      ]);

      if (shouldIncrementUsage || shouldRecordLastLogin) {
        await identityUaDAL.transaction(async (tx) => {
          if (shouldIncrementUsage) {
            await identityUaClientSecretDAL.incrementUsage(clientSecretId, tx);
          }
          if (shouldRecordLastLogin) {
            await recordIdentityLastLogin(membershipIdentityDAL, identity, IdentityAuthMethod.UNIVERSAL_AUTH, tx);
          }
        });
      }

      const subOrgDetails =
        subOrganizationId && subOrganizationId !== org.id ? await orgDAL.findById(subOrganizationId) : null;
      const tokenScopeOrg = subOrgDetails ?? org;
      const tokenRootOrgId = tokenScopeOrg.rootOrgId ?? tokenScopeOrg.id;
      const tokenParentOrgId = tokenScopeOrg.parentOrgId ?? tokenRootOrgId;

      const { accessToken, identityAccessToken } = await identityAccessTokenService.issueIdentityAccessToken({
        identityId: identityUa.identityId,
        identityName: identity.name,
        authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
        orgId: tokenScopeOrg.id,
        rootOrgId: tokenRootOrgId,
        parentOrgId: tokenParentOrgId,
        subOrganizationId,
        accessTokenTTL: Number(identityUa.accessTokenTTL),
        accessTokenMaxTTL: Number(identityUa.accessTokenMaxTTL),
        accessTokenNumUsesLimit: Number(identityUa.accessTokenNumUsesLimit),
        accessTokenPeriod: Number(identityUa.accessTokenPeriod),
        accessTokenTrustedIps: identityUa.accessTokenTrustedIps as TIp[],
        clientSecretId: validClientSecretInfo.id
      });

      if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
        authAttemptCounter.add(1, {
          "infisical.identity.id": identityUa.identityId,
          "infisical.identity.name": identity.name,
          "infisical.organization.id": org.id,
          "infisical.organization.name": org.name,
          "infisical.identity.auth_method": AuthAttemptAuthMethod.UNIVERSAL_AUTH,
          "infisical.identity.auth_result": AuthAttemptAuthResult.SUCCESS,
          "client.address": requestContext.get(RequestContextKey.Ip),
          "user_agent.original": requestContext.get(RequestContextKey.UserAgent)
        });
      }

      recordAuthAttemptMetric({
        startTime: authMetricStartTime,
        method: AuthAttemptAuthMethod.UNIVERSAL_AUTH,
        result: AuthAttemptAuthResult.SUCCESS,
        orgId: org.id
      });

      return {
        accessToken,
        identityUa,
        validClientSecretInfo,
        identityAccessToken,
        identity,
        accessTokenTTL: identityAccessToken.accessTokenTTL,
        accessTokenMaxTTL: identityAccessToken.accessTokenMaxTTL
      };
    } catch (error) {
      if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
        authAttemptCounter.add(1, {
          "infisical.identity.id": identityUa.identityId,
          "infisical.identity.name": identity.name,
          "infisical.organization.id": org.id,
          "infisical.organization.name": org.name,
          "infisical.identity.auth_method": AuthAttemptAuthMethod.UNIVERSAL_AUTH,
          "infisical.identity.auth_result": AuthAttemptAuthResult.FAILURE,
          "client.address": requestContext.get(RequestContextKey.Ip),
          "user_agent.original": requestContext.get(RequestContextKey.UserAgent)
        });
      }

      recordAuthAttemptMetric({
        startTime: authMetricStartTime,
        method: AuthAttemptAuthMethod.UNIVERSAL_AUTH,
        result: AuthAttemptAuthResult.FAILURE,
        orgId: org.id,
        error
      });
      throw error;
    }
  };

  const attachUniversalAuth = async ({
    accessTokenMaxTTL,
    identityId,
    accessTokenNumUsesLimit,
    accessTokenTTL,
    accessTokenTrustedIps,
    clientSecretTrustedIps,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId,
    isActorSuperAdmin,
    accessTokenPeriod,
    lockoutEnabled,
    lockoutThreshold,
    lockoutDurationSeconds,
    lockoutCounterResetSeconds
  }: TAttachUaDTO) => {
    const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
      scopeData: {
        scope: AccessScope.Organization,
        orgId: actorOrgId
      },
      identityId
    });
    if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });

    if (identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.UNIVERSAL_AUTH)) {
      throw new BadRequestError({
        message: "Failed to add universal auth to already configured identity"
      });
    }
    if (identityMembershipOrg.identity.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

    if (accessTokenMaxTTL > 0 && accessTokenTTL > accessTokenMaxTTL) {
      throw new BadRequestError({ message: "Access token TTL cannot be greater than max TTL" });
    }

    await assertIdentityAuthAccessAllowed(
      { permissionService, orgDAL },
      {
        identityId,
        orgId: identityMembershipOrg.scopeOrgId,
        projectId: identityMembershipOrg.identity.projectId,
        action: OrgPermissionIdentityActions.EditAuth,
        baseMessage: "Failed to add universal auth to identity with more privileged role",
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId
      }
    );

    await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);

    const plan = await licenseService.getPlan(identityMembershipOrg.scopeOrgId);
    const reformattedClientSecretTrustedIps = clientSecretTrustedIps.map((clientSecretTrustedIp) => {
      if (
        !plan.ipAllowlisting &&
        clientSecretTrustedIp.ipAddress !== "0.0.0.0/0" &&
        clientSecretTrustedIp.ipAddress !== "::/0"
      )
        throw new BadRequestError({
          message:
            "Failed to add IP access range to service token due to plan restriction. Upgrade plan to add IP access range."
        });
      if (!isValidIpOrCidr(clientSecretTrustedIp.ipAddress))
        throw new BadRequestError({
          message: "The IP is not a valid IPv4, IPv6, or CIDR block"
        });
      return extractIPDetails(clientSecretTrustedIp.ipAddress);
    });
    const reformattedAccessTokenTrustedIps = accessTokenTrustedIps.map((accessTokenTrustedIp) => {
      if (
        !plan.ipAllowlisting &&
        accessTokenTrustedIp.ipAddress !== "0.0.0.0/0" &&
        accessTokenTrustedIp.ipAddress !== "::/0"
      )
        throw new BadRequestError({
          message:
            "Failed to add IP access range to service token due to plan restriction. Upgrade plan to add IP access range."
        });
      if (!isValidIpOrCidr(accessTokenTrustedIp.ipAddress))
        throw new BadRequestError({
          message: "The IP is not a valid IPv4, IPv6, or CIDR block"
        });
      return extractIPDetails(accessTokenTrustedIp.ipAddress);
    });

    const identityUa = await identityUaDAL.transaction(async (tx) => {
      const doc = await identityUaDAL.create(
        {
          identityId: identityMembershipOrg.identity.id,
          clientId: crypto.nativeCrypto.randomUUID(),
          clientSecretTrustedIps: JSON.stringify(reformattedClientSecretTrustedIps),
          accessTokenMaxTTL,
          accessTokenTTL,
          accessTokenNumUsesLimit,
          accessTokenTrustedIps: JSON.stringify(reformattedAccessTokenTrustedIps),
          accessTokenPeriod,
          lockoutEnabled,
          lockoutThreshold,
          lockoutDurationSeconds,
          lockoutCounterResetSeconds
        },
        tx
      );
      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
          change: IdentityAuthMethodChange.Added,
          actor,
          actorId
        },
        tx
      );
      return doc;
    });
    await identityAccessTokenService.invalidateTrustedIpsCache(
      identityMembershipOrg.identity.id,
      IdentityAuthMethod.UNIVERSAL_AUTH
    );
    return { ...identityUa, orgId: identityMembershipOrg.scopeOrgId };
  };

  const updateUniversalAuth = async ({
    accessTokenMaxTTL,
    identityId,
    accessTokenNumUsesLimit,
    accessTokenTTL,
    accessTokenTrustedIps,
    clientSecretTrustedIps,
    accessTokenPeriod,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId,
    lockoutEnabled,
    lockoutThreshold,
    lockoutDurationSeconds,
    lockoutCounterResetSeconds,
    isActorSuperAdmin
  }: TUpdateUaDTO) => {
    const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
      scopeData: {
        scope: AccessScope.Organization,
        orgId: actorOrgId
      },
      identityId
    });
    if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });

    const uaIdentityAuth = await identityUaDAL.findOne({ identityId });
    if (!uaIdentityAuth) {
      throw new NotFoundError({ message: `Failed to find universal auth for identity with ID ${identityId}` });
    }

    if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.UNIVERSAL_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have universal auth"
      });
    }

    if (identityMembershipOrg.identity.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

    if (
      (accessTokenMaxTTL || uaIdentityAuth.accessTokenMaxTTL) > 0 &&
      (accessTokenTTL || uaIdentityAuth.accessTokenMaxTTL) > (accessTokenMaxTTL || uaIdentityAuth.accessTokenMaxTTL)
    ) {
      throw new BadRequestError({ message: "Access token TTL cannot be greater than max TTL" });
    }

    await assertIdentityAuthAccessAllowed(
      { permissionService, orgDAL },
      {
        identityId,
        orgId: identityMembershipOrg.scopeOrgId,
        projectId: identityMembershipOrg.identity.projectId,
        action: OrgPermissionIdentityActions.EditAuth,
        baseMessage: "Failed to update universal auth of identity with more privileged role",
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId
      }
    );

    await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);

    const plan = await licenseService.getPlan(identityMembershipOrg.scopeOrgId);
    const reformattedClientSecretTrustedIps = clientSecretTrustedIps?.map((clientSecretTrustedIp) => {
      if (
        !plan.ipAllowlisting &&
        clientSecretTrustedIp.ipAddress !== "0.0.0.0/0" &&
        clientSecretTrustedIp.ipAddress !== "::/0"
      )
        throw new BadRequestError({
          message:
            "Failed to add IP access range to service token due to plan restriction. Upgrade plan to add IP access range."
        });
      if (!isValidIpOrCidr(clientSecretTrustedIp.ipAddress))
        throw new BadRequestError({
          message: "The IP is not a valid IPv4, IPv6, or CIDR block"
        });
      return extractIPDetails(clientSecretTrustedIp.ipAddress);
    });
    const reformattedAccessTokenTrustedIps = accessTokenTrustedIps?.map((accessTokenTrustedIp) => {
      if (
        !plan.ipAllowlisting &&
        accessTokenTrustedIp.ipAddress !== "0.0.0.0/0" &&
        accessTokenTrustedIp.ipAddress !== "::/0"
      )
        throw new BadRequestError({
          message:
            "Failed to add IP access range to service token due to plan restriction. Upgrade plan to add IP access range."
        });
      if (!isValidIpOrCidr(accessTokenTrustedIp.ipAddress))
        throw new BadRequestError({
          message: "The IP is not a valid IPv4, IPv6, or CIDR block"
        });
      return extractIPDetails(accessTokenTrustedIp.ipAddress);
    });

    const updatedUaAuth = await identityUaDAL.transaction(async (tx) => {
      const doc = await identityUaDAL.updateById(
        uaIdentityAuth.id,
        {
          clientSecretTrustedIps: reformattedClientSecretTrustedIps
            ? JSON.stringify(reformattedClientSecretTrustedIps)
            : undefined,
          accessTokenMaxTTL,
          accessTokenTTL,
          accessTokenNumUsesLimit,
          accessTokenPeriod,
          accessTokenTrustedIps: reformattedAccessTokenTrustedIps
            ? JSON.stringify(reformattedAccessTokenTrustedIps)
            : undefined,
          lockoutEnabled,
          lockoutThreshold,
          lockoutDurationSeconds,
          lockoutCounterResetSeconds
        },
        tx
      );
      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
          change: IdentityAuthMethodChange.Updated,
          actor,
          actorId
        },
        tx
      );
      return doc;
    });
    await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.UNIVERSAL_AUTH);
    return { ...updatedUaAuth, orgId: identityMembershipOrg.scopeOrgId };
  };

  const getIdentityUniversalAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetUaDTO) => {
    const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
      scopeData: {
        scope: AccessScope.Organization,
        orgId: actorOrgId
      },
      identityId
    });
    if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });

    const uaIdentityAuth = await identityUaDAL.findOne({ identityId });
    if (!uaIdentityAuth) {
      throw new NotFoundError({ message: `Failed to find universal auth for identity with ID ${identityId}` });
    }

    if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.UNIVERSAL_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have universal auth"
      });
    }
    if (identityMembershipOrg.identity.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

    if (identityMembershipOrg.identity.projectId) {
      const { permission } = await permissionService.getProjectPermission({
        actionProjectType: ActionProjectType.Any,
        actor,
        actorId,
        projectId: identityMembershipOrg.identity.projectId,
        actorAuthMethod,
        actorOrgId
      });

      ForbiddenError.from(permission).throwUnlessCan(
        ProjectPermissionIdentityActions.Read,
        subject(ProjectPermissionSub.Identity, { identityId })
      );
    } else {
      const { permission } = await permissionService.getOrgPermission({
        scope: OrganizationActionScope.Any,
        actor,
        actorId,
        orgId: identityMembershipOrg.scopeOrgId,
        actorAuthMethod,
        actorOrgId
      });
      ForbiddenError.from(permission).throwUnlessCan(OrgPermissionIdentityActions.Read, OrgPermissionSubjects.Identity);
    }
    return { ...uaIdentityAuth, orgId: identityMembershipOrg.scopeOrgId };
  };

  const revokeIdentityUniversalAuth = async ({
    identityId,
    actorId,
    actor,
    actorAuthMethod,
    actorOrgId,
    isActorSuperAdmin
  }: TRevokeUaDTO) => {
    const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
      scopeData: {
        scope: AccessScope.Organization,
        orgId: actorOrgId
      },
      identityId
    });
    if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });

    if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.UNIVERSAL_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have universal auth"
      });
    }
    if (identityMembershipOrg.identity.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

    await assertIdentityAuthAccessAllowed(
      { permissionService, orgDAL },
      {
        identityId,
        orgId: identityMembershipOrg.scopeOrgId,
        projectId: identityMembershipOrg.identity.projectId,
        action: OrgPermissionIdentityActions.RevokeAuth,
        baseMessage: "Failed to revoke universal auth of identity with more privileged role",
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId
      }
    );

    await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
    const revokedIdentityUniversalAuth = await identityUaDAL.transaction(async (tx) => {
      const deletedUniversalAuth = await identityUaDAL.delete({ identityId }, tx);
      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
          change: IdentityAuthMethodChange.Removed,
          actor,
          actorId
        },
        tx
      );
      return { ...deletedUniversalAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };
    });

    // Scoped marker so leaked tokens issued via UA stop authenticating once an
    // admin detaches the method; tokens minted via other still-attached methods
    // on the same identity stay valid (PLATFOR-359).
    await identityAccessTokenService.revokeTokensForIdentityAuthMethod({
      identityId,
      authMethod: IdentityAuthMethod.UNIVERSAL_AUTH
    });
    await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.UNIVERSAL_AUTH);

    return revokedIdentityUniversalAuth;
  };

  const createUniversalAuthClientSecret = async ({
    actor,
    actorId,
    actorOrgId,
    identityId,
    ttl,
    actorAuthMethod,
    description,
    numUsesLimit,
    isActorSuperAdmin
  }: TCreateUaClientSecretDTO) => {
    const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
      scopeData: {
        scope: AccessScope.Organization,
        orgId: actorOrgId
      },
      identityId
    });
    if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });

    if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.UNIVERSAL_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have universal auth"
      });
    }
    if (identityMembershipOrg.identity.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

    await assertIdentityAuthAccessAllowed(
      { permissionService, orgDAL },
      {
        identityId,
        orgId: identityMembershipOrg.scopeOrgId,
        projectId: identityMembershipOrg.identity.projectId,
        action: OrgPermissionIdentityActions.CreateToken,
        baseMessage: "Failed to create client secret for identity with more privileged role",
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId
      }
    );

    await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);

    const appCfg = getConfig();
    const clientSecret = crypto.randomBytes(32).toString("hex");
    const clientSecretHash = await crypto.hashing().createHash(clientSecret, appCfg.SALT_ROUNDS);

    const identityUaAuth = await identityUaDAL.findOne({ identityId: identityMembershipOrg.identity.id });
    if (!identityUaAuth) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });

    const identityUaClientSecret = await identityUaDAL.transaction(async (tx) => {
      const doc = await identityUaClientSecretDAL.create(
        {
          identityUAId: identityUaAuth.id,
          description,
          clientSecretPrefix: clientSecret.slice(0, 4),
          clientSecretHash,
          clientSecretNumUses: 0,
          clientSecretNumUsesLimit: numUsesLimit,
          clientSecretTTL: ttl,
          isClientSecretRevoked: false
        },
        tx
      );
      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
          change: IdentityAuthMethodChange.CredentialAdded,
          actor,
          actorId,
          credential: { id: doc.id, name: doc.description || doc.clientSecretPrefix }
        },
        tx
      );
      return doc;
    });
    return {
      clientSecret,
      clientSecretData: identityUaClientSecret,
      orgId: identityMembershipOrg.scopeOrgId
    };
  };

  const getUniversalAuthClientSecrets = async ({
    actor,
    actorId,
    actorOrgId,
    actorAuthMethod,
    identityId
  }: TGetUaClientSecretsDTO) => {
    const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
      scopeData: {
        scope: AccessScope.Organization,
        orgId: actorOrgId
      },
      identityId
    });
    if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });

    if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.UNIVERSAL_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have universal auth"
      });
    }
    if (identityMembershipOrg.identity.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

    await assertIdentityAuthAccessAllowed(
      { permissionService, orgDAL },
      {
        identityId,
        orgId: identityMembershipOrg.scopeOrgId,
        projectId: identityMembershipOrg.identity.projectId,
        action: OrgPermissionIdentityActions.GetToken,
        baseMessage: "Failed to get identity client secret with more privileged role",
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId
      }
    );

    const identityUniversalAuth = await identityUaDAL.findOne({
      identityId
    });

    const clientSecrets = await identityUaClientSecretDAL.find({
      identityUAId: identityUniversalAuth.id,
      isClientSecretRevoked: false
    });
    return { clientSecrets, orgId: identityMembershipOrg.scopeOrgId };
  };

  const getUniversalAuthClientSecretById = async ({
    identityId,
    actorId,
    actor,
    actorOrgId,
    actorAuthMethod,
    clientSecretId
  }: TGetUniversalAuthClientSecretByIdDTO) => {
    const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
      scopeData: {
        scope: AccessScope.Organization,
        orgId: actorOrgId
      },
      identityId
    });
    if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });

    if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.UNIVERSAL_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have universal auth"
      });
    }
    if (identityMembershipOrg.identity.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

    const identityUa = await identityUaDAL.findOne({ identityId });
    if (!identityUa) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });

    const clientSecret = await identityUaClientSecretDAL.findOne({ id: clientSecretId, identityUAId: identityUa.id });
    if (!clientSecret) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });

    await assertIdentityAuthAccessAllowed(
      { permissionService, orgDAL },
      {
        identityId,
        orgId: identityMembershipOrg.scopeOrgId,
        projectId: identityMembershipOrg.identity.projectId,
        action: OrgPermissionIdentityActions.GetToken,
        baseMessage: "Failed to read identity client secret of identity with more privileged role",
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId
      }
    );

    return { ...clientSecret, identityId, orgId: identityMembershipOrg.scopeOrgId };
  };

  const revokeUniversalAuthClientSecret = async ({
    identityId,
    actorId,
    actor,
    actorOrgId,
    actorAuthMethod,
    clientSecretId,
    isActorSuperAdmin
  }: TRevokeUaClientSecretDTO) => {
    const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
      scopeData: {
        scope: AccessScope.Organization,
        orgId: actorOrgId
      },
      identityId
    });
    if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });

    if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.UNIVERSAL_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have universal auth"
      });
    }
    if (identityMembershipOrg.identity.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

    const identityUa = await identityUaDAL.findOne({ identityId });
    if (!identityUa) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });

    const clientSecret = await identityUaClientSecretDAL.findOne({ id: clientSecretId, identityUAId: identityUa.id });
    if (!clientSecret) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });

    await assertIdentityAuthAccessAllowed(
      { permissionService, orgDAL },
      {
        identityId,
        orgId: identityMembershipOrg.scopeOrgId,
        projectId: identityMembershipOrg.identity.projectId,
        action: OrgPermissionIdentityActions.DeleteToken,
        baseMessage: "Failed to revoke identity client secret with more privileged role",
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId
      }
    );

    await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);

    // Insert the revocation marker BEFORE flipping isClientSecretRevoked. If
    // the flip fails, tokens are already dead and a retry safely re-flips the
    // bit; flipping first would leave the secret flagged but tokens authentic.
    await identityAccessTokenService.revokeAllTokensForClientSecret({
      identityId,
      clientSecretId
    });

    const updatedClientSecret = await identityUaDAL.transaction(async (tx) => {
      const doc = await identityUaClientSecretDAL.updateById(clientSecretId, { isClientSecretRevoked: true }, tx);
      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
          change: IdentityAuthMethodChange.CredentialRevoked,
          actor,
          actorId,
          credential: { id: doc.id, name: doc.description || doc.clientSecretPrefix }
        },
        tx
      );
      return doc;
    });

    return { ...updatedClientSecret, identityId, orgId: identityMembershipOrg.scopeOrgId };
  };

  const clearUniversalAuthLockouts = async ({
    identityId,
    actorId,
    actor,
    actorOrgId,
    actorAuthMethod,
    isActorSuperAdmin
  }: TClearUaLockoutsDTO) => {
    const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
      scopeData: {
        scope: AccessScope.Organization,
        orgId: actorOrgId
      },
      identityId
    });
    if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });

    if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.UNIVERSAL_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have universal auth"
      });
    }
    if (identityMembershipOrg.identity.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

    if (identityMembershipOrg.identity.projectId) {
      const { permission } = await permissionService.getProjectPermission({
        actionProjectType: ActionProjectType.Any,
        actor,
        actorId,
        projectId: identityMembershipOrg.identity.projectId,
        actorAuthMethod,
        actorOrgId
      });

      ForbiddenError.from(permission).throwUnlessCan(
        ProjectPermissionIdentityActions.Edit,
        subject(ProjectPermissionSub.Identity, { identityId })
      );
    } else {
      const { permission } = await permissionService.getOrgPermission({
        scope: OrganizationActionScope.Any,
        actor,
        actorId,
        orgId: identityMembershipOrg.scopeOrgId,
        actorAuthMethod,
        actorOrgId
      });
      ForbiddenError.from(permission).throwUnlessCan(OrgPermissionIdentityActions.Edit, OrgPermissionSubjects.Identity);
    }

    await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);

    const deleted = await clearIdentityLockoutsForAuthMethod(identityId, IdentityAuthMethod.UNIVERSAL_AUTH, keyStore);

    return { deleted, identityId, orgId: identityMembershipOrg.scopeOrgId };
  };

  return {
    login,
    attachUniversalAuth,
    updateUniversalAuth,
    getIdentityUniversalAuth,
    revokeIdentityUniversalAuth,
    createUniversalAuthClientSecret,
    getUniversalAuthClientSecrets,
    revokeUniversalAuthClientSecret,
    getUniversalAuthClientSecretById,
    clearUniversalAuthLockouts
  };
};