Skip to content

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

35.3 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 { TKeyStoreFactory } from "@app/keystore/keystore";
import { extractX509CertFromChain } from "@app/lib/certificates/extract-certificate";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, ForbiddenRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
import { 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 { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";
import { computeCertificateThumbprint } from "../identity-access-token/identity-access-token-fns";
import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";
import { CERTIFICATE_THUMBPRINT_CLAIM } from "../identity-access-token/identity-access-token-types";
import { assertIdentityAuthAccessAllowed } from "../identity/identity-auth-permission-fns";
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 { TIdentityTlsCertAuthDALFactory } from "./identity-tls-cert-auth-dal";
import {
  findNameConstraintsProblem,
  isSubjectAltNameAllowed,
  parseAllowedSubjectAltNames,
  parseSubjectDetails,
  permitsClientAuth,
  readSubjectAltNames,
  serializeAllowedSubjectAltNames,
  TNameConstraintsProblem,
  TVerifyClientCertificateChainResult,
  verifyClientCertificateChain,
  verifyDirectlyIssuedClientCertificate
} from "./identity-tls-cert-auth-fns";
import { TIdentityTlsCertAuthServiceFactory } from "./identity-tls-cert-auth-types";

const CHAIN_FAILURE_MESSAGES: Record<
  Extract<TVerifyClientCertificateChainResult, { ok: false }>["reasonCode"],
  string
> = {
  ca_verification_failed: "Access denied: Certificate chain could not be validated against the provided CA.",
  certificate_expired: "Access denied: Certificate has expired.",
  certificate_not_yet_valid: "Access denied: Certificate not yet valid.",
  issuer_certificate_expired: "Access denied: A CA certificate that issued the client certificate has expired.",
  issuer_certificate_not_yet_valid:
    "Access denied: A CA certificate that issued the client certificate is not yet valid.",
  issuer_client_auth_usage_not_allowed:
    "Access denied: A CA in the certificate chain is not permitted to issue client authentication certificates.",
  name_constraint_violation:
    "Access denied: The client certificate's name is outside the namespace its issuing CA is permitted to certify.",
  path_length_exceeded: "Access denied: The certificate chain has more intermediate CAs than a CA in it permits.",
  unsupported_name_constraint:
    "Access denied: A CA in the certificate chain restricts a URI name that is not a fully qualified domain name, so no client certificate can satisfy it."
};

const normalizeCaCertificate = (caCertificate: string) => caCertificate.replace(/\s+/g, "");

const nameConstraintsProblemMessage = (problem: TNameConstraintsProblem) => {
  if (problem.kind === "unparseable_certificate")
    return "CA certificate could not be decoded. Provide a PEM-encoded X.509 certificate that conforms to RFC 5280.";

  if (problem.kind === "unreadable_extension")
    return "CA certificate's name constraints extension is malformed, so the namespace it restricts cannot be honored and no certificate it issues could be used to log in. Provide a CA certificate whose name constraints are well-formed.";

  return `CA certificate restricts the URI name "${problem.constraint}", which is not a fully qualified domain name, so no certificate it issues could be used to log in. A URI name constraint restricts the host only, such as "example.org". To restrict individual workload identities, use allowed subject alternative names instead.`;
};

// The chain arrives percent-encoded, since that is what a TLS-terminating proxy emits (nginx's
// `$ssl_client_escaped_cert` and equivalents). A value that will not decode means a malformed
// request, not an untrusted certificate, hence 400 rather than 401.
const decodeClientCertificateHeader = (clientCertificate: string) => {
  try {
    return decodeURIComponent(clientCertificate);
  } catch {
    throw new BadRequestError({
      message:
        "Malformed client certificate header: the value is not valid URL-encoded data. The TLS-terminating proxy must URL-encode the certificate chain it forwards."
    });
  }
};

/**
 * Denies rather than 500s on a certificate that carries the PEM markers but will not parse, since
 * reading it is what would establish who the client is. Denying also keeps the attempt auditable:
 * only `UnauthorizedError` is recorded, so a client probing with junk stays visible.
 *
 * The OpenSSL reason is logged rather than returned; it describes the encoding, not anything the
 * caller can act on.
 */
const parsePresentedCertificate = (
  pem: string,
  role: "leaf" | "chain",
  detail: { identityId: string; orgId: string; identityName: string }
) => {
  try {
    return new crypto.nativeCrypto.X509Certificate(pem);
  } catch (err) {
    logger.warn(
      err,
      `TLS certificate auth: a presented certificate could not be decoded [role=${role}] [identityId=${detail.identityId}]`
    );
    throw new UnauthorizedError({
      message:
        role === "leaf"
          ? "Access denied: the client certificate could not be decoded."
          : "Access denied: a CA certificate in the presented chain could not be decoded.",
      detail: { reasonCode: "certificate_decode_failed", ...detail }
    });
  }
};

/**
 * Reject a CA certificate when it is configured, rather than at every login it would deny. Only
 * conditions that can never authenticate anyone belong here: a not-yet-valid certificate is allowed
 * through, since an operator may be pre-provisioning the next CA in a rotation.
 */
const validateCaCertificateUsable = (caCertificate: string) => {
  let caCertificateX509: InstanceType<typeof crypto.nativeCrypto.X509Certificate>;
  try {
    caCertificateX509 = new crypto.nativeCrypto.X509Certificate(caCertificate);
  } catch {
    throw new BadRequestError({
      message: "CA certificate could not be read. Provide a PEM-encoded X.509 certificate."
    });
  }

  const validTo = new Date(caCertificateX509.validTo);
  if (validTo < new Date()) {
    throw new BadRequestError({
      message: `CA certificate expired on ${validTo.toISOString()}. Provide a CA certificate that is still valid.`
    });
  }

  if (!permitsClientAuth(caCertificateX509)) {
    throw new BadRequestError({
      message:
        "CA certificate's extended key usage does not include client authentication, so no certificate it issues could be used to log in. Provide a CA certificate that permits client authentication."
    });
  }

  const nameConstraintsProblem = findNameConstraintsProblem(caCertificateX509);
  if (nameConstraintsProblem)
    throw new BadRequestError({ message: nameConstraintsProblemMessage(nameConstraintsProblem) });
};

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

export const identityTlsCertAuthServiceFactory = ({
  identityDAL,
  identityAccessTokenDAL,
  identityTlsCertAuthDAL,
  membershipIdentityDAL,
  keyStore,
  licenseService,
  permissionService,
  kmsService,
  orgDAL,
  identityAccessTokenService,
  eventEmitter
}: TIdentityTlsCertAuthServiceFactoryDep): TIdentityTlsCertAuthServiceFactory => {
  const login: TIdentityTlsCertAuthServiceFactory["login"] = async ({
    identityId,
    clientCertificate,
    organizationSlug
  }) => {
    const authMetricStartTime = performance.now();
    const appCfg = getConfig();
    // Read from the primary so a lagging replica can't issue an unbound token after binding was turned on.
    const identityTlsCertAuth = await identityTlsCertAuthDAL.findOne(
      { identityId },
      identityTlsCertAuthDAL.primaryNode()
    );
    if (!identityTlsCertAuth) {
      throw new NotFoundError({
        message: "TLS Certificate auth method not found for identity, did you configure TLS Certificate auth?"
      });
    }

    const identity = await requestMemoize(requestMemoKeys.identityFindById(identityTlsCertAuth.identityId), () =>
      identityDAL.findById(identityTlsCertAuth.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 } = await kmsService.createCipherPairWithDataKey({
        type: KmsDataKey.Organization,
        orgId: identity.orgId
      });

      const caCertificate = decryptor({
        cipherTextBlob: identityTlsCertAuth.encryptedCaCertificate
      }).toString();

      const presentedCertificates = extractX509CertFromChain(decodeClientCertificateHeader(clientCertificate));
      const leafCertificate = presentedCertificates?.[0];
      if (!leafCertificate) {
        throw new BadRequestError({ message: "Missing client certificate" });
      }

      const failureDetail = { identityId: identity.id, orgId: identity.orgId, identityName: identity.name };

      const clientCertificateX509 = parsePresentedCertificate(leafCertificate, "leaf", failureDetail);
      const caCertificateX509 = new crypto.nativeCrypto.X509Certificate(caCertificate);

      if (identityTlsCertAuth.verifyClientCertificateChain) {
        // Trust-anchor mode: the configured CA is a trust anchor. Build a path from the presented
        // leaf through the presented intermediates up to the anchor (RFC 5280 path validation),
        // rather than requiring the anchor to be the leaf's direct issuer. This supports issuers
        // that rotate beneath a stable root (e.g. SPIRE X.509-SVID intermediates) by pinning the
        // long-lived root while the client presents the current intermediate alongside its leaf.
        const presentedChain = presentedCertificates
          .slice(1)
          .map((pem) => parsePresentedCertificate(pem, "chain", failureDetail));

        const chainResult = await verifyClientCertificateChain({
          leaf: clientCertificateX509,
          presentedChain,
          trustAnchor: caCertificateX509
        });

        if (!chainResult.ok) {
          const message = CHAIN_FAILURE_MESSAGES[chainResult.reasonCode];
          throw new UnauthorizedError({
            message,
            detail: {
              reasonCode: chainResult.reasonCode,
              identityId: identity.id,
              orgId: identity.orgId,
              identityName: identity.name
            }
          });
        }
      } else {
        // Single-hop mode (default): the configured CA must be the direct issuer of the leaf.
        const directResult = await verifyDirectlyIssuedClientCertificate({
          leaf: clientCertificateX509,
          ca: caCertificateX509
        });

        if (!directResult.ok) {
          throw new UnauthorizedError({
            message:
              directResult.reasonCode === "ca_verification_failed"
                ? "Access denied: Certificate not issued by the provided CA."
                : CHAIN_FAILURE_MESSAGES[directResult.reasonCode],
            detail: {
              reasonCode: directResult.reasonCode,
              identityId: identity.id,
              orgId: identity.orgId,
              identityName: identity.name
            }
          });
        }
      }

      // Require an end-entity certificate issued by the configured CA, not the CA certificate
      // itself. `.ca` covers certs marked CA:TRUE; the raw comparison also covers a self-signed CA
      // that omits basic constraints.
      const isClientCertACa = clientCertificateX509.ca || clientCertificateX509.raw.equals(caCertificateX509.raw);
      if (isClientCertACa) {
        throw new UnauthorizedError({
          message: "Access denied: a CA certificate cannot be used as a client certificate.",
          detail: {
            reasonCode: "ca_certificate_not_allowed",
            identityId: identity.id,
            orgId: identity.orgId,
            identityName: identity.name
          }
        });
      }

      if (!permitsClientAuth(clientCertificateX509)) {
        throw new UnauthorizedError({
          message: "Access denied: the client certificate is not valid for client authentication.",
          detail: {
            reasonCode: "client_auth_usage_not_allowed",
            identityId: identity.id,
            orgId: identity.orgId,
            identityName: identity.name
          }
        });
      }

      const subjectDetails = parseSubjectDetails(clientCertificateX509.subject);
      if (identityTlsCertAuth.allowedCommonNames) {
        const isValidCommonName = identityTlsCertAuth.allowedCommonNames.split(",").includes(subjectDetails.CN);
        if (!isValidCommonName) {
          throw new UnauthorizedError({
            message: "Access denied: TLS Certificate Auth common name not allowed.",
            detail: {
              reasonCode: "common_name_not_allowed",
              identityId: identity.id,
              orgId: identity.orgId,
              identityName: identity.name
            }
          });
        }
      }

      if (identityTlsCertAuth.allowedSubjectAltNames) {
        const isValidSubjectAltName = isSubjectAltNameAllowed(
          parseAllowedSubjectAltNames(identityTlsCertAuth.allowedSubjectAltNames),
          readSubjectAltNames(clientCertificateX509)
        );
        if (!isValidSubjectAltName) {
          throw new UnauthorizedError({
            message: "Access denied: TLS Certificate Auth subject alternative name not allowed.",
            detail: {
              reasonCode: "subject_alt_name_not_allowed",
              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;
        }
      }

      // Generate the token
      await recordIdentityLastLoginDebounced({
        keyStore,
        membershipIdentityDAL,
        identity,
        lastLoginAuthMethod: IdentityAuthMethod.TLS_CERT_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: identityTlsCertAuth.identityId,
        identityName: identity.name,
        authMethod: IdentityAuthMethod.TLS_CERT_AUTH,
        orgId: tokenScopeOrg.id,
        rootOrgId: tokenRootOrgId,
        parentOrgId: tokenParentOrgId,
        subOrganizationId,
        accessTokenTTL: Number(identityTlsCertAuth.accessTokenTTL),
        accessTokenMaxTTL: Number(identityTlsCertAuth.accessTokenMaxTTL),
        accessTokenNumUsesLimit: Number(identityTlsCertAuth.accessTokenNumUsesLimit),
        // TLS Cert auth schema has no accessTokenPeriod column.
        accessTokenPeriod: 0,
        accessTokenTrustedIps: identityTlsCertAuth.accessTokenTrustedIps as TIp[],
        cnf: identityTlsCertAuth.bindAccessTokenToCertificate
          ? { [CERTIFICATE_THUMBPRINT_CLAIM]: computeCertificateThumbprint(clientCertificateX509.raw) }
          : undefined
      });

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

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

  const attachTlsCertAuth: TIdentityTlsCertAuthServiceFactory["attachTlsCertAuth"] = async ({
    identityId,
    accessTokenTTL,
    accessTokenMaxTTL,
    accessTokenNumUsesLimit,
    accessTokenTrustedIps,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId,
    isActorSuperAdmin,
    caCertificate,
    allowedCommonNames,
    allowedSubjectAltNames,
    verifyClientCertificateChain: verifyClientCertificateChainOpt,
    bindAccessTokenToCertificate
  }) => {
    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.TLS_CERT_AUTH)) {
      throw new BadRequestError({
        message: "Failed to add TLS Certificate 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 TLS Certificate 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);
    });

    validateCaCertificateUsable(caCertificate);

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

    const identityTlsCertAuth = await identityTlsCertAuthDAL.transaction(async (tx) => {
      const doc = await identityTlsCertAuthDAL.create(
        {
          identityId: identityMembershipOrg.identity.id,
          accessTokenMaxTTL,
          allowedCommonNames,
          allowedSubjectAltNames: serializeAllowedSubjectAltNames(allowedSubjectAltNames),
          accessTokenTTL,
          encryptedCaCertificate: encryptor({ plainText: Buffer.from(caCertificate) }).cipherTextBlob,
          verifyClientCertificateChain: verifyClientCertificateChainOpt ?? false,
          bindAccessTokenToCertificate: bindAccessTokenToCertificate ?? false,
          accessTokenNumUsesLimit,
          accessTokenTrustedIps: JSON.stringify(reformattedAccessTokenTrustedIps)
        },
        tx
      );
      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.TLS_CERT_AUTH,
          change: IdentityAuthMethodChange.Added,
          actor,
          actorId
        },
        tx
      );
      return doc;
    });
    await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.TLS_CERT_AUTH);
    return { ...identityTlsCertAuth, orgId: identityMembershipOrg.scopeOrgId };
  };

  const updateTlsCertAuth: TIdentityTlsCertAuthServiceFactory["updateTlsCertAuth"] = async ({
    identityId,
    caCertificate,
    allowedCommonNames,
    allowedSubjectAltNames,
    verifyClientCertificateChain: verifyClientCertificateChainOpt,
    bindAccessTokenToCertificate,
    accessTokenTTL,
    accessTokenMaxTTL,
    accessTokenNumUsesLimit,
    accessTokenTrustedIps,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId,
    isActorSuperAdmin
  }) => {
    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.TLS_CERT_AUTH)) {
      throw new NotFoundError({
        message: "The identity does not have TLS Certificate Auth attached"
      });
    }

    const identityTlsCertAuth = await identityTlsCertAuthDAL.findOne({ identityId });

    if (
      (accessTokenMaxTTL || identityTlsCertAuth.accessTokenMaxTTL) > 0 &&
      (accessTokenTTL || identityTlsCertAuth.accessTokenTTL) >
        (accessTokenMaxTTL || identityTlsCertAuth.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 TLS Certificate 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);
    });
    const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
      type: KmsDataKey.Organization,
      orgId: identityMembershipOrg.scopeOrgId
    });

    const storedCaCertificate = decryptor({
      cipherTextBlob: identityTlsCertAuth.encryptedCaCertificate
    }).toString();
    if (caCertificate && normalizeCaCertificate(caCertificate) !== normalizeCaCertificate(storedCaCertificate)) {
      validateCaCertificateUsable(caCertificate);
    }

    const isEnablingBinding =
      Boolean(bindAccessTokenToCertificate) && !identityTlsCertAuth.bindAccessTokenToCertificate;
    const updatedTlsCertAuth = await identityTlsCertAuthDAL.transaction(async (tx) => {
      const doc = await identityTlsCertAuthDAL.updateById(
        identityTlsCertAuth.id,
        {
          allowedCommonNames,
          allowedSubjectAltNames: serializeAllowedSubjectAltNames(allowedSubjectAltNames),
          encryptedCaCertificate: caCertificate
            ? encryptor({ plainText: Buffer.from(caCertificate) }).cipherTextBlob
            : undefined,
          verifyClientCertificateChain: verifyClientCertificateChainOpt,
          bindAccessTokenToCertificate,
          accessTokenMaxTTL,
          accessTokenTTL,
          accessTokenNumUsesLimit,
          accessTokenTrustedIps: reformattedAccessTokenTrustedIps
            ? JSON.stringify(reformattedAccessTokenTrustedIps)
            : undefined
        },
        tx
      );
      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.TLS_CERT_AUTH,
          change: IdentityAuthMethodChange.Updated,
          actor,
          actorId
        },
        tx
      );
      // Tokens issued before binding was enabled carry no certificate claim, so they must not outlive the change.
      if (isEnablingBinding) {
        await identityAccessTokenService.revokeTokensForIdentityAuthMethod({
          identityId,
          authMethod: IdentityAuthMethod.TLS_CERT_AUTH,
          tx
        });
      }
      return doc;
    });

    if (isEnablingBinding) {
      await identityAccessTokenService.bumpIdentityRevocationVersion({ identityId });
    }
    await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.TLS_CERT_AUTH);
    return { ...updatedTlsCertAuth, orgId: identityMembershipOrg.scopeOrgId };
  };

  const getTlsCertAuth: TIdentityTlsCertAuthServiceFactory["getTlsCertAuth"] = async ({
    identityId,
    actorId,
    actor,
    actorAuthMethod,
    actorOrgId
  }) => {
    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.TLS_CERT_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have TLS Certificate Auth attached"
      });
    }

    const identityAuth = await identityTlsCertAuthDAL.findOne({ identityId });

    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 { decryptor } = await kmsService.createCipherPairWithDataKey({
      type: KmsDataKey.Organization,
      orgId: identityMembershipOrg.scopeOrgId
    });
    let caCertificate = "";
    if (identityAuth.encryptedCaCertificate) {
      caCertificate = decryptor({ cipherTextBlob: identityAuth.encryptedCaCertificate }).toString();
    }

    return { ...identityAuth, caCertificate, orgId: identityMembershipOrg.scopeOrgId };
  };

  const revokeTlsCertAuth: TIdentityTlsCertAuthServiceFactory["revokeTlsCertAuth"] = async ({
    identityId,
    actorId,
    actor,
    actorAuthMethod,
    actorOrgId,
    isActorSuperAdmin
  }) => {
    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.TLS_CERT_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have TLS Certificate auth"
      });
    }

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

    await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);

    const revokedIdentityTlsCertAuth = await identityTlsCertAuthDAL.transaction(async (tx) => {
      const deletedTlsCertAuth = await identityTlsCertAuthDAL.delete({ identityId }, tx);
      await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.TLS_CERT_AUTH }, tx);

      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.TLS_CERT_AUTH,
          change: IdentityAuthMethodChange.Removed,
          actor,
          actorId
        },
        tx
      );
      return { ...deletedTlsCertAuth?.[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.TLS_CERT_AUTH
    });
    await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.TLS_CERT_AUTH);

    return revokedIdentityTlsCertAuth;
  };

  return {
    login,
    attachTlsCertAuth,
    updateTlsCertAuth,
    getTlsCertAuth,
    revokeTlsCertAuth
  };
};