Skip to content

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

59.1 KB
Raw Blame
import net from "node:net";

import { ForbiddenError } from "@casl/ability";
import * as x509 from "@peculiar/x509";

import {
  OrganizationActionScope,
  OrgMembershipRole,
  OrgMembershipStatus,
  TGatewaysV2Update,
  TRelays
} from "@app/db/schemas";
import { assertHostNotInfisicalInfrastructure } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";
import { PgSqlLock } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
import { groupBy } from "@app/lib/fn";
import { getGatewayLoadTracker } from "@app/lib/gateway-v2/gateway-load-tracker";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import { OrgServiceActor } from "@app/lib/types";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
import {
  createSerialNumber,
  getNotAfterWithClockSkew,
  getNotBeforeWithClockSkew,
  keyAlgorithmToAlgCfg
} from "@app/services/certificate-authority/certificate-authority-fns";
import { constructPemChainFromCerts } from "@app/services/certificate/certificate-fns";
import { CertExtendedKeyUsage, CertKeyAlgorithm, CertKeyUsage } from "@app/services/certificate/certificate-types";
import { TIdentityKubernetesAuthDALFactory } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
import { NotificationType } from "@app/services/notification/notification-types";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TSmtpService } from "@app/services/smtp/smtp-service";

import { TDynamicSecretDALFactory } from "../dynamic-secret/dynamic-secret-dal";
import { TPamAccountTemplateDALFactory } from "../pam-account-template/pam-account-template-dal";
import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
import { PamAccountType } from "../pam/pam-enums";
import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission";
import { TPermissionServiceFactory } from "../permission/permission-service-types";
import { TPkiDiscoveryConfigDALFactory } from "../pki-discovery/pki-discovery-config-dal";
import { TRelayDALFactory } from "../relay/relay-dal";
import { TRelayServiceFactory } from "../relay/relay-service";
import { TResourceAuthMethodServiceFactory } from "../resource-auth-method/resource-auth-method-service";
import {
  TAwsAuthMethodConfig,
  TGcpAuthMethodConfig,
  TKubernetesAuthMethodConfig
} from "../resource-auth-method/resource-auth-method-types";
import { issueGatewayServerCertificate } from "./gateway-v2-certificate-fns";
import {
  DEFAULT_HEARTBEAT_TTL,
  GATEWAY_ACTOR_OID,
  GATEWAY_ROUTING_INFO_OID,
  GatewayTransport,
  PAM_INFO_OID
} from "./gateway-v2-constants";
import { TGatewayV2DALFactory } from "./gateway-v2-dal";
import { parseDirectAddress, resolveClientTransports, resolveTransports } from "./gateway-v2-transport-fns";
import { TGatewayV2ConnectionDetails } from "./gateway-v2-types";
import { TOrgGatewayConfigV2DALFactory } from "./org-gateway-config-v2-dal";

// Temporary limit until gateway limiting is implemented at the relay level
const MAX_GATEWAYS_PER_ORG = 50;

type TGatewayV2ServiceFactoryDep = {
  orgGatewayConfigV2DAL: Pick<TOrgGatewayConfigV2DALFactory, "findOne" | "create" | "transaction" | "findById">;
  kmsService: TKmsServiceFactory;
  relayService: TRelayServiceFactory;
  gatewayV2DAL: TGatewayV2DALFactory;
  relayDAL: TRelayDALFactory;
  permissionService: TPermissionServiceFactory;
  orgDAL: Pick<TOrgDALFactory, "findOrgMembersByRole">;
  notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
  smtpService: Pick<TSmtpService, "sendMail">;
  appConnectionDAL: Pick<TAppConnectionDALFactory, "findByGatewayId" | "countByGatewayId">;
  dynamicSecretDAL: Pick<TDynamicSecretDALFactory, "findByGatewayId" | "countByGatewayId">;
  identityKubernetesAuthDAL: Pick<TIdentityKubernetesAuthDALFactory, "findByGatewayId" | "countByGatewayId">;
  pkiDiscoveryConfigDAL: Pick<TPkiDiscoveryConfigDALFactory, "findByGatewayId" | "countByGatewayId">;
  pamAccountDAL: Pick<TPamAccountDALFactory, "findByGatewayId" | "countByGatewayIds">;
  pamAccountTemplateDAL: Pick<TPamAccountTemplateDALFactory, "findByGatewayId" | "countByGatewayIds">;
  resourceAuthMethodService: Pick<
    TResourceAuthMethodServiceFactory,
    | "initAtCreate"
    | "loadView"
    | "mintToken"
    | "loginWithToken"
    | "encryptKubernetesSecrets"
    | "preflightKubernetesConfig"
    | "findKubernetesProxyDependents"
  >;
};

export type TGatewayV2ServiceFactory = ReturnType<typeof gatewayV2ServiceFactory>;

export const gatewayV2ServiceFactory = ({
  orgGatewayConfigV2DAL,
  kmsService,
  relayService,
  gatewayV2DAL,
  relayDAL,
  permissionService,
  orgDAL,
  notificationService,
  appConnectionDAL,
  dynamicSecretDAL,
  identityKubernetesAuthDAL,
  pkiDiscoveryConfigDAL,
  pamAccountDAL,
  pamAccountTemplateDAL,
  resourceAuthMethodService
}: TGatewayV2ServiceFactoryDep) => {
  const $validateIdentityAccessToGateway = async (orgId: string, actorId: string, actorAuthMethod: ActorAuthMethod) => {
    const { permission } = await permissionService.getOrgPermission({
      scope: OrganizationActionScope.Any,
      actor: ActorType.IDENTITY,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId: orgId
    });

    ForbiddenError.from(permission).throwUnlessCan(
      OrgPermissionGatewayActions.CreateGateways,
      OrgPermissionSubjects.Gateway
    );
  };

  const $getOrgCAs = async (orgId: string) => {
    const { encryptor: orgKmsEncryptor, decryptor: orgKmsDecryptor } = await kmsService.createCipherPairWithDataKey({
      type: KmsDataKey.Organization,
      orgId
    });

    const orgCAs = await orgGatewayConfigV2DAL.transaction(async (tx) => {
      const orgGatewayConfigV2 = await orgGatewayConfigV2DAL.findOne({ orgId });
      if (orgGatewayConfigV2) return orgGatewayConfigV2;

      await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.OrgGatewayV2Init(orgId)]);
      // Re-read under the lock: a request that waited on it must not create a second one.
      const lockedOrgGatewayConfigV2 = await orgGatewayConfigV2DAL.findOne({ orgId }, tx);
      if (lockedOrgGatewayConfigV2) return lockedOrgGatewayConfigV2;

      // generate root CA
      const rootCaKeyAlgorithm = CertKeyAlgorithm.RSA_2048;
      const alg = keyAlgorithmToAlgCfg(rootCaKeyAlgorithm);
      const rootCaKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);

      const rootCaSerialNumber = createSerialNumber();
      const rootCaSkObj = crypto.nativeCrypto.KeyObject.from(rootCaKeys.privateKey);
      const rootCaIssuedAt = new Date();
      const rootCaExpiration = new Date(new Date().setFullYear(2045));

      const rootCaCert = await x509.X509CertificateGenerator.createSelfSigned({
        name: `O=${orgId},CN=Infisical Gateway Root CA`,
        serialNumber: rootCaSerialNumber,
        notBefore: getNotBeforeWithClockSkew(rootCaIssuedAt),
        notAfter: getNotAfterWithClockSkew(rootCaExpiration),
        signingAlgorithm: alg,
        keys: rootCaKeys,
        extensions: [
          // eslint-disable-next-line no-bitwise
          new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true),
          await x509.SubjectKeyIdentifierExtension.create(rootCaKeys.publicKey)
        ]
      });

      // generate server CA
      const serverCaSerialNumber = createSerialNumber();
      const serverCaIssuedAt = new Date();
      const serverCaExpiration = new Date(new Date().setFullYear(2045));
      const serverCaKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
      const serverCaSkObj = crypto.nativeCrypto.KeyObject.from(serverCaKeys.privateKey);
      const serverCaCert = await x509.X509CertificateGenerator.create({
        serialNumber: serverCaSerialNumber,
        subject: `O=${orgId},CN=Infisical Gateway Server CA`,
        issuer: rootCaCert.subject,
        notBefore: getNotBeforeWithClockSkew(serverCaIssuedAt),
        notAfter: getNotAfterWithClockSkew(serverCaExpiration),
        signingKey: rootCaKeys.privateKey,
        publicKey: serverCaKeys.publicKey,
        signingAlgorithm: alg,
        extensions: [
          new x509.KeyUsagesExtension(
            // eslint-disable-next-line no-bitwise
            x509.KeyUsageFlags.keyCertSign |
              x509.KeyUsageFlags.cRLSign |
              x509.KeyUsageFlags.digitalSignature |
              x509.KeyUsageFlags.keyEncipherment,
            true
          ),
          new x509.BasicConstraintsExtension(true, 0, true),
          await x509.AuthorityKeyIdentifierExtension.create(rootCaCert, false),
          await x509.SubjectKeyIdentifierExtension.create(serverCaKeys.publicKey)
        ]
      });

      // generate client CA
      const clientCaSerialNumber = createSerialNumber();
      const clientCaIssuedAt = new Date();
      const clientCaExpiration = new Date(new Date().setFullYear(2045));
      const clientCaKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
      const clientCaSkObj = crypto.nativeCrypto.KeyObject.from(clientCaKeys.privateKey);
      const clientCaCert = await x509.X509CertificateGenerator.create({
        serialNumber: clientCaSerialNumber,
        subject: `O=${orgId},CN=Infisical Gateway Client CA`,
        issuer: rootCaCert.subject,
        notBefore: getNotBeforeWithClockSkew(clientCaIssuedAt),
        notAfter: getNotAfterWithClockSkew(clientCaExpiration),
        signingKey: rootCaKeys.privateKey,
        publicKey: clientCaKeys.publicKey,
        signingAlgorithm: alg,
        extensions: [
          new x509.KeyUsagesExtension(
            // eslint-disable-next-line no-bitwise
            x509.KeyUsageFlags.keyCertSign |
              x509.KeyUsageFlags.cRLSign |
              x509.KeyUsageFlags.digitalSignature |
              x509.KeyUsageFlags.keyEncipherment,
            true
          ),
          new x509.BasicConstraintsExtension(true, 0, true),
          await x509.AuthorityKeyIdentifierExtension.create(rootCaCert, false),
          await x509.SubjectKeyIdentifierExtension.create(clientCaKeys.publicKey)
        ]
      });

      const encryptedRootGatewayCaPrivateKey = orgKmsEncryptor({
        plainText: Buffer.from(
          rootCaSkObj.export({
            type: "pkcs8",
            format: "der"
          })
        )
      }).cipherTextBlob;
      const encryptedRootGatewayCaCertificate = orgKmsEncryptor({
        plainText: Buffer.from(rootCaCert.rawData)
      }).cipherTextBlob;

      const encryptedGatewayServerCaPrivateKey = orgKmsEncryptor({
        plainText: Buffer.from(serverCaSkObj.export({ type: "pkcs8", format: "der" }))
      }).cipherTextBlob;
      const encryptedGatewayServerCaCertificate = orgKmsEncryptor({
        plainText: Buffer.from(serverCaCert.rawData)
      }).cipherTextBlob;
      const encryptedGatewayServerCaCertificateChain = orgKmsEncryptor({
        plainText: Buffer.from(constructPemChainFromCerts([rootCaCert]))
      }).cipherTextBlob;

      const encryptedGatewayClientCaPrivateKey = orgKmsEncryptor({
        plainText: Buffer.from(clientCaSkObj.export({ type: "pkcs8", format: "der" }))
      }).cipherTextBlob;
      const encryptedGatewayClientCaCertificate = orgKmsEncryptor({
        plainText: Buffer.from(clientCaCert.rawData)
      }).cipherTextBlob;
      const encryptedGatewayClientCaCertificateChain = orgKmsEncryptor({
        plainText: Buffer.from(constructPemChainFromCerts([rootCaCert]))
      }).cipherTextBlob;

      return orgGatewayConfigV2DAL.create({
        orgId,
        encryptedRootGatewayCaPrivateKey,
        encryptedRootGatewayCaCertificate,
        encryptedGatewayServerCaPrivateKey,
        encryptedGatewayServerCaCertificate,
        encryptedGatewayServerCaCertificateChain,
        encryptedGatewayClientCaPrivateKey,
        encryptedGatewayClientCaCertificate,
        encryptedGatewayClientCaCertificateChain
      });
    });

    const rootGatewayCaPrivateKey = orgKmsDecryptor({ cipherTextBlob: orgCAs.encryptedRootGatewayCaPrivateKey });
    const rootGatewayCaCertificate = orgKmsDecryptor({ cipherTextBlob: orgCAs.encryptedRootGatewayCaCertificate });

    const gatewayServerCaPrivateKey = orgKmsDecryptor({ cipherTextBlob: orgCAs.encryptedGatewayServerCaPrivateKey });
    const gatewayServerCaCertificate = orgKmsDecryptor({ cipherTextBlob: orgCAs.encryptedGatewayServerCaCertificate });
    const gatewayServerCaCertificateChain = orgKmsDecryptor({
      cipherTextBlob: orgCAs.encryptedGatewayServerCaCertificateChain
    });

    const gatewayClientCaPrivateKey = orgKmsDecryptor({ cipherTextBlob: orgCAs.encryptedGatewayClientCaPrivateKey });
    const gatewayClientCaCertificate = orgKmsDecryptor({
      cipherTextBlob: orgCAs.encryptedGatewayClientCaCertificate
    });
    const gatewayClientCaCertificateChain = orgKmsDecryptor({
      cipherTextBlob: orgCAs.encryptedGatewayClientCaCertificateChain
    });

    return {
      rootGatewayCaPrivateKey,
      rootGatewayCaCertificate,
      gatewayServerCaPrivateKey,
      gatewayServerCaCertificate,
      gatewayServerCaCertificateChain,
      gatewayClientCaPrivateKey,
      gatewayClientCaCertificate,
      gatewayClientCaCertificateChain
    };
  };

  const listGateways = async ({ orgPermission }: { orgPermission: OrgServiceActor }) => {
    const { permission } = await permissionService.getOrgPermission({
      actor: orgPermission.type,
      actorId: orgPermission.id,
      orgId: orgPermission.orgId,
      actorAuthMethod: orgPermission.authMethod,
      actorOrgId: orgPermission.orgId,
      scope: OrganizationActionScope.Any
    });

    ForbiddenError.from(permission).throwUnlessCan(
      OrgPermissionGatewayActions.ListGateways,
      OrgPermissionSubjects.Gateway
    );

    const gateways = await gatewayV2DAL.find({
      orgId: orgPermission.orgId
    });

    if (gateways.length === 0) {
      return [];
    }

    const gatewayIds = gateways.map((g) => g.id);

    const [
      appConnectionsCounts,
      dynamicSecretsCounts,
      kubernetesAuthsCounts,
      pkiDiscoveryConfigsCounts,
      pamAccountsCounts,
      pamAccountTemplatesCounts
    ] = await Promise.all([
      Promise.all(gatewayIds.map((id) => appConnectionDAL.countByGatewayId(id).then((count) => ({ id, count })))),
      Promise.all(gatewayIds.map((id) => dynamicSecretDAL.countByGatewayId(id).then((count) => ({ id, count })))),
      Promise.all(
        gatewayIds.map((id) => identityKubernetesAuthDAL.countByGatewayId(id).then((count) => ({ id, count })))
      ),
      Promise.all(gatewayIds.map((id) => pkiDiscoveryConfigDAL.countByGatewayId(id).then((count) => ({ id, count })))),
      pamAccountDAL.countByGatewayIds(gatewayIds),
      pamAccountTemplateDAL.countByGatewayIds(gatewayIds)
    ]);

    const countMap = new Map<string, number>();

    for (const { id, count } of appConnectionsCounts) {
      countMap.set(id, (countMap.get(id) ?? 0) + count);
    }
    for (const { id, count } of dynamicSecretsCounts) {
      countMap.set(id, (countMap.get(id) ?? 0) + count);
    }
    for (const { id, count } of kubernetesAuthsCounts) {
      countMap.set(id, (countMap.get(id) ?? 0) + count);
    }
    for (const { id, count } of pkiDiscoveryConfigsCounts) {
      countMap.set(id, (countMap.get(id) ?? 0) + count);
    }
    for (const { id, count } of pamAccountsCounts) {
      countMap.set(id, (countMap.get(id) ?? 0) + count);
    }
    for (const { id, count } of pamAccountTemplatesCounts) {
      countMap.set(id, (countMap.get(id) ?? 0) + count);
    }

    return gateways.map((gateway) => ({
      ...gateway,
      connectedResourcesCount: countMap.get(gateway.id) ?? 0
    }));
  };

  const getPlatformConnectionDetailsByGatewayId = async ({
    gatewayId,
    targetHost,
    targetPort,
    // Named in the signed cert so the gateway need not trust a port out of the request body.
    additionalTargetPorts,
    transport
  }: {
    gatewayId: string;
    targetHost: string;
    targetPort: number;
    additionalTargetPorts?: number[];
    transport?: GatewayTransport;
  }): Promise<TGatewayV2ConnectionDetails | undefined> => {
    const gateway = await gatewayV2DAL.findById(gatewayId);
    if (!gateway) {
      return;
    }

    const orgGatewayConfig = await orgGatewayConfigV2DAL.findOne({ orgId: gateway.orgId });
    if (!orgGatewayConfig) {
      throw new NotFoundError({ message: `Gateway Config for org ${gateway.orgId} not found.` });
    }

    const { useDirect, useRelay, hasTransport } = resolveTransports({ gateway, transport });

    if (!hasTransport) {
      throw new BadRequestError({
        message: `Gateway does not have a ${transport ?? "reachable"} transport configured`
      });
    }

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

    const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048);

    const rootGatewayCaCert = new x509.X509Certificate(
      orgKmsDecryptor({
        cipherTextBlob: orgGatewayConfig.encryptedRootGatewayCaCertificate
      })
    );

    const gatewayClientCaCert = new x509.X509Certificate(
      orgKmsDecryptor({
        cipherTextBlob: orgGatewayConfig.encryptedGatewayClientCaCertificate
      })
    );

    const gatewayServerCaCert = new x509.X509Certificate(
      orgKmsDecryptor({
        cipherTextBlob: orgGatewayConfig.encryptedGatewayServerCaCertificate
      })
    );

    const gatewayClientCaPrivateKey = orgKmsDecryptor({
      cipherTextBlob: orgGatewayConfig.encryptedGatewayClientCaPrivateKey
    });

    const gatewayClientCaSkObj = crypto.nativeCrypto.createPrivateKey({
      key: gatewayClientCaPrivateKey,
      format: "der",
      type: "pkcs8"
    });

    const importedGatewayClientCaPrivateKey = await crypto.nativeCrypto.subtle.importKey(
      "pkcs8",
      gatewayClientCaSkObj.export({ format: "der", type: "pkcs8" }),
      alg,
      true,
      ["sign"]
    );

    const clientCertIssuedAt = new Date();
    const clientCertExpiration = new Date(new Date().getTime() + 5 * 60 * 1000);
    const clientKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
    const clientCertSerialNumber = createSerialNumber();

    const allowedPorts = [targetPort, ...(additionalTargetPorts ?? [])].filter(
      (port, index, ports) => port > 0 && ports.indexOf(port) === index
    );
    const routingInfo = {
      targetHost,
      targetPort,
      ...(allowedPorts.length > 1 ? { targetPorts: allowedPorts } : {})
    };

    const routingExtension = new x509.Extension(
      GATEWAY_ROUTING_INFO_OID,
      false,
      Buffer.from(JSON.stringify(routingInfo))
    );

    const actorExtension = new x509.Extension(
      GATEWAY_ACTOR_OID,
      false,
      Buffer.from(JSON.stringify({ type: ActorType.PLATFORM }))
    );

    const clientCert = await x509.X509CertificateGenerator.create({
      serialNumber: clientCertSerialNumber,
      subject: `O=${orgGatewayConfig.orgId},OU=gateway-client,CN=${ActorType.PLATFORM}:${gatewayId}`,
      issuer: gatewayClientCaCert.subject,
      notAfter: getNotAfterWithClockSkew(clientCertExpiration),
      notBefore: getNotBeforeWithClockSkew(clientCertIssuedAt),
      signingKey: importedGatewayClientCaPrivateKey,
      publicKey: clientKeys.publicKey,
      signingAlgorithm: alg,
      extensions: [
        new x509.BasicConstraintsExtension(false),
        await x509.AuthorityKeyIdentifierExtension.create(gatewayClientCaCert, false),
        await x509.SubjectKeyIdentifierExtension.create(clientKeys.publicKey),
        new x509.CertificatePolicyExtension(["2.5.29.32.0"]), // anyPolicy
        new x509.KeyUsagesExtension(
          // eslint-disable-next-line no-bitwise
          x509.KeyUsageFlags[CertKeyUsage.DIGITAL_SIGNATURE] |
            x509.KeyUsageFlags[CertKeyUsage.KEY_ENCIPHERMENT] |
            x509.KeyUsageFlags[CertKeyUsage.KEY_AGREEMENT],
          true
        ),
        new x509.ExtendedKeyUsageExtension([x509.ExtendedKeyUsage[CertExtendedKeyUsage.CLIENT_AUTH]], true),
        routingExtension,
        actorExtension
      ]
    });

    const gatewayClientCertPrivateKey = crypto.nativeCrypto.KeyObject.from(clientKeys.privateKey);

    const relayCredentials =
      useRelay && gateway.relayId
        ? await relayService.getCredentialsForClient({
            relayId: gateway.relayId,
            orgId: gateway.orgId,
            orgName: gateway.orgName,
            gatewayId,
            gatewayName: gateway.name
          })
        : undefined;

    return {
      gatewayId,
      directAddress: useDirect ? (gateway.directAddress ?? undefined) : undefined,
      relayHost: relayCredentials?.relayHost,
      gateway: {
        clientCertificate: clientCert.toString("pem"),
        clientPrivateKey: gatewayClientCertPrivateKey.export({ format: "pem", type: "pkcs8" }).toString(),
        serverCertificateChain: constructPemChainFromCerts([gatewayServerCaCert, rootGatewayCaCert])
      },
      relay: relayCredentials
        ? {
            clientCertificate: relayCredentials.clientCertificate,
            clientPrivateKey: relayCredentials.clientPrivateKey,
            serverCertificateChain: relayCredentials.serverCertificateChain
          }
        : undefined
    };
  };

  const getPAMConnectionDetails = async ({
    gatewayId,
    sessionId,
    duration,
    accountType,
    host,
    port,
    actorMetadata,
    clientSupportsDirect
  }: {
    gatewayId: string;
    sessionId: string;
    accountType: PamAccountType;
    duration?: number;
    host: string;
    port?: number;
    actorMetadata: { id: string; type: ActorType; name: string };
    clientSupportsDirect: boolean;
  }) => {
    const gateway = await gatewayV2DAL.findById(gatewayId);
    if (!gateway) {
      return;
    }

    const orgGatewayConfig = await orgGatewayConfigV2DAL.findOne({ orgId: gateway.orgId });
    if (!orgGatewayConfig) {
      throw new NotFoundError({ message: `Gateway Config for org ${gateway.orgId} not found.` });
    }

    const { allowDirect, hasTransport, isDirectOnlyForOlderClient, gatewayHasTransport } = resolveClientTransports({
      gateway,
      clientSupportsDirect
    });

    if (isDirectOnlyForOlderClient) {
      throw new BadRequestError({
        message: "This gateway only supports direct connections. Upgrade the Infisical CLI to connect to it."
      });
    }
    if (!hasTransport) {
      throw new BadRequestError({
        message: gatewayHasTransport
          ? "This gateway's connection transports are not supported by your client. Upgrade the Infisical CLI to connect to it."
          : "Gateway has no configured connection transport"
      });
    }

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

    const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048);

    const rootGatewayCaCert = new x509.X509Certificate(
      orgKmsDecryptor({
        cipherTextBlob: orgGatewayConfig.encryptedRootGatewayCaCertificate
      })
    );

    const gatewayClientCaCert = new x509.X509Certificate(
      orgKmsDecryptor({
        cipherTextBlob: orgGatewayConfig.encryptedGatewayClientCaCertificate
      })
    );

    const gatewayServerCaCert = new x509.X509Certificate(
      orgKmsDecryptor({
        cipherTextBlob: orgGatewayConfig.encryptedGatewayServerCaCertificate
      })
    );

    const gatewayClientCaPrivateKey = orgKmsDecryptor({
      cipherTextBlob: orgGatewayConfig.encryptedGatewayClientCaPrivateKey
    });

    const gatewayClientCaSkObj = crypto.nativeCrypto.createPrivateKey({
      key: gatewayClientCaPrivateKey,
      format: "der",
      type: "pkcs8"
    });

    const importedGatewayClientCaPrivateKey = await crypto.nativeCrypto.subtle.importKey(
      "pkcs8",
      gatewayClientCaSkObj.export({ format: "der", type: "pkcs8" }),
      alg,
      true,
      ["sign"]
    );

    const clientCertIssuedAt = new Date();
    const clientCertExpiration = new Date(new Date().getTime() + (duration ?? 5 * 60 * 1000));
    const clientKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
    const clientCertSerialNumber = createSerialNumber();

    const routingInfo = {
      targetHost: host,
      targetPort: port ?? 0
    };

    const routingExtension = new x509.Extension(
      GATEWAY_ROUTING_INFO_OID,
      false,
      Buffer.from(JSON.stringify(routingInfo))
    );

    const pamInfoExtension = new x509.Extension(
      PAM_INFO_OID,
      false,
      Buffer.from(
        JSON.stringify({
          sessionId,
          resourceType: accountType // "resourceType" name needed to support current CLI version
        })
      )
    );

    const actorExtension = new x509.Extension(
      GATEWAY_ACTOR_OID,
      false,
      Buffer.from(JSON.stringify({ type: actorMetadata.type, id: actorMetadata.id, name: actorMetadata.name }))
    );

    const clientCert = await x509.X509CertificateGenerator.create({
      serialNumber: clientCertSerialNumber,
      subject: `O=${orgGatewayConfig.orgId},OU=gateway-client,CN=${actorMetadata.type}:${gatewayId}`,
      issuer: gatewayClientCaCert.subject,
      notAfter: getNotAfterWithClockSkew(clientCertExpiration),
      notBefore: getNotBeforeWithClockSkew(clientCertIssuedAt),
      signingKey: importedGatewayClientCaPrivateKey,
      publicKey: clientKeys.publicKey,
      signingAlgorithm: alg,
      extensions: [
        new x509.BasicConstraintsExtension(false),
        await x509.AuthorityKeyIdentifierExtension.create(gatewayClientCaCert, false),
        await x509.SubjectKeyIdentifierExtension.create(clientKeys.publicKey),
        new x509.CertificatePolicyExtension(["2.5.29.32.0"]), // anyPolicy
        new x509.KeyUsagesExtension(
          // eslint-disable-next-line no-bitwise
          x509.KeyUsageFlags[CertKeyUsage.DIGITAL_SIGNATURE] |
            x509.KeyUsageFlags[CertKeyUsage.KEY_ENCIPHERMENT] |
            x509.KeyUsageFlags[CertKeyUsage.KEY_AGREEMENT],
          true
        ),
        new x509.ExtendedKeyUsageExtension([x509.ExtendedKeyUsage[CertExtendedKeyUsage.CLIENT_AUTH]], true),
        routingExtension,
        actorExtension,
        pamInfoExtension
      ]
    });

    const gatewayClientCertPrivateKey = crypto.nativeCrypto.KeyObject.from(clientKeys.privateKey);

    const relayCredentials = gateway.relayId
      ? await relayService.getCredentialsForClient({
          relayId: gateway.relayId,
          orgId: gateway.orgId,
          orgName: gateway.orgName,
          gatewayId,
          gatewayName: gateway.name,
          duration
        })
      : undefined;

    return {
      gatewayId,
      directAddress: allowDirect ? (gateway.directAddress ?? undefined) : undefined,
      relayHost: relayCredentials?.relayHost,
      gateway: {
        clientCertificate: clientCert.toString("pem"),
        clientPrivateKey: gatewayClientCertPrivateKey.export({ format: "pem", type: "pkcs8" }).toString(),
        serverCertificateChain: constructPemChainFromCerts([gatewayServerCaCert, rootGatewayCaCert])
      },
      relay: relayCredentials
        ? {
            clientCertificate: relayCredentials.clientCertificate,
            clientPrivateKey: relayCredentials.clientPrivateKey,
            serverCertificateChain: relayCredentials.serverCertificateChain
          }
        : undefined
    };
  };

  const $issueGatewayCerts = async ({
    orgId,
    orgCAs,
    relayName,
    gateway
  }: {
    orgId: string;
    orgCAs: Awaited<ReturnType<typeof $getOrgCAs>>;
    relayName?: string;
    gateway: { id: string; name: string; directAddress?: string | null };
  }) => {
    const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048);
    const gatewayServerCaCert = new x509.X509Certificate(orgCAs.gatewayServerCaCertificate);
    const rootGatewayCaCert = new x509.X509Certificate(orgCAs.rootGatewayCaCertificate);
    const gatewayClientCaCert = new x509.X509Certificate(orgCAs.gatewayClientCaCertificate);

    const gatewayServerCaSkObj = crypto.nativeCrypto.createPrivateKey({
      key: orgCAs.gatewayServerCaPrivateKey,
      format: "der",
      type: "pkcs8"
    });
    const gatewayServerCaPrivateKey = await crypto.nativeCrypto.subtle.importKey(
      "pkcs8",
      gatewayServerCaSkObj.export({ format: "der", type: "pkcs8" }),
      alg,
      true,
      ["sign"]
    );

    const { certificate: gatewayServerCertificate, privateKey: gatewayServerCertPrivateKey } =
      await issueGatewayServerCertificate({
        orgId,
        gateway,
        caCertificate: gatewayServerCaCert,
        caPrivateKey: gatewayServerCaPrivateKey
      });

    const relayCredentials = relayName
      ? await relayService.getCredentialsForGateway({
          relayName,
          orgId,
          gatewayId: gateway.id,
          gatewayName: gateway.name
        })
      : undefined;

    return {
      gatewayId: gateway.id,
      // For the audit log; not in either response schema, so zod strips it.
      gatewayName: gateway.name,
      directAddress: gateway.directAddress ?? undefined,
      relayHost: relayCredentials?.relayHost,
      pki: {
        serverCertificate: gatewayServerCertificate.toString("pem"),
        serverPrivateKey: gatewayServerCertPrivateKey.export({ format: "pem", type: "pkcs8" }).toString(),
        clientCertificateChain: constructPemChainFromCerts([gatewayClientCaCert, rootGatewayCaCert])
      },
      ssh: relayCredentials
        ? {
            clientCertificate: relayCredentials.clientSshCert,
            clientPrivateKey: relayCredentials.clientSshPrivateKey,
            serverCAPublicKey: relayCredentials.serverCAPublicKey
          }
        : undefined
    };
  };

  // Revoking clears a gateway's transports and bumps its token version. A connect authenticated just
  // before the revoke would otherwise write them back after it, so the write only lands while the
  // version the request authenticated with is still current.
  const $writeAgentTransports = async (
    gatewayId: string,
    tokenVersion: number | undefined,
    transports: Pick<TGatewaysV2Update, "directAddress" | "directHeartbeat" | "heartbeat" | "relayId">
  ) => {
    if (tokenVersion === undefined) {
      throw new UnauthorizedError({ message: "Gateway token has been revoked" });
    }
    const [updated] = await gatewayV2DAL.update({ id: gatewayId, tokenVersion }, transports);
    if (!updated) {
      throw new UnauthorizedError({ message: "Gateway token has been revoked" });
    }
    return updated;
  };

  const registerGateway = async ({
    orgId,
    actorId,
    actorType,
    actorAuthMethod,
    relayName,
    directAddress,
    name,
    tokenVersion
  }: {
    orgId: string;
    actorId: string;
    actorType: ActorType;
    actorAuthMethod: ActorAuthMethod;
    relayName?: string;
    directAddress?: string;
    name?: string;
    /** The gateway access token's version, when a gateway agent is the actor. */
    tokenVersion?: number;
  }) => {
    if (directAddress) {
      if (getConfig().isCloud) {
        throw new BadRequestError({ message: "Direct gateway connections are not available on Infisical Cloud" });
      }
      const { host } = parseDirectAddress(directAddress);
      // Once per address change rather than once per dial, since this resolves DNS.
      await assertHostNotInfisicalInfrastructure({ host });
    }
    const orgCAs = await $getOrgCAs(orgId);

    // Enrollment-flow gateways authenticate with GATEWAY_ACCESS_TOKEN — the gateway row
    // already exists, so we just look it up and issue fresh certs using its stored relay.
    if (actorType === ActorType.GATEWAY) {
      const gateway = await gatewayV2DAL.findById(actorId);
      if (!gateway || gateway.orgId !== orgId) {
        throw new NotFoundError({ message: `Gateway ${actorId} not found` });
      }

      let resolvedRelay: TRelays | undefined;
      if (relayName) {
        resolvedRelay = await relayDAL.findOne({ orgId, name: relayName });
        if (!resolvedRelay) resolvedRelay = await relayDAL.findOne({ name: relayName, orgId: null });
        if (!resolvedRelay) throw new NotFoundError({ message: `Relay ${relayName} not found` });
      } else if (!directAddress && gateway.relayId) {
        resolvedRelay = await relayDAL.findById(gateway.relayId);
        if (!resolvedRelay) throw new NotFoundError({ message: "No relay associated with this gateway" });
      } else if (!directAddress) {
        throw new NotFoundError({ message: "No connection transport associated with this gateway" });
      }

      // The gateway declares its full transport set every call, so an omitted transport is removed.
      const registeredGateway = await $writeAgentTransports(gateway.id, tokenVersion, {
        directAddress: directAddress ?? null,
        directHeartbeat: directAddress === gateway.directAddress ? gateway.directHeartbeat : null,
        heartbeat: resolvedRelay?.id === gateway.relayId ? gateway.heartbeat : null,
        relayId: resolvedRelay?.id ?? null
      });

      return $issueGatewayCerts({ orgId, orgCAs, relayName: resolvedRelay?.name, gateway: registeredGateway });
    }

    // Identity-based flow: upsert the gateway row then issue certs.
    await $validateIdentityAccessToGateway(orgId, actorId, actorAuthMethod);

    if (!name) {
      throw new BadRequestError({ message: "Gateway name is required" });
    }

    if (!relayName && !directAddress) {
      throw new BadRequestError({ message: "A relay name or direct address is required" });
    }

    let relay: TRelays | undefined;
    if (relayName) {
      relay = await relayDAL.findOne({ orgId, name: relayName });
      if (!relay) relay = await relayDAL.findOne({ name: relayName, orgId: null });
      if (!relay) throw new NotFoundError({ message: `Relay ${relayName} not found` });
    }

    try {
      const gateway = await gatewayV2DAL.transaction(async (tx) => {
        const [upserted] = await gatewayV2DAL.upsert(
          [
            {
              orgId,
              name,
              identityId: actorId,
              relayId: relay?.id ?? null,
              directAddress: directAddress ?? null,
              directHeartbeat: null,
              heartbeat: null
            }
          ],
          ["identityId"],
          tx
        );

        return upserted;
      });

      return await $issueGatewayCerts({ orgId, orgCAs, relayName: relay?.name, gateway });
    } catch (err) {
      if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
        throw new BadRequestError({ message: "A gateway with this name already exists" });
      }

      throw err;
    }
  };

  const $checkGatewayHealth = async (gatewayId: string, transport?: GatewayTransport) => {
    const gatewayV2ConnectionDetails = await getPlatformConnectionDetailsByGatewayId({
      gatewayId,
      targetHost: "health-check",
      targetPort: 443,
      transport
    });

    if (!gatewayV2ConnectionDetails) {
      throw new NotFoundError({ message: `Gateway connection details for gateway ${gatewayId} not found.` });
    }

    const probeResponse = await withGatewayV2Proxy(
      async (port) => {
        return new Promise<string>((resolve, reject) => {
          const socket = new net.Socket();
          let isResolved = false;
          const chunks: Buffer[] = [];

          socket.setTimeout(10000);

          const cleanup = () => {
            if (!socket.destroyed) {
              socket.destroy();
            }
          };

          socket.on("data", (data: Buffer) => {
            chunks.push(data);
            const totalLength = chunks.reduce((sum, c) => sum + c.length, 0);
            if (totalLength > 1024) {
              if (!isResolved) {
                isResolved = true;
                cleanup();
                reject(new Error("Probe response exceeded 1KB limit"));
              }
              return;
            }
            const response = Buffer.concat(chunks).toString().trim();
            if ((response === "PONG" || response.includes("\n") || response.endsWith("}")) && !isResolved) {
              isResolved = true;
              cleanup();
              resolve(response);
            }
          });

          socket.on("error", (err: Error) => {
            if (!isResolved) {
              isResolved = true;
              cleanup();
              reject(new Error(`TCP connection error: ${err.message}`));
            }
          });

          socket.on("timeout", () => {
            if (!isResolved) {
              isResolved = true;
              cleanup();
              reject(new Error("TCP connection timeout"));
            }
          });

          socket.on("close", () => {
            if (!isResolved) {
              isResolved = true;
              cleanup();
              reject(new Error("Connection closed without receiving response"));
            }
          });

          socket.connect(port, "localhost");
        });
      },
      {
        protocol: GatewayProxyProtocol.Health,
        ...gatewayV2ConnectionDetails
      }
    );

    if (!probeResponse) {
      throw new BadRequestError({ message: `Gateway ${gatewayId} is not reachable` });
    }

    // Parse the response to extract heartbeatTTL.
    // New gateways respond with JSON: {"status":"ok","heartbeatTTL":180}
    // Old gateways respond with plain: PONG
    let heartbeatTTL = DEFAULT_HEARTBEAT_TTL;
    if (probeResponse.startsWith("{")) {
      try {
        const parsed = JSON.parse(probeResponse) as { status?: string; heartbeatTTL?: number };
        if (parsed.status === "ok" && typeof parsed.heartbeatTTL === "number" && parsed.heartbeatTTL > 0) {
          heartbeatTTL = parsed.heartbeatTTL;
        }
      } catch {
        // Malformed JSON — fall back to default TTL since the gateway *was* reachable
        logger.warn({ gatewayId, probeResponse }, "Gateway health probe returned unparseable JSON, using default TTL");
      }
    }

    await gatewayV2DAL.updateById(
      gatewayId,
      transport === GatewayTransport.Direct
        ? { directHeartbeat: new Date(), heartbeatTTL }
        : { heartbeat: new Date(), heartbeatTTL }
    );
  };

  const $checkAllGatewayTransports = async (gatewayId: string) => {
    const gateway = await gatewayV2DAL.findById(gatewayId);
    if (!gateway) throw new NotFoundError({ message: `Gateway ${gatewayId} not found` });

    const transports: GatewayTransport[] = [];
    if (gateway.directAddress) transports.push(GatewayTransport.Direct);
    if (gateway.relayId) transports.push(GatewayTransport.Relay);
    if (transports.length === 0) {
      throw new BadRequestError({ message: `Gateway ${gatewayId} has no configured connection transport` });
    }

    const results = await Promise.allSettled(transports.map((transport) => $checkGatewayHealth(gatewayId, transport)));

    // One transport failing raises nothing, so log it or a broken direct path stays invisible.
    results.forEach((result, index) => {
      if (result.status !== "rejected") return;
      const err = result.reason instanceof Error ? result.reason : new Error(String(result.reason));
      logger.warn(
        { gatewayId, transport: transports[index], err },
        `Gateway ${gatewayId} health probe failed on its ${transports[index]} transport`
      );
    });

    if (results.every((result) => result.status === "rejected")) {
      await gatewayV2DAL.updateById(gatewayId, { heartbeatTTL: 0 });
      const failure = results.find((result): result is PromiseRejectedResult => result.status === "rejected");
      if (failure?.reason instanceof Error) throw failure.reason;
      throw new BadRequestError({
        message: `Gateway ${gatewayId} is not reachable on any configured transport`
      });
    }
  };

  const triggerHeartbeat = async ({ orgPermission, id }: { orgPermission: OrgServiceActor; id: string }) => {
    const gateway = await gatewayV2DAL.findOne({ id, orgId: orgPermission.orgId });
    if (!gateway) {
      throw new NotFoundError({ message: `Gateway ${id} not found` });
    }

    const { permission } = await permissionService.getOrgPermission({
      actor: orgPermission.type,
      actorId: orgPermission.id,
      orgId: gateway.orgId,
      actorAuthMethod: orgPermission.authMethod,
      actorOrgId: orgPermission.orgId,
      scope: OrganizationActionScope.Any
    });

    ForbiddenError.from(permission).throwUnlessCan(
      OrgPermissionGatewayActions.ListGateways,
      OrgPermissionSubjects.Gateway
    );

    await $checkAllGatewayTransports(gateway.id);
  };

  const heartbeat = async ({
    orgPermission,
    capabilities
  }: {
    orgPermission: OrgServiceActor;
    capabilities?: {
      pkcs11?: boolean;
      pkcs11MlDsa?: boolean;
      sessionLogMaskingBuiltInDetection?: boolean;
      clickhouseNativeProtocol?: boolean;
      certificateScan?: boolean;
      windowsCertificateScan?: boolean;
      supported_account_types?: string[];
    };
  }) => {
    const nextCapabilities = capabilities ?? {};

    if (orgPermission.type === ActorType.GATEWAY) {
      const gateway = await gatewayV2DAL.findById(orgPermission.id);
      if (!gateway || gateway.orgId !== orgPermission.orgId) {
        throw new NotFoundError({ message: `Gateway ${orgPermission.id} not found.` });
      }
      await gatewayV2DAL.updateById(gateway.id, { capabilities: nextCapabilities });
      await $checkAllGatewayTransports(gateway.id);
      return;
    }

    await $validateIdentityAccessToGateway(orgPermission.orgId, orgPermission.id, orgPermission.authMethod);

    const gateway = await gatewayV2DAL.findOne({
      orgId: orgPermission.orgId,
      identityId: orgPermission.id
    });

    if (!gateway) {
      throw new NotFoundError({ message: `Gateway for identity ${orgPermission.id} not found.` });
    }

    await gatewayV2DAL.updateById(gateway.id, { capabilities: nextCapabilities });
    await $checkAllGatewayTransports(gateway.id);
  };

  const reportMetrics = async ({
    orgPermission,
    activeChannels
  }: {
    orgPermission: OrgServiceActor;
    activeChannels: number;
  }) => {
    let gateway;
    if (orgPermission.type === ActorType.GATEWAY) {
      gateway = await gatewayV2DAL.findById(orgPermission.id);
    } else {
      // Same check heartbeat makes: an identity whose gateway permission was revoked must not keep
      // submitting occupancy values and steering pool routing.
      await $validateIdentityAccessToGateway(orgPermission.orgId, orgPermission.id, orgPermission.authMethod);
      gateway = await gatewayV2DAL.findOne({ orgId: orgPermission.orgId, identityId: orgPermission.id });
    }

    if (!gateway || gateway.orgId !== orgPermission.orgId) {
      throw new NotFoundError({ message: `Gateway with ID '${orgPermission.id}' not found` });
    }

    // Do not mark the gateway alive here. A load report only proves the gateway can reach us;
    // heartbeat proves we can reach it back over one of its transports. Updating liveness from this
    // would keep a gateway whose inbound path is broken looking healthy.
    await getGatewayLoadTracker()?.recordReportedLoad(gateway.id, activeChannels);

    return { gatewayId: gateway.id, activeChannels };
  };

  const deleteGatewayById = async ({ orgPermission, id }: { orgPermission: OrgServiceActor; id: string }) => {
    const gateway = await gatewayV2DAL.findOne({ id, orgId: orgPermission.orgId });
    if (!gateway) {
      throw new NotFoundError({ message: `Gateway ${id} not found` });
    }

    const { permission } = await permissionService.getOrgPermission({
      actor: orgPermission.type,
      actorId: orgPermission.id,
      orgId: gateway.orgId,
      actorAuthMethod: orgPermission.authMethod,
      actorOrgId: orgPermission.orgId,
      scope: OrganizationActionScope.Any
    });

    ForbiddenError.from(permission).throwUnlessCan(
      OrgPermissionGatewayActions.DeleteGateways,
      OrgPermissionSubjects.Gateway
    );

    const proxyDependents = await resourceAuthMethodService.findKubernetesProxyDependents(gateway.id);
    if (proxyDependents.length) {
      throw new BadRequestError({
        message: `Gateway '${gateway.name}' reviews Kubernetes tokens for ${proxyDependents.map((name) => `'${name}'`).join(", ")}. Point those gateways at a different reviewer before deleting this one.`
      });
    }

    // app_connections.gatewayId has no foreign key, so nothing in the database stops a delete that
    // would leave a connection routing through a gateway that no longer exists.
    const appConnections = await appConnectionDAL.findByGatewayId(gateway.id);
    if (appConnections.length) {
      throw new BadRequestError({
        message: `Gateway '${gateway.name}' is used by app connection(s) ${appConnections.map((c) => `'${c.name}'`).join(", ")}. Remove the gateway from those connections before deleting it.`
      });
    }

    try {
      return await gatewayV2DAL.deleteById(gateway.id);
    } catch (err) {
      if (
        err instanceof DatabaseError &&
        (err.error as { code: string })?.code === DatabaseErrorCode.ForeignKeyViolation
      ) {
        throw new BadRequestError({
          message: "Failed to delete gateway because it is attached to active resources"
        });
      }

      throw err;
    }
  };

  const getPamSessionKey = async ({ orgPermission }: { orgPermission: OrgServiceActor }) => {
    // Gateway actors are already authenticated via GATEWAY_ACCESS_TOKEN JWT — skip org permission check.
    if (orgPermission.type !== ActorType.GATEWAY) {
      const { permission } = await permissionService.getOrgPermission({
        actor: orgPermission.type,
        actorId: orgPermission.id,
        orgId: orgPermission.orgId,
        actorAuthMethod: orgPermission.authMethod,
        actorOrgId: orgPermission.orgId,
        scope: OrganizationActionScope.Any
      });

      ForbiddenError.from(permission).throwUnlessCan(
        OrgPermissionGatewayActions.CreateGateways,
        OrgPermissionSubjects.Gateway
      );
    }

    return gatewayV2DAL.transaction(async (tx) => {
      const gateway = await gatewayV2DAL.findOne(
        orgPermission.type === ActorType.GATEWAY ? { id: orgPermission.id } : { identityId: orgPermission.id },
        tx
      );

      if (!gateway) {
        throw new NotFoundError({ message: "Gateway not found" });
      }

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

      if (gateway.encryptedPamSessionKey) {
        return decryptor({ cipherTextBlob: gateway.encryptedPamSessionKey });
      }

      await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.GatewayPamSessionKey(gateway.id)]);
      // Re-read under the lock: a request that waited on it must return the key the first one
      // stored rather than replace it.
      const lockedGateway = await gatewayV2DAL.findById(gateway.id, tx);
      if (lockedGateway?.encryptedPamSessionKey) {
        return decryptor({ cipherTextBlob: lockedGateway.encryptedPamSessionKey });
      }

      const newPamSessionKey = crypto.randomBytes(32);
      const { cipherTextBlob: encryptedPamSessionKey } = encryptor({ plainText: newPamSessionKey });

      await gatewayV2DAL.updateById(gateway.id, { encryptedPamSessionKey }, tx);

      return newPamSessionKey;
    });
  };

  const healthcheckNotify = async () => {
    const unhealthyGateways = await gatewayV2DAL.find({
      isHeartbeatStale: true
    });

    if (unhealthyGateways.length === 0) return;

    logger.warn(
      { gatewayIds: unhealthyGateways.map((g) => g.id) },
      "Found gateways that may be offline or unreachable. Sending notifications."
    );

    const gatewaysByOrg = groupBy(unhealthyGateways, (gw) => gw.orgId);

    for await (const [orgId, gateways] of Object.entries(gatewaysByOrg)) {
      try {
        const admins = (await orgDAL.findOrgMembersByRole(orgId, OrgMembershipRole.Admin)).filter(
          (admin) => admin.status !== OrgMembershipStatus.Invited
        );
        if (admins.length === 0) {
          logger.warn({ orgId }, "Organization has no admins to notify about unhealthy gateway.");
          // eslint-disable-next-line no-continue
          continue;
        }

        const gatewayNames = gateways.map((g) => `"${g.name}"`).join(", ");
        const body = `The following gateway(s) in your organization may be offline or unreachable: ${gatewayNames}. Please check their status.`;

        await notificationService.createUserNotifications(
          admins.map((admin) => ({
            userId: admin.user.id,
            orgId,
            type: NotificationType.GATEWAY_HEALTH_ALERT,
            title: "Gateway Health Alert",
            body,
            link: `/organizations/${orgId}/networking`
          }))
        );

        // Temporarily disabled email notifications due to excessive noise. Will be revised later
        //
        // await smtpService.sendMail({
        //   recipients: admins.map((admin) => admin.user.email).filter((v): v is string => !!v),
        //   subjectLine: "Gateway Health Alert",
        //   substitutions: {
        //     type: "gateway",
        //     names: gatewayNames
        //   },
        //   template: SmtpTemplates.HealthAlert
        // });

        await Promise.all(gateways.map((gw) => gatewayV2DAL.updateById(gw.id, { healthAlertedAt: new Date() })));
      } catch (error) {
        logger.error(error, `Failed to send gateway health notifications for organization [orgId=${orgId}]`);
      }
    }
  };

  const getConnectedResources = async ({
    orgPermission,
    gatewayId
  }: {
    orgPermission: OrgServiceActor;
    gatewayId: string;
  }) => {
    const gateway = await gatewayV2DAL.findOne({ id: gatewayId, orgId: orgPermission.orgId });
    if (!gateway) {
      throw new NotFoundError({ message: `Gateway ${gatewayId} not found` });
    }

    const { permission } = await permissionService.getOrgPermission({
      actor: orgPermission.type,
      actorId: orgPermission.id,
      orgId: gateway.orgId,
      actorAuthMethod: orgPermission.authMethod,
      actorOrgId: orgPermission.orgId,
      scope: OrganizationActionScope.Any
    });

    ForbiddenError.from(permission).throwUnlessCan(
      OrgPermissionGatewayActions.ListGateways,
      OrgPermissionSubjects.Gateway
    );

    const [appConnections, dynamicSecrets, kubernetesAuths, pkiDiscoveryConfigs, pamAccounts, pamAccountTemplates] =
      await Promise.all([
        appConnectionDAL.findByGatewayId(gatewayId),
        dynamicSecretDAL.findByGatewayId(gatewayId),
        identityKubernetesAuthDAL.findByGatewayId(gatewayId),
        pkiDiscoveryConfigDAL.findByGatewayId(gatewayId),
        pamAccountDAL.findByGatewayId(gatewayId),
        pamAccountTemplateDAL.findByGatewayId(gatewayId)
      ]);

    return {
      appConnections,
      dynamicSecrets,
      kubernetesAuths,
      pkiDiscoveryConfigs,
      pamAccounts,
      pamAccountTemplates
    };
  };

  const getGatewayById = async ({ gatewayId }: { gatewayId: string }) => {
    const gateway = await gatewayV2DAL.findById(gatewayId);
    if (!gateway) {
      throw new NotFoundError({ message: `Gateway ${gatewayId} not found` });
    }
    return gateway;
  };

  // --- V3 service methods ---

  const $assertCanEditGateway = async (orgPermission: OrgServiceActor, gatewayId: string) => {
    const gateway = await gatewayV2DAL.findOne({ id: gatewayId, orgId: orgPermission.orgId });
    if (!gateway) {
      throw new NotFoundError({ message: `Gateway ${gatewayId} not found` });
    }

    const { permission } = await permissionService.getOrgPermission({
      actor: orgPermission.type,
      actorId: orgPermission.id,
      orgId: gateway.orgId,
      actorAuthMethod: orgPermission.authMethod,
      actorOrgId: orgPermission.orgId,
      scope: OrganizationActionScope.Any
    });

    ForbiddenError.from(permission).throwUnlessCan(
      OrgPermissionGatewayActions.EditGateways,
      OrgPermissionSubjects.Gateway
    );

    return gateway;
  };

  // Setting an auth method dials the customer's cluster, so the two halves of an update cannot
  // share a transaction. Checking the name first means the ordinary rejection lands before the
  // auth method is committed; the unique violation in renameGateway still covers the race.
  const assertGatewayNameAvailable = async ({
    orgPermission,
    gatewayId,
    name
  }: {
    orgPermission: OrgServiceActor;
    gatewayId: string;
    name: string;
  }) => {
    const gateway = await $assertCanEditGateway(orgPermission, gatewayId);
    if (gateway.name === name) return;

    const existing = await gatewayV2DAL.findOne({ orgId: orgPermission.orgId, name });
    if (existing && existing.id !== gatewayId) {
      throw new BadRequestError({ message: `A gateway named "${name}" already exists` });
    }
  };

  const renameGateway = async ({
    orgPermission,
    gatewayId,
    name
  }: {
    orgPermission: OrgServiceActor;
    gatewayId: string;
    name: string;
  }) => {
    const gateway = await $assertCanEditGateway(orgPermission, gatewayId);
    if (gateway.name === name) return { gateway, previousName: name };

    try {
      const renamed = await gatewayV2DAL.updateById(gateway.id, { name });
      return { gateway: renamed, previousName: gateway.name };
    } catch (err) {
      if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
        throw new BadRequestError({ message: `A gateway named "${name}" already exists` });
      }

      throw err;
    }
  };

  const createGateway = async ({
    orgId,
    actorId,
    actorType,
    actorAuthMethod,
    name,
    authMethod
  }: {
    orgId: string;
    actorId: string;
    actorType: ActorType;
    actorAuthMethod: ActorAuthMethod;
    name: string;
    authMethod:
      | { method: "aws"; config: TAwsAuthMethodConfig }
      | { method: "gcp"; config: TGcpAuthMethodConfig }
      | { method: "kubernetes"; config: TKubernetesAuthMethodConfig }
      | { method: "token" };
  }) => {
    const { permission } = await permissionService.getOrgPermission({
      actor: actorType,
      actorId,
      orgId,
      actorAuthMethod,
      actorOrgId: orgId,
      scope: OrganizationActionScope.Any
    });

    ForbiddenError.from(permission).throwUnlessCan(
      OrgPermissionGatewayActions.CreateGateways,
      OrgPermissionSubjects.Gateway
    );

    // The host check (DNS) and the secret encryption (possibly an external KMS) both reach
    // the network, so they run before the transaction is opened rather than inside it.
    let authMethodArg = authMethod;
    if (authMethod.method === "kubernetes") {
      await resourceAuthMethodService.preflightKubernetesConfig(authMethod.config, orgId, undefined, {
        type: actorType,
        id: actorId,
        orgId,
        authMethod: actorAuthMethod
      });
      authMethodArg = {
        method: authMethod.method,
        config: {
          ...authMethod.config,
          ...(await resourceAuthMethodService.encryptKubernetesSecrets(orgId, authMethod.config))
        }
      };
    }

    const gateway = await gatewayV2DAL.transaction(async (tx) => {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-call
      await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.CreateGateway(orgId)]);

      // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-assignment
      const existingGatewayCount = await gatewayV2DAL.countByOrgId(orgId, tx);
      if (existingGatewayCount >= MAX_GATEWAYS_PER_ORG) {
        throw new BadRequestError({
          message: `Organization has reached the maximum limit of ${MAX_GATEWAYS_PER_ORG} gateways`
        });
      }

      let created;
      try {
        created = await gatewayV2DAL.create({ orgId, name }, tx);
      } catch (err) {
        if (
          err instanceof DatabaseError &&
          (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation
        ) {
          throw new BadRequestError({ message: `A gateway named "${name}" already exists` });
        }
        throw err;
      }

      await resourceAuthMethodService.initAtCreate(
        { resource: { type: "gateway", id: created.id }, authMethod: authMethodArg },
        tx
      );

      return created;
    });

    return gateway;
  };

  const connectGateway = async ({
    orgId,
    actorId,
    actorType,
    relayName,
    directAddress,
    tokenVersion
  }: {
    orgId: string;
    actorId: string;
    actorType: ActorType;
    relayName?: string;
    directAddress?: string;
    /** The gateway access token's version the request authenticated with. */
    tokenVersion?: number;
  }) => {
    if (directAddress) {
      if (getConfig().isCloud) {
        throw new BadRequestError({ message: "Direct gateway connections are not available on Infisical Cloud" });
      }
      const { host } = parseDirectAddress(directAddress);
      // Once per address change rather than once per dial, since this resolves DNS.
      await assertHostNotInfisicalInfrastructure({ host });
    }
    const orgCAs = await $getOrgCAs(orgId);

    if (actorType === ActorType.GATEWAY) {
      const gateway = await gatewayV2DAL.findById(actorId);
      if (!gateway || gateway.orgId !== orgId) {
        throw new NotFoundError({ message: `Gateway ${actorId} not found` });
      }

      let resolvedRelay: TRelays | undefined;
      if (relayName) {
        resolvedRelay = await relayDAL.findOne({ orgId, name: relayName });
        if (!resolvedRelay) resolvedRelay = await relayDAL.findOne({ name: relayName, orgId: null });
        if (!resolvedRelay) throw new NotFoundError({ message: `Relay ${relayName} not found` });
      } else if (!directAddress && gateway.relayId) {
        resolvedRelay = await relayDAL.findById(gateway.relayId);
        if (!resolvedRelay) throw new NotFoundError({ message: "No relay associated with this gateway" });
      } else if (!directAddress) {
        throw new NotFoundError({ message: "No connection transport associated with this gateway" });
      }

      // The gateway declares its full transport set every call, so an omitted transport is removed.
      const registeredGateway = await $writeAgentTransports(gateway.id, tokenVersion, {
        directAddress: directAddress ?? null,
        directHeartbeat: directAddress === gateway.directAddress ? gateway.directHeartbeat : null,
        heartbeat: resolvedRelay?.id === gateway.relayId ? gateway.heartbeat : null,
        relayId: resolvedRelay?.id ?? null
      });

      return $issueGatewayCerts({ orgId, orgCAs, relayName: resolvedRelay?.name, gateway: registeredGateway });
    }

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

  const enrollGateway = async ({ token }: { token: string }) => {
    return resourceAuthMethodService.loginWithToken({ token, expectedResourceType: "gateway" });
  };

  return {
    listGateways,
    registerGateway,
    reportMetrics,
    getPlatformConnectionDetailsByGatewayId,
    getPAMConnectionDetails,
    deleteGatewayById,
    heartbeat,
    triggerHeartbeat,
    getPamSessionKey,
    healthcheckNotify,
    getConnectedResources,
    getGatewayById,
    enrollGateway,
    // V3
    createGateway,
    renameGateway,
    assertGatewayNameAvailable,
    connectGateway
  };
};