Skip to content

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

31.4 KB
Raw Blame
import { ForbiddenError, subject } from "@casl/ability";
import { requestContext } from "@fastify/request-context";
import https from "https";
import jwt from "jsonwebtoken";
import { JwksClient } from "jwks-rsa";

import {
  AccessScope,
  ActionProjectType,
  IdentityAuthMethod,
  OrganizationActionScope,
  TIdentityJwtAuthsUpdate
} 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 { TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";
import { logger, sanitizeUrlForLog } 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 { getValueByDot } from "@app/lib/template/dot-access";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
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 { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";
import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";
import { assertIdentityAuthAccessAllowed } from "../identity/identity-auth-permission-fns";
import { splitCommaSeparatedPolicyValues } from "../identity/identity-auth-policy-values";
import { TIdentityDALFactory } from "../identity/identity-dal";
import { TKmsServiceFactory } from "../kms/kms-service";
import { KmsDataKey } from "../kms/kms-types";
import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";
import { recordIdentityLastLoginDebounced } from "../membership-identity/membership-identity-fns";
import { TOrgDALFactory } from "../org/org-dal";
import { validateIdentityUpdateForSuperAdminPrivileges } from "../super-admin/super-admin-fns";
import { TIdentityJwtAuthDALFactory } from "./identity-jwt-auth-dal";
import { doesFieldValueMatchJwtPolicy } from "./identity-jwt-auth-fns";
import {
  JwtConfigurationType,
  TAttachJwtAuthDTO,
  TGetJwtAuthDTO,
  TLoginJwtAuthDTO,
  TRevokeJwtAuthDTO,
  TUpdateJwtAuthDTO
} from "./identity-jwt-auth-types";

type TIdentityJwtAuthServiceFactoryDep = {
  identityDAL: Pick<TIdentityDALFactory, "findById">;
  identityJwtAuthDAL: TIdentityJwtAuthDALFactory;
  membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne" | "update" | "getIdentityById">;
  keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;
  identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;
  permissionService: Pick<
    TPermissionServiceFactory,
    "getOrgPermission" | "getProjectPermission" | "getActorGrantAbilities"
  >;
  licenseService: Pick<TLicenseServiceFactory, "getPlan">;
  kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
  orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;
  identityAccessTokenService: Pick<
    TIdentityAccessTokenServiceFactory,
    "issueIdentityAccessToken" | "revokeTokensForIdentityAuthMethod" | "invalidateTrustedIpsCache"
  >;
  eventEmitter: TEventEmitter;
};

export type TIdentityJwtAuthServiceFactory = ReturnType<typeof identityJwtAuthServiceFactory>;

export const identityJwtAuthServiceFactory = ({
  identityDAL,
  identityJwtAuthDAL,
  membershipIdentityDAL,
  keyStore,
  permissionService,
  licenseService,
  identityAccessTokenDAL,
  kmsService,
  orgDAL,
  identityAccessTokenService,
  eventEmitter
}: TIdentityJwtAuthServiceFactoryDep) => {
  const login = async ({ identityId, jwt: jwtValue, organizationSlug }: TLoginJwtAuthDTO) => {
    const authMetricStartTime = performance.now();
    const appCfg = getConfig();
    const identityJwtAuth = await identityJwtAuthDAL.findOne({ identityId });
    if (!identityJwtAuth) {
      throw new NotFoundError({ message: "JWT auth method not found for identity, did you configure JWT auth?" });
    }

    const identity = await requestMemoize(requestMemoKeys.identityFindById(identityJwtAuth.identityId), () =>
      identityDAL.findById(identityJwtAuth.identityId)
    );
    if (!identity)
      throw new UnauthorizedError({
        message: "Identity not found"
      });

    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 organizationSlug is specified
    let subOrganizationId = isSubOrgIdentity ? org.id : null;

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

      const decodedToken = crypto.jwt().decode(jwtValue, { complete: true });
      if (!decodedToken) {
        throw new UnauthorizedError({
          message: "Invalid JWT",
          detail: {
            reasonCode: "invalid_jwt",
            identityId: identity.id,
            orgId: identity.orgId,
            identityName: identity.name
          }
        });
      }

      let tokenData: Record<string, string | boolean | number> = {};

      if (identityJwtAuth.configurationType === JwtConfigurationType.JWKS) {
        await blockLocalAndPrivateIpAddresses(identityJwtAuth.jwksUrl);

        let client: JwksClient;
        if (identityJwtAuth.jwksUrl.includes("https:")) {
          const decryptedJwksCaCert = orgDataKeyDecryptor({
            cipherTextBlob: identityJwtAuth.encryptedJwksCaCert
          }).toString();

          const requestAgent = decryptedJwksCaCert
            ? new https.Agent({ ca: decryptedJwksCaCert, rejectUnauthorized: true })
            : undefined;
          client = new JwksClient({
            jwksUri: identityJwtAuth.jwksUrl,
            requestAgent
          });
        } else {
          client = new JwksClient({
            jwksUri: identityJwtAuth.jwksUrl
          });
        }

        const { kid } = decodedToken.header as { kid: string };
        let jwtSigningKey;
        try {
          jwtSigningKey = await client.getSigningKey(kid);
        } catch (error) {
          if (error instanceof Error && error.name === "SigningKeyNotFoundError") {
            throw new UnauthorizedError({
              message: `Access denied: Unable to verify JWT signature. The signing key '${kid}' was not found in the configured JWKS.`,
              detail: {
                reasonCode: "signing_key_not_found",
                identityId: identity.id,
                orgId: identity.orgId,
                identityName: identity.name
              }
            });
          }
          // The fetch error can carry network details or the endpoint's response body, and this
          // route is unauthenticated, so the caller gets a fixed message and the detail is logged.
          // The JWKS URL can carry credentials in its path or query, so it is logged sanitized and
          // the error as name, message and code rather than an object that may hold the request.
          logger.error(
            {
              errorName: error instanceof Error ? error.name : undefined,
              errorMessage: error instanceof Error ? error.message : String(error),
              errorCode: (error as NodeJS.ErrnoException)?.code,
              identityId: identity.id,
              jwksUrl: sanitizeUrlForLog(identityJwtAuth.jwksUrl),
              kid
            },
            `JWT auth signing key retrieval failed [identityId=${identity.id}] [kid=${kid}]`
          );
          throw new UnauthorizedError({
            message: "Access denied: Failed to retrieve the signing key from the configured JWKS endpoint.",
            detail: {
              reasonCode: "signing_key_retrieval_failed",
              identityId: identity.id,
              orgId: identity.orgId,
              identityName: identity.name
            }
          });
        }

        try {
          tokenData = crypto.jwt().verify(jwtValue, jwtSigningKey.getPublicKey()) as Record<string, string>;
        } catch (error) {
          if (error instanceof jwt.JsonWebTokenError) {
            throw new UnauthorizedError({
              message: `Access denied: ${error.message}`,
              detail: {
                reasonCode: "jwt_verification_failed",
                identityId: identity.id,
                orgId: identity.orgId,
                identityName: identity.name
              }
            });
          }

          throw error;
        }
      } else {
        const decryptedPublicKeys = orgDataKeyDecryptor({ cipherTextBlob: identityJwtAuth.encryptedPublicKeys })
          .toString()
          .split(",");

        const errors: string[] = [];
        let isMatchAnyKey = false;
        for (const publicKey of decryptedPublicKeys) {
          try {
            tokenData = crypto.jwt().verify(jwtValue, publicKey) as Record<string, string>;
            isMatchAnyKey = true;
          } catch (error) {
            if (error instanceof jwt.JsonWebTokenError) {
              errors.push(error.message);
            }
          }
        }

        if (!isMatchAnyKey) {
          throw new UnauthorizedError({
            message: `Access denied: JWT verification failed with all keys. Errors - ${errors.join("; ")}`,
            detail: {
              reasonCode: "jwt_verification_failed",
              identityId: identity.id,
              orgId: identity.orgId,
              identityName: identity.name
            }
          });
        }
      }

      if (identityJwtAuth.boundIssuer) {
        if (tokenData.iss !== identityJwtAuth.boundIssuer) {
          throw new ForbiddenRequestError({
            message: "Access denied: issuer mismatch"
          });
        }
      }

      if (identityJwtAuth.boundSubject) {
        if (!tokenData.sub) {
          throw new UnauthorizedError({
            message: "Access denied: token has no subject field",
            detail: {
              reasonCode: "missing_subject",
              identityId: identity.id,
              orgId: identity.orgId,
              identityName: identity.name
            }
          });
        }

        if (!doesFieldValueMatchJwtPolicy(tokenData.sub, identityJwtAuth.boundSubject)) {
          throw new ForbiddenRequestError({
            message: "Access denied: subject not allowed"
          });
        }
      }

      if (identityJwtAuth.boundAudiences) {
        if (!tokenData.aud) {
          throw new UnauthorizedError({
            message: "Access denied: token has no audience field",
            detail: {
              reasonCode: "missing_audience",
              identityId: identity.id,
              orgId: identity.orgId,
              identityName: identity.name
            }
          });
        }

        if (
          !splitCommaSeparatedPolicyValues(identityJwtAuth.boundAudiences).some((policyValue) =>
            doesFieldValueMatchJwtPolicy(tokenData.aud, policyValue)
          )
        ) {
          throw new UnauthorizedError({
            message: "Access denied: token audience not allowed",
            detail: {
              reasonCode: "audience_not_allowed",
              identityId: identity.id,
              orgId: identity.orgId,
              identityName: identity.name
            }
          });
        }
      }

      if (identityJwtAuth.boundClaims) {
        Object.keys(identityJwtAuth.boundClaims).forEach((claimKey) => {
          const claimValue = (identityJwtAuth.boundClaims as Record<string, string>)[claimKey];
          const value = getValueByDot(tokenData, claimKey);

          if (!value) {
            throw new UnauthorizedError({
              message: `Access denied: token has no ${claimKey} field`,
              detail: {
                reasonCode: "missing_claim",
                identityId: identity.id,
                orgId: identity.orgId,
                identityName: identity.name
              }
            });
          }

          // handle both single and multi-valued claims
          if (
            !splitCommaSeparatedPolicyValues(claimValue).some((claimEntry) =>
              doesFieldValueMatchJwtPolicy(value, claimEntry)
            )
          ) {
            throw new UnauthorizedError({
              message: `Access denied: claim mismatch for field ${claimKey}`,
              detail: {
                reasonCode: "claim_mismatch",
                identityId: identity.id,
                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 slug ${organizationSlug} not found` });
          }

          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: identity.id,
                orgId: identity.orgId,
                identityName: identity.name
              }
            });
          }

          subOrganizationId = subOrg.id;
        }
      }

      await recordIdentityLastLoginDebounced({
        keyStore,
        membershipIdentityDAL,
        identity,
        lastLoginAuthMethod: IdentityAuthMethod.JWT_AUTH
      });

      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: identityJwtAuth.identityId,
        identityName: identity.name,
        authMethod: IdentityAuthMethod.JWT_AUTH,
        orgId: tokenScopeOrg.id,
        rootOrgId: tokenRootOrgId,
        parentOrgId: tokenParentOrgId,
        subOrganizationId,
        accessTokenTTL: Number(identityJwtAuth.accessTokenTTL),
        accessTokenMaxTTL: Number(identityJwtAuth.accessTokenMaxTTL),
        accessTokenNumUsesLimit: Number(identityJwtAuth.accessTokenNumUsesLimit),
        accessTokenPeriod: Number(identityJwtAuth.accessTokenPeriod) || 0,
        accessTokenTrustedIps: identityJwtAuth.accessTokenTrustedIps as TIp[]
      });

      if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
        authAttemptCounter.add(1, {
          "infisical.identity.id": identityJwtAuth.identityId,
          "infisical.identity.name": identity.name,
          "infisical.organization.id": org.id,
          "infisical.organization.name": org.name,
          "infisical.identity.auth_method": AuthAttemptAuthMethod.JWT_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.JWT_AUTH,
        result: AuthAttemptAuthResult.SUCCESS,
        orgId: org.id
      });

      return { accessToken, identityJwtAuth, identityAccessToken, identity };
    } catch (error) {
      if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
        authAttemptCounter.add(1, {
          "infisical.identity.id": identityJwtAuth.identityId,
          "infisical.identity.name": identity.name,
          "infisical.organization.id": org.id,
          "infisical.organization.name": org.name,
          "infisical.identity.auth_method": AuthAttemptAuthMethod.JWT_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.JWT_AUTH,
        result: AuthAttemptAuthResult.FAILURE,
        orgId: org.id,
        error
      });
      throw error;
    }
  };

  const attachJwtAuth = async ({
    identityId,
    configurationType,
    jwksUrl,
    jwksCaCert,
    publicKeys,
    boundIssuer,
    boundAudiences,
    boundClaims,
    boundSubject,
    accessTokenTTL,
    accessTokenMaxTTL,
    accessTokenNumUsesLimit,
    accessTokenTrustedIps,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId,
    isActorSuperAdmin
  }: TAttachJwtAuthDTO) => {
    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.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

    if (identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.JWT_AUTH)) {
      throw new BadRequestError({
        message: "Failed to add JWT Auth to already configured 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 jwt auth to identity with more privileged role",
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId
      }
    );

    await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);

    const plan = await licenseService.getPlan(identityMembershipOrg.scopeOrgId);
    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 access 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);
    });

    if (configurationType === JwtConfigurationType.JWKS && jwksUrl) {
      await blockLocalAndPrivateIpAddresses(jwksUrl);
    }

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

    const { cipherTextBlob: encryptedJwksCaCert } = orgDataKeyEncryptor({
      plainText: Buffer.from(jwksCaCert)
    });

    const { cipherTextBlob: encryptedPublicKeys } = orgDataKeyEncryptor({
      plainText: Buffer.from(publicKeys.join(","))
    });

    const identityJwtAuth = await identityJwtAuthDAL.transaction(async (tx) => {
      const doc = await identityJwtAuthDAL.create(
        {
          identityId: identityMembershipOrg.identity.id,
          configurationType,
          jwksUrl,
          encryptedJwksCaCert,
          encryptedPublicKeys,
          boundIssuer,
          boundAudiences,
          boundClaims,
          boundSubject,
          accessTokenMaxTTL,
          accessTokenTTL,
          accessTokenNumUsesLimit,
          accessTokenTrustedIps: JSON.stringify(reformattedAccessTokenTrustedIps)
        },
        tx
      );

      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.JWT_AUTH,
          change: IdentityAuthMethodChange.Added,
          actor,
          actorId
        },
        tx
      );
      return doc;
    });
    await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.JWT_AUTH);
    return { ...identityJwtAuth, orgId: identityMembershipOrg.scopeOrgId, jwksCaCert, publicKeys };
  };

  const updateJwtAuth = async ({
    identityId,
    configurationType,
    jwksUrl,
    jwksCaCert,
    publicKeys,
    boundIssuer,
    boundAudiences,
    boundClaims,
    boundSubject,
    accessTokenTTL,
    accessTokenMaxTTL,
    accessTokenNumUsesLimit,
    accessTokenTrustedIps,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId,
    isActorSuperAdmin
  }: TUpdateJwtAuthDTO) => {
    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.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

    if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.JWT_AUTH)) {
      throw new BadRequestError({
        message: "Failed to update JWT Auth"
      });
    }

    const identityJwtAuth = await identityJwtAuthDAL.findOne({ identityId });

    if (
      (accessTokenMaxTTL || identityJwtAuth.accessTokenMaxTTL) > 0 &&
      (accessTokenTTL || identityJwtAuth.accessTokenMaxTTL) > (accessTokenMaxTTL || identityJwtAuth.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 jwt auth of identity with more privileged role",
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId
      }
    );

    await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
    const plan = await licenseService.getPlan(identityMembershipOrg.scopeOrgId);
    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 access 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);
    });

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

    const updateQuery: TIdentityJwtAuthsUpdate = {
      boundIssuer,
      configurationType,
      jwksUrl,
      boundAudiences,
      boundClaims,
      boundSubject,
      accessTokenMaxTTL,
      accessTokenTTL,
      accessTokenNumUsesLimit,
      accessTokenTrustedIps: reformattedAccessTokenTrustedIps
        ? JSON.stringify(reformattedAccessTokenTrustedIps)
        : undefined
    };

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

    if (jwksCaCert !== undefined) {
      const { cipherTextBlob: encryptedJwksCaCert } = orgDataKeyEncryptor({
        plainText: Buffer.from(jwksCaCert)
      });

      updateQuery.encryptedJwksCaCert = encryptedJwksCaCert;
    }

    if (publicKeys) {
      const { cipherTextBlob: encryptedPublicKeys } = orgDataKeyEncryptor({
        plainText: Buffer.from(publicKeys.join(","))
      });

      updateQuery.encryptedPublicKeys = encryptedPublicKeys;
    }

    const updatedJwtAuth = await identityJwtAuthDAL.transaction(async (tx) => {
      const doc = await identityJwtAuthDAL.updateById(identityJwtAuth.id, updateQuery, tx);
      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.JWT_AUTH,
          change: IdentityAuthMethodChange.Updated,
          actor,
          actorId
        },
        tx
      );
      return doc;
    });
    const decryptedJwksCaCert = orgDataKeyDecryptor({ cipherTextBlob: updatedJwtAuth.encryptedJwksCaCert }).toString();
    const decryptedPublicKeys = orgDataKeyDecryptor({ cipherTextBlob: updatedJwtAuth.encryptedPublicKeys })
      .toString()
      .split(",");

    await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.JWT_AUTH);
    return {
      ...updatedJwtAuth,
      orgId: identityMembershipOrg.scopeOrgId,
      jwksCaCert: decryptedJwksCaCert,
      publicKeys: decryptedPublicKeys
    };
  };

  const getJwtAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetJwtAuthDTO) => {
    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.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

    if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.JWT_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have JWT Auth attached"
      });
    }

    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);
    }
    const identityJwtAuth = await identityJwtAuthDAL.findOne({ identityId });

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

    const decryptedJwksCaCert = orgDataKeyDecryptor({ cipherTextBlob: identityJwtAuth.encryptedJwksCaCert }).toString();
    const decryptedPublicKeys = orgDataKeyDecryptor({ cipherTextBlob: identityJwtAuth.encryptedPublicKeys })
      .toString()
      .split(",");

    return {
      ...identityJwtAuth,
      orgId: identityMembershipOrg.scopeOrgId,
      jwksCaCert: decryptedJwksCaCert,
      publicKeys: decryptedPublicKeys
    };
  };

  const revokeJwtAuth = async ({
    identityId,
    actorId,
    actor,
    actorAuthMethod,
    actorOrgId,
    isActorSuperAdmin
  }: TRevokeJwtAuthDTO) => {
    const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
      scopeData: {
        scope: AccessScope.Organization,
        orgId: actorOrgId
      },
      identityId
    });
    if (!identityMembershipOrg) {
      throw new NotFoundError({ message: "Failed to find identity" });
    }
    if (identityMembershipOrg.identity.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

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

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

    await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
    const revokedIdentityJwtAuth = await identityJwtAuthDAL.transaction(async (tx) => {
      const deletedJwtAuth = await identityJwtAuthDAL.delete({ identityId }, tx);
      await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.JWT_AUTH }, tx);

      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.JWT_AUTH,
          change: IdentityAuthMethodChange.Removed,
          actor,
          actorId
        },
        tx
      );
      return { ...deletedJwtAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };
    });

    // Detaching the auth method must invalidate any tokens already issued
    // through it; without this, leaked tokens authenticate up to MAX_AGE
    // even after the admin pulled the auth method.
    await identityAccessTokenService.revokeTokensForIdentityAuthMethod({
      identityId,
      authMethod: IdentityAuthMethod.JWT_AUTH
    });
    await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.JWT_AUTH);

    return revokedIdentityJwtAuth;
  };

  return {
    login,
    attachJwtAuth,
    updateJwtAuth,
    getJwtAuth,
    revokeJwtAuth
  };
};