Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
refactor(gateways): move the transport logic out of the constants file
bernie-g18efe7ffe29c
diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.tsindex 709100f218..ac0cb8456a 100644--- a/backend/src/ee/routes/v2/gateway-router.ts+++ b/backend/src/ee/routes/v2/gateway-router.ts@@ -2,7 +2,7 @@ import z from "zod";import { GatewaysV2Schema } from "@app/db/schemas";import { EventType } from "@app/ee/services/audit-log/audit-log-types";-import { gatewayTransports } from "@app/ee/services/gateway-v2/gateway-v2-constants";+import { gatewayTransports } from "@app/ee/services/gateway-v2/gateway-v2-transport-fns";import { GATEWAYS } from "@app/lib/api-docs";import { zodBuffer } from "@app/lib/zod";import { gatewayMetricsReportLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";diff --git a/backend/src/ee/routes/v3/gateway-router.ts b/backend/src/ee/routes/v3/gateway-router.tsindex f818753edb..1963203d62 100644--- a/backend/src/ee/routes/v3/gateway-router.ts+++ b/backend/src/ee/routes/v3/gateway-router.ts@@ -2,7 +2,7 @@ import z from "zod";import { GatewaysV2Schema } from "@app/db/schemas";import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";-import { gatewayTransports } from "@app/ee/services/gateway-v2/gateway-v2-constants";+import { gatewayTransports } from "@app/ee/services/gateway-v2/gateway-v2-transport-fns";import { validateAccountIds, validatePrincipalArns } from "@app/ee/services/resource-auth-method/aws-auth-validators";import {validateAllowedNames,diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-dal.ts b/backend/src/ee/services/gateway-pool/gateway-pool-dal.tsindex b00a822a17..101fd2439a 100644--- a/backend/src/ee/services/gateway-pool/gateway-pool-dal.ts+++ b/backend/src/ee/services/gateway-pool/gateway-pool-dal.ts@@ -5,7 +5,7 @@ import { TableName } from "@app/db/schemas";import { DatabaseError } from "@app/lib/errors";import { ormify, selectAllTableCols } from "@app/lib/knex";-import { buildGatewayReachableSql } from "../gateway-v2/gateway-v2-constants";+import { buildGatewayReachableSql } from "../gateway-v2/gateway-v2-transport-fns";export type TGatewayPoolDALFactory = ReturnType<typeof gatewayPoolDalFactory>;diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-membership-dal.ts b/backend/src/ee/services/gateway-pool/gateway-pool-membership-dal.tsindex cb44a79892..f9445b7939 100644--- a/backend/src/ee/services/gateway-pool/gateway-pool-membership-dal.ts+++ b/backend/src/ee/services/gateway-pool/gateway-pool-membership-dal.ts@@ -3,7 +3,7 @@ import { TableName, TGatewaysV2 } from "@app/db/schemas";import { DatabaseError } from "@app/lib/errors";import { ormify } from "@app/lib/knex";-import { buildGatewayReachableSql } from "../gateway-v2/gateway-v2-constants";+import { buildGatewayReachableSql } from "../gateway-v2/gateway-v2-transport-fns";export type TGatewayPoolMembershipDALFactory = ReturnType<typeof gatewayPoolMembershipDalFactory>;diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts b/backend/src/ee/services/gateway-v2/gateway-v2-constants.tsindex 6ef7a92f70..7baba5e2a0 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts@@ -1,9 +1,3 @@-import net from "node:net";--import RE2 from "re2";--import { BadRequestError } from "@app/lib/errors";-export const HEARTBEAT_BUFFER_SECONDS = 30;export const DEFAULT_HEARTBEAT_TTL = 1800; // 30 minutes — fallback for old gateways that don't report their interval@@ -11,166 +5,7 @@ export const GATEWAY_ROUTING_INFO_OID = "1.3.6.1.4.1.12345.100.1";export const GATEWAY_ACTOR_OID = "1.3.6.1.4.1.12345.100.2";export const PAM_INFO_OID = "1.3.6.1.4.1.12345.100.3";-// Never probed counts as usable, so a freshly registered gateway is not locked out.-export const isTransportHealthy = ({- probedAt,- heartbeatTTL-}: {- probedAt?: Date | null;- heartbeatTTL?: number | null;-}) => {- if (heartbeatTTL === 0) return false;- if (!probedAt) return true;- const staleAfterMs = ((heartbeatTTL ?? 0) + HEARTBEAT_BUFFER_SECONDS) * 1000;- return Date.now() - new Date(probedAt).getTime() <= staleAfterMs;-};--// Any configured transport with a fresh probe, so a dual gateway stays up when one path breaks.-export const buildGatewayReachableSql = (table: string) => {- const isFresh = (probe: string) =>- `("${table}"."${probe}" IS NOT NULL AND "${table}"."${probe}" + make_interval(secs => COALESCE("${table}"."heartbeatTTL", 0) + ${HEARTBEAT_BUFFER_SECONDS}) > NOW())`;-- return `(COALESCE("${table}"."heartbeatTTL", 0) > 0 AND (("${table}"."directAddress" IS NOT NULL AND ${isFresh(- "directHeartbeat"- )}) OR ("${table}"."relayId" IS NOT NULL AND ${isFresh("heartbeat")})))`;-};--// Ignores which transports are configured now: a gateway whose relay was deleted still needs alerting.-export const buildGatewayProbedSql = (table: string) =>- `("${table}"."directHeartbeat" IS NOT NULL OR "${table}"."heartbeat" IS NOT NULL)`;-export enum GatewayTransport {Direct = "direct",Relay = "relay"}--export type TGatewayTransport = GatewayTransport;--export const resolveTransports = ({- gateway,- transport-}: {- gateway: {- directAddress?: string | null;- relayId?: string | null;- directHeartbeat?: Date | null;- heartbeatTTL?: number | null;- };- transport?: TGatewayTransport;-}) => {- const directUsable =- Boolean(gateway.directAddress) &&- (transport === GatewayTransport.Direct ||- !gateway.relayId ||- isTransportHealthy({ probedAt: gateway.directHeartbeat, heartbeatTTL: gateway.heartbeatTTL }));- const useDirect = transport !== GatewayTransport.Relay && directUsable;- // Relay credentials ride along even when direct is chosen, so a dial can retry before the probe goes stale.- const useRelay = transport !== GatewayTransport.Direct && Boolean(gateway.relayId);-- return { useDirect, useRelay, hasTransport: useDirect || useRelay };-};--export const gatewayTransports = ({- directAddress,- relayHost-}: {- directAddress?: string;- relayHost?: string;-}): TGatewayTransport[] => {- const transports: TGatewayTransport[] = [];- if (directAddress) transports.push(GatewayTransport.Direct);- if (relayHost) transports.push(GatewayTransport.Relay);- return transports;-};--// undefined means the platform dials on the client's behalf; [] is an older CLI that only knows relays.-export const resolveClientTransports = ({- gateway,- supportedTransports-}: {- gateway: {- directAddress?: string | null;- relayId?: string | null;- directHeartbeat?: Date | null;- heartbeatTTL?: number | null;- };- supportedTransports?: TGatewayTransport[];-}) => {- const clientAllowsDirect = supportedTransports === undefined || supportedTransports.includes(GatewayTransport.Direct);- const allowRelay =- supportedTransports === undefined ||- supportedTransports.length === 0 ||- supportedTransports.includes(GatewayTransport.Relay);-- // Skip a stale direct address only when the relay can take over; otherwise it is the client's only path.- const canFallBackToRelay = allowRelay && Boolean(gateway.relayId);- const allowDirect =- clientAllowsDirect &&- (!canFallBackToRelay ||- isTransportHealthy({ probedAt: gateway.directHeartbeat, heartbeatTTL: gateway.heartbeatTTL }));-- const useDirect = allowDirect && Boolean(gateway.directAddress);- const useRelay = allowRelay && Boolean(gateway.relayId);-- return {- allowDirect,- allowRelay,- useDirect,- useRelay,- hasTransport: useDirect || useRelay,- isDirectOnlyForOlderClient: Boolean(gateway.directAddress) && !gateway.relayId && !clientAllowsDirect,- gatewayHasTransport: Boolean(gateway.directAddress || gateway.relayId)- };-};--export const DNS_LABEL_REGEX = new RE2(/^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/);-const TRAILING_DOT_REGEX = new RE2(/\.$/);--// The address lands in copy-and-run deploy commands, so a host carrying shell syntax must not pass.-export const isValidDirectHost = (host: string) => {- if (net.isIP(host)) return true;- if (host.length > 253) return false;- const labels = host.replace(TRAILING_DOT_REGEX, "").split(".");- return labels.length > 0 && labels.every((label) => DNS_LABEL_REGEX.test(label));-};--export const parseDirectAddress = (address: string) => {- // Never echo the address: it can arrive shaped like a connection string.- const invalidFormat = () =>- new BadRequestError({- message: "Gateway direct address must use the host:port format, such as gateway.internal:8443"- });-- let parsed: URL;- try {- parsed = new URL(`tcp://${address}`);- } catch {- throw invalidFormat();- }-- if (- !parsed.hostname ||- !parsed.port ||- parsed.username ||- parsed.password ||- parsed.pathname ||- parsed.search ||- parsed.hash- ) {- throw invalidFormat();- }-- const port = Number(parsed.port);- if (!Number.isInteger(port) || port < 1 || port > 65535) {- throw new BadRequestError({ message: "Gateway direct address must include a port from 1 to 65535" });- }-- const host = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;- if (!isValidDirectHost(host)) {- throw new BadRequestError({- message: "Gateway direct address host must be an IP address or a DNS hostname"- });- }-- return { host, port };-};diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-dal.ts b/backend/src/ee/services/gateway-v2/gateway-v2-dal.tsindex 2afa0ae68f..bf84b4dbda 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-dal.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-dal.ts@@ -5,7 +5,7 @@ import { GatewaysV2Schema, TableName, TGatewaysV2 } from "@app/db/schemas";import { DatabaseError } from "@app/lib/errors";import { buildFindFilter, ormify, selectAllTableCols, TFindFilter, TFindOpt } from "@app/lib/knex";-import { buildGatewayProbedSql, buildGatewayReachableSql } from "./gateway-v2-constants";+import { buildGatewayProbedSql, buildGatewayReachableSql } from "./gateway-v2-transport-fns";export type TGatewayV2DALFactory = ReturnType<typeof gatewayV2DalFactory>;diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.tsindex 6f0f3c0f39..1136fb1e90 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts@@ -48,12 +48,10 @@ import {GATEWAY_ACTOR_OID,GATEWAY_ROUTING_INFO_OID,GatewayTransport,- PAM_INFO_OID,- parseDirectAddress,- resolveClientTransports,- resolveTransports+ 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";diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-transport.test.ts b/backend/src/ee/services/gateway-v2/gateway-v2-transport-fns.test.tssimilarity index 98%rename from backend/src/ee/services/gateway-v2/gateway-v2-transport.test.tsrename to backend/src/ee/services/gateway-v2/gateway-v2-transport-fns.test.tsindex dd54f78e21..09cfd3fd11 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-transport.test.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-transport-fns.test.ts@@ -1,11 +1,10 @@+import { GatewayTransport, HEARTBEAT_BUFFER_SECONDS } from "./gateway-v2-constants";import {- GatewayTransport,- HEARTBEAT_BUFFER_SECONDS,isTransportHealthy,parseDirectAddress,resolveClientTransports,resolveTransports-} from "./gateway-v2-constants";+} from "./gateway-v2-transport-fns";const secondsAgo = (seconds: number) => new Date(Date.now() - seconds * 1000);const TTL = 180;diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-transport-fns.ts b/backend/src/ee/services/gateway-v2/gateway-v2-transport-fns.tsnew file mode 100644index 0000000000..cf509509e6--- /dev/null+++ b/backend/src/ee/services/gateway-v2/gateway-v2-transport-fns.ts@@ -0,0 +1,164 @@+import net from "node:net";++import RE2 from "re2";++import { BadRequestError } from "@app/lib/errors";++import { GatewayTransport, HEARTBEAT_BUFFER_SECONDS } from "./gateway-v2-constants";++// Never probed counts as usable, so a freshly registered gateway is not locked out.+export const isTransportHealthy = ({+ probedAt,+ heartbeatTTL+}: {+ probedAt?: Date | null;+ heartbeatTTL?: number | null;+}) => {+ if (heartbeatTTL === 0) return false;+ if (!probedAt) return true;+ const staleAfterMs = ((heartbeatTTL ?? 0) + HEARTBEAT_BUFFER_SECONDS) * 1000;+ return Date.now() - new Date(probedAt).getTime() <= staleAfterMs;+};++// Any configured transport with a fresh probe, so a dual gateway stays up when one path breaks.+export const buildGatewayReachableSql = (table: string) => {+ const isFresh = (probe: string) =>+ `("${table}"."${probe}" IS NOT NULL AND "${table}"."${probe}" + make_interval(secs => COALESCE("${table}"."heartbeatTTL", 0) + ${HEARTBEAT_BUFFER_SECONDS}) > NOW())`;++ return `(COALESCE("${table}"."heartbeatTTL", 0) > 0 AND (("${table}"."directAddress" IS NOT NULL AND ${isFresh(+ "directHeartbeat"+ )}) OR ("${table}"."relayId" IS NOT NULL AND ${isFresh("heartbeat")})))`;+};++// Ignores which transports are configured now: a gateway whose relay was deleted still needs alerting.+export const buildGatewayProbedSql = (table: string) =>+ `("${table}"."directHeartbeat" IS NOT NULL OR "${table}"."heartbeat" IS NOT NULL)`;++export const resolveTransports = ({+ gateway,+ transport+}: {+ gateway: {+ directAddress?: string | null;+ relayId?: string | null;+ directHeartbeat?: Date | null;+ heartbeatTTL?: number | null;+ };+ transport?: GatewayTransport;+}) => {+ const directUsable =+ Boolean(gateway.directAddress) &&+ (transport === GatewayTransport.Direct ||+ !gateway.relayId ||+ isTransportHealthy({ probedAt: gateway.directHeartbeat, heartbeatTTL: gateway.heartbeatTTL }));+ const useDirect = transport !== GatewayTransport.Relay && directUsable;+ // Relay credentials ride along even when direct is chosen, so a dial can retry before the probe goes stale.+ const useRelay = transport !== GatewayTransport.Direct && Boolean(gateway.relayId);++ return { useDirect, useRelay, hasTransport: useDirect || useRelay };+};++export const gatewayTransports = ({+ directAddress,+ relayHost+}: {+ directAddress?: string;+ relayHost?: string;+}): GatewayTransport[] => {+ const transports: GatewayTransport[] = [];+ if (directAddress) transports.push(GatewayTransport.Direct);+ if (relayHost) transports.push(GatewayTransport.Relay);+ return transports;+};++// undefined means the platform dials on the client's behalf; [] is an older CLI that only knows relays.+export const resolveClientTransports = ({+ gateway,+ supportedTransports+}: {+ gateway: {+ directAddress?: string | null;+ relayId?: string | null;+ directHeartbeat?: Date | null;+ heartbeatTTL?: number | null;+ };+ supportedTransports?: GatewayTransport[];+}) => {+ const clientAllowsDirect = supportedTransports === undefined || supportedTransports.includes(GatewayTransport.Direct);+ const allowRelay =+ supportedTransports === undefined ||+ supportedTransports.length === 0 ||+ supportedTransports.includes(GatewayTransport.Relay);++ // Skip a stale direct address only when the relay can take over; otherwise it is the client's only path.+ const canFallBackToRelay = allowRelay && Boolean(gateway.relayId);+ const allowDirect =+ clientAllowsDirect &&+ (!canFallBackToRelay ||+ isTransportHealthy({ probedAt: gateway.directHeartbeat, heartbeatTTL: gateway.heartbeatTTL }));++ const useDirect = allowDirect && Boolean(gateway.directAddress);+ const useRelay = allowRelay && Boolean(gateway.relayId);++ return {+ allowDirect,+ allowRelay,+ useDirect,+ useRelay,+ hasTransport: useDirect || useRelay,+ isDirectOnlyForOlderClient: Boolean(gateway.directAddress) && !gateway.relayId && !clientAllowsDirect,+ gatewayHasTransport: Boolean(gateway.directAddress || gateway.relayId)+ };+};++export const DNS_LABEL_REGEX = new RE2(/^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/);+const TRAILING_DOT_REGEX = new RE2(/\.$/);++// The address lands in copy-and-run deploy commands, so a host carrying shell syntax must not pass.+export const isValidDirectHost = (host: string) => {+ if (net.isIP(host)) return true;+ if (host.length > 253) return false;+ const labels = host.replace(TRAILING_DOT_REGEX, "").split(".");+ return labels.length > 0 && labels.every((label) => DNS_LABEL_REGEX.test(label));+};++export const parseDirectAddress = (address: string) => {+ // Never echo the address: it can arrive shaped like a connection string.+ const invalidFormat = () =>+ new BadRequestError({+ message: "Gateway direct address must use the host:port format, such as gateway.internal:8443"+ });++ let parsed: URL;+ try {+ parsed = new URL(`tcp://${address}`);+ } catch {+ throw invalidFormat();+ }++ if (+ !parsed.hostname ||+ !parsed.port ||+ parsed.username ||+ parsed.password ||+ parsed.pathname ||+ parsed.search ||+ parsed.hash+ ) {+ throw invalidFormat();+ }++ const port = Number(parsed.port);+ if (!Number.isInteger(port) || port < 1 || port > 65535) {+ throw new BadRequestError({ message: "Gateway direct address must include a port from 1 to 65535" });+ }++ const host = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;+ if (!isValidDirectHost(host)) {+ throw new BadRequestError({+ message: "Gateway direct address host must be an IP address or a DNS hostname"+ });+ }++ return { host, port };+};diff --git a/backend/src/services/telemetry/telemetry-dal.ts b/backend/src/services/telemetry/telemetry-dal.tsindex 1b5c2e6d05..c0d74225ab 100644--- a/backend/src/services/telemetry/telemetry-dal.ts+++ b/backend/src/services/telemetry/telemetry-dal.ts@@ -1,6 +1,6 @@import { TDbClient } from "@app/db";import { AccessScope, OrgMembershipRole, ProjectMembershipRole, TableName } from "@app/db/schemas";-import { buildGatewayReachableSql } from "@app/ee/services/gateway-v2/gateway-v2-constants";+import { buildGatewayReachableSql } from "@app/ee/services/gateway-v2/gateway-v2-transport-fns";import { DatabaseError } from "@app/lib/errors";const BUILT_IN_ROLE_SLUGS = [...Object.values(OrgMembershipRole), ...Object.values(ProjectMembershipRole)] as string[];