Skip to content

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

fix(gateway): transport-aware health and direct dial fallback

bernie-ge5989f3c2f8a
diff --git a/backend/src/ee/routes/v1/gateway-pool-router.ts b/backend/src/ee/routes/v1/gateway-pool-router.ts
index df243d7ddc..3c411aca22 100644
--- a/backend/src/ee/routes/v1/gateway-pool-router.ts
+++ b/backend/src/ee/routes/v1/gateway-pool-router.ts
@@ -19,7 +19,9 @@ const SanitizedPoolMemberSchema = GatewaysV2Schema.pick({
id: true,
name: true,
heartbeat: true,
- heartbeatTTL: true
+ heartbeatTTL: true,
+ directAddress: true,
+ directHeartbeat: true
});
export const registerGatewayPoolRouter = async (server: FastifyZodProvider) => {
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.ts
index 7a6b553eba..56125f9798 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
@@ -328,6 +328,9 @@ export const registerPamWebAccessRouter = async (server: FastifyZodProvider) =>
.array(z.enum(["relay", "direct"]))
.max(2)
.optional()
+ .describe(
+ "Transports the client can dial. Omit to let the platform choose. A CLI that predates direct connections omits it, so the platform treats an omitted list as relay-only for CLI access."
+ )
}),
response: {
200: z.object({
@@ -383,6 +386,10 @@ 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.
supportedTransports:
req.body.accessMethod === PamAccessMethod.Web ? undefined : (req.body.supportedTransports ?? [])
});
diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.ts
index 4021d2e29a..fc03ff2bf6 100644
--- a/backend/src/ee/routes/v2/gateway-router.ts
+++ b/backend/src/ee/routes/v2/gateway-router.ts
@@ -1,6 +1,7 @@
import z from "zod";
import { GatewaysV2Schema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { GATEWAYS } from "@app/lib/api-docs";
import { zodBuffer } from "@app/lib/zod";
import { gatewayMetricsReportLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";
@@ -8,6 +9,15 @@ import { slugSchema } from "@app/server/lib/schemas";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
+// Derived from what was actually issued rather than what was asked for, so the log records the
+// transports the gateway ended up with.
+const gatewayTransports = ({ directAddress, relayHost }: { directAddress?: string; relayHost?: string }) => {
+ const transports: ("direct" | "relay")[] = [];
+ if (directAddress) transports.push("direct");
+ if (relayHost) transports.push("relay");
+ return transports;
+};
+
const SanitizedGatewayV2Schema = GatewaysV2Schema.pick({
id: true,
identityId: true,
@@ -28,11 +38,15 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
url: "/",
schema: {
operationId: "registerGateway",
- body: z.object({
- relayName: slugSchema({ min: 1, max: 32, field: "relayName" }).optional(),
- directAddress: z.string().trim().min(3).max(255).optional(),
- name: slugSchema({ min: 1, max: 64, field: "name" })
- }),
+ body: z
+ .object({
+ relayName: slugSchema({ min: 1, max: 32, field: "relayName" }).optional(),
+ directAddress: z.string().trim().min(3).max(255).optional(),
+ name: slugSchema({ min: 1, max: 64, field: "name" })
+ })
+ .refine((body) => Boolean(body.relayName || body.directAddress), {
+ message: "Either relayName or directAddress is required"
+ }),
response: {
200: z.object({
gatewayId: z.string(),
@@ -58,7 +72,7 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),
handler: async (req) => {
- return server.services.gatewayV2.registerGateway({
+ const registered = await server.services.gatewayV2.registerGateway({
orgId: req.permission.orgId,
relayName: req.body.relayName,
actorId: req.permission.id,
@@ -67,6 +81,23 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
directAddress: req.body.directAddress,
name: req.body.name
});
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.GATEWAY_ENROLL,
+ metadata: {
+ gatewayId: registered.gatewayId,
+ name: req.body.name,
+ transports: gatewayTransports(registered),
+ directAddress: registered.directAddress,
+ relayName: req.body.relayName
+ }
+ }
+ });
+
+ return registered;
}
});
diff --git a/backend/src/ee/routes/v3/gateway-router.ts b/backend/src/ee/routes/v3/gateway-router.ts
index b81369388d..3fa0f61d10 100644
--- a/backend/src/ee/routes/v3/gateway-router.ts
+++ b/backend/src/ee/routes/v3/gateway-router.ts
@@ -745,13 +745,35 @@ export const registerGatewayV3Router = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.GATEWAY_ACCESS_TOKEN]),
handler: async (req) => {
- return server.services.gatewayV2.connectGateway({
+ const connected = await server.services.gatewayV2.connectGateway({
orgId: req.permission.orgId,
actorId: req.permission.id,
actorType: req.permission.type,
relayName: req.body.relayName,
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.
+ const transports: ("direct" | "relay")[] = [];
+ if (connected.directAddress) transports.push("direct");
+ if (connected.relayHost) transports.push("relay");
+
+ await server.services.auditLog.createAuditLog({
+ orgId: req.permission.orgId,
+ actor: { type: ActorType.GATEWAY, metadata: { gatewayId: connected.gatewayId } },
+ event: {
+ type: EventType.GATEWAY_ENROLL,
+ metadata: {
+ gatewayId: connected.gatewayId,
+ transports,
+ directAddress: connected.directAddress,
+ relayName: req.body.relayName
+ }
+ }
+ });
+
+ return connected;
}
});
};
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index e5ff945d82..663c1369f9 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -6991,7 +6991,13 @@ interface GatewayEnrollEvent {
type: EventType.GATEWAY_ENROLL;
metadata: {
gatewayId: string;
- name: string;
+ // Absent on the connect path, where the gateway authenticates by id and sends no name.
+ 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/gateway-pool/gateway-pool-dal.ts b/backend/src/ee/services/gateway-pool/gateway-pool-dal.ts
index 2ff7108718..bb7a91ed9a 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 { HEARTBEAT_BUFFER_SECONDS } from "../gateway-v2/gateway-v2-constants";
+import { buildGatewayReachableSql } from "../gateway-v2/gateway-v2-constants";
export type TGatewayPoolDALFactory = ReturnType<typeof gatewayPoolDalFactory>;
@@ -14,7 +14,6 @@ export const gatewayPoolDalFactory = (db: TDbClient) => {
const findByOrgIdWithDetails = async (orgId: string) => {
try {
- const effectiveHeartbeat = `CASE WHEN ${TableName.GatewayV2}."directAddress" IS NOT NULL THEN ${TableName.GatewayV2}."directHeartbeat" ELSE ${TableName.GatewayV2}."heartbeat" END`;
const pools = await db
.replicaNode()(TableName.GatewayPool)
.where(`${TableName.GatewayPool}.orgId`, orgId)
@@ -28,7 +27,9 @@ export const gatewayPoolDalFactory = (db: TDbClient) => {
.select(
db.raw(`COUNT(DISTINCT ${TableName.GatewayPoolMembership}."gatewayId") AS "memberCount"`),
db.raw(
- `COUNT(DISTINCT CASE WHEN COALESCE(${TableName.GatewayV2}."heartbeatTTL", 0) > 0 AND ${effectiveHeartbeat} + make_interval(secs => COALESCE(${TableName.GatewayV2}."heartbeatTTL", 0) + ${HEARTBEAT_BUFFER_SECONDS}) > NOW() THEN ${TableName.GatewayPoolMembership}."gatewayId" END) AS "healthyMemberCount"`
+ `COUNT(DISTINCT CASE WHEN ${buildGatewayReachableSql(TableName.GatewayV2)} THEN ${
+ TableName.GatewayPoolMembership
+ }."gatewayId" END) AS "healthyMemberCount"`
),
db.raw(
`COALESCE(array_agg(DISTINCT ${TableName.GatewayPoolMembership}."gatewayId") FILTER (WHERE ${TableName.GatewayPoolMembership}."gatewayId" IS NOT NULL), '{}') AS "memberGatewayIds"`
@@ -69,7 +70,9 @@ export const gatewayPoolDalFactory = (db: TDbClient) => {
`${TableName.GatewayV2}.id`,
`${TableName.GatewayV2}.name`,
`${TableName.GatewayV2}.heartbeat`,
- `${TableName.GatewayV2}.heartbeatTTL`
+ `${TableName.GatewayV2}.heartbeatTTL`,
+ `${TableName.GatewayV2}.directAddress`,
+ `${TableName.GatewayV2}.directHeartbeat`
);
return { ...pool, gateways: members };
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.ts
index 10cfcec6ad..cb44a79892 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 { HEARTBEAT_BUFFER_SECONDS } from "../gateway-v2/gateway-v2-constants";
+import { buildGatewayReachableSql } from "../gateway-v2/gateway-v2-constants";
export type TGatewayPoolMembershipDALFactory = ReturnType<typeof gatewayPoolMembershipDalFactory>;
@@ -12,14 +12,11 @@ export const gatewayPoolMembershipDalFactory = (db: TDbClient) => {
const findHealthyGatewaysByPoolId = async (poolId: string): Promise<TGatewaysV2[]> => {
try {
- const effectiveHeartbeat = `CASE WHEN "${TableName.GatewayV2}"."directAddress" IS NOT NULL THEN "${TableName.GatewayV2}"."directHeartbeat" ELSE "${TableName.GatewayV2}"."heartbeat" END`;
const gateways = await db
.replicaNode()(TableName.GatewayPoolMembership)
.where(`${TableName.GatewayPoolMembership}.gatewayPoolId`, poolId)
.join(TableName.GatewayV2, `${TableName.GatewayPoolMembership}.gatewayId`, `${TableName.GatewayV2}.id`)
- .whereRaw(
- `COALESCE("${TableName.GatewayV2}"."heartbeatTTL", 0) > 0 AND ${effectiveHeartbeat} + make_interval(secs => COALESCE("${TableName.GatewayV2}"."heartbeatTTL", 0) + ${HEARTBEAT_BUFFER_SECONDS}) > NOW()`
- )
+ .whereRaw(buildGatewayReachableSql(TableName.GatewayV2))
.select(`${TableName.GatewayV2}.*`);
return gateways as TGatewaysV2[];
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts b/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts
index 45e7f2d9ac..5d8e1ee6a3 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts
@@ -4,3 +4,72 @@ export const DEFAULT_HEARTBEAT_TTL = 1800; // 30 minutes — fallback for old ga
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.
+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;
+};
+
+// 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.
+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")})))`;
+};
+
+// 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.
+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
+}: {
+ gateway: {
+ directAddress?: string | null;
+ relayId?: string | null;
+ directHeartbeat?: Date | null;
+ heartbeatTTL?: number | null;
+ };
+ 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.
+ 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 };
+};
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-dal.ts b/backend/src/ee/services/gateway-v2/gateway-v2-dal.ts
index 1d0cfc6061..2afa0ae68f 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 { HEARTBEAT_BUFFER_SECONDS } from "./gateway-v2-constants";
+import { buildGatewayProbedSql, buildGatewayReachableSql } from "./gateway-v2-constants";
export type TGatewayV2DALFactory = ReturnType<typeof gatewayV2DalFactory>;
@@ -27,17 +27,8 @@ export const gatewayV2DalFactory = (db: TDbClient) => {
.select(db.ref("name").withSchema(TableName.Identity).as("identityName"));
if (isHeartbeatStale) {
- const effectiveHeartbeat = `CASE WHEN "${TableName.GatewayV2}"."directAddress" IS NOT NULL THEN "${TableName.GatewayV2}"."directHeartbeat" ELSE "${TableName.GatewayV2}"."heartbeat" END`;
- void query.whereRaw(`${effectiveHeartbeat} IS NOT NULL`);
- void query.where((builder) => {
- void builder
- .where(
- db.raw(
- `${effectiveHeartbeat} + make_interval(secs => COALESCE("${TableName.GatewayV2}"."heartbeatTTL", 0) + ${HEARTBEAT_BUFFER_SECONDS}) < NOW()`
- )
- )
- .orWhere(`${TableName.GatewayV2}.heartbeatTTL`, 0);
- });
+ void query.whereRaw(buildGatewayProbedSql(TableName.GatewayV2));
+ void query.whereRaw(`NOT ${buildGatewayReachableSql(TableName.GatewayV2)}`);
// Notification cooldown: only alert if never alerted or last alert was over 1 hour ago
void query.where((v) => {
void v
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
index 7ce9316013..de0ee2ea2e 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -46,7 +46,8 @@ import {
DEFAULT_HEARTBEAT_TTL,
GATEWAY_ACTOR_OID,
GATEWAY_ROUTING_INFO_OID,
- PAM_INFO_OID
+ PAM_INFO_OID,
+ resolveTransports
} from "./gateway-v2-constants";
import { TGatewayV2DALFactory } from "./gateway-v2-dal";
import { TGatewayV2ConnectionDetails } from "./gateway-v2-types";
@@ -390,10 +391,9 @@ export const gatewayV2ServiceFactory = ({
throw new NotFoundError({ message: `Gateway Config for org ${gateway.orgId} not found.` });
}
- const useDirect = transport !== "relay" && Boolean(gateway.directAddress);
- const useRelay = transport === "relay" || !useDirect;
+ const { useDirect, useRelay, hasTransport } = resolveTransports({ gateway, transport });
- if ((transport === "direct" && !gateway.directAddress) || (useRelay && !gateway.relayId)) {
+ if (!hasTransport) {
throw new BadRequestError({
message: `Gateway does not have a ${transport ?? "reachable"} transport configured`
});
@@ -561,8 +561,11 @@ export const gatewayV2ServiceFactory = ({
});
}
if ((!gateway.directAddress || !allowDirect) && (!gateway.relayId || !allowRelay)) {
+ const hasTransport = Boolean(gateway.directAddress || gateway.relayId);
throw new BadRequestError({
- message: "Gateway has no configured connection transport"
+ message: hasTransport
+ ? "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"
});
}
@@ -1026,7 +1029,10 @@ export const gatewayV2ServiceFactory = ({
if (results.every((result) => result.status === "rejected")) {
await gatewayV2DAL.updateById(gatewayId, { heartbeatTTL: 0 });
const failure = results.find((result): result is PromiseRejectedResult => result.status === "rejected");
- throw failure?.reason;
+ if (failure?.reason instanceof Error) throw failure.reason;
+ throw new BadRequestError({
+ message: `Gateway ${gatewayId} is not reachable on any configured transport`
+ });
}
};
@@ -1109,8 +1115,8 @@ export const gatewayV2ServiceFactory = ({
}
// Do not mark the gateway alive here. A load report only proves the gateway can reach us;
- // heartbeat proves we can reach it back through the relay. Updating liveness from this would
- // keep a gateway whose relay path is broken looking healthy.
+ // 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 };
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.ts
new file mode 100644
index 0000000000..e0eade8598
--- /dev/null
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-transport.test.ts
@@ -0,0 +1,125 @@
+import { HEARTBEAT_BUFFER_SECONDS, isTransportHealthy, resolveTransports } from "./gateway-v2-constants";
+
+const secondsAgo = (seconds: number) => new Date(Date.now() - seconds * 1000);
+const TTL = 180;
+const fresh = secondsAgo(TTL - 60);
+const stale = secondsAgo(TTL + HEARTBEAT_BUFFER_SECONDS + 60);
+
+describe("isTransportHealthy", () => {
+ test("a never-probed transport is usable, so a freshly registered gateway is not locked out", () => {
+ expect(isTransportHealthy({ probedAt: null, heartbeatTTL: TTL })).toBe(true);
+ expect(isTransportHealthy({ probedAt: undefined, heartbeatTTL: TTL })).toBe(true);
+ });
+
+ test("a probe inside the TTL window is usable", () => {
+ expect(isTransportHealthy({ probedAt: fresh, heartbeatTTL: TTL })).toBe(true);
+ });
+
+ test("the buffer extends the window, so a probe that is barely late still counts", () => {
+ expect(isTransportHealthy({ probedAt: secondsAgo(TTL + HEARTBEAT_BUFFER_SECONDS - 5), heartbeatTTL: TTL })).toBe(
+ true
+ );
+ });
+
+ test("a probe past the TTL plus buffer is stale", () => {
+ expect(isTransportHealthy({ probedAt: stale, heartbeatTTL: TTL })).toBe(false);
+ });
+
+ test("TTL 0 is the kill switch set when every transport fails, so nothing is usable", () => {
+ expect(isTransportHealthy({ probedAt: new Date(), heartbeatTTL: 0 })).toBe(false);
+ expect(isTransportHealthy({ probedAt: null, heartbeatTTL: 0 })).toBe(false);
+ });
+});
+
+describe("resolveTransports", () => {
+ const direct = { directAddress: "gw.internal:8443", relayId: null, heartbeatTTL: TTL };
+ const relay = { directAddress: null, relayId: "relay-1", heartbeatTTL: TTL };
+ const dual = { directAddress: "gw.internal:8443", relayId: "relay-1", heartbeatTTL: TTL };
+
+ test("a direct-only gateway dials direct", () => {
+ expect(resolveTransports({ gateway: { ...direct, directHeartbeat: fresh } })).toEqual({
+ useDirect: true,
+ useRelay: false,
+ hasTransport: true
+ });
+ });
+
+ test("a direct-only gateway still dials direct on a stale probe, since there is nothing else", () => {
+ expect(resolveTransports({ gateway: { ...direct, directHeartbeat: stale } })).toMatchObject({
+ useDirect: true,
+ hasTransport: true
+ });
+ });
+
+ test("a relay-only gateway dials the relay", () => {
+ expect(resolveTransports({ gateway: { ...relay, directHeartbeat: null } })).toEqual({
+ useDirect: false,
+ useRelay: true,
+ hasTransport: true
+ });
+ });
+
+ test("a gateway with neither transport has nothing to dial", () => {
+ expect(
+ resolveTransports({ gateway: { directAddress: null, relayId: null, heartbeatTTL: null, directHeartbeat: null } })
+ ).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.
+ test("a healthy dual gateway prefers direct but carries relay credentials for the fallback", () => {
+ expect(resolveTransports({ gateway: { ...dual, directHeartbeat: fresh } })).toEqual({
+ useDirect: true,
+ useRelay: true,
+ hasTransport: true
+ });
+ });
+
+ test("a dual gateway whose direct probe went stale drops to the relay", () => {
+ expect(resolveTransports({ gateway: { ...dual, directHeartbeat: stale } })).toEqual({
+ useDirect: false,
+ useRelay: true,
+ hasTransport: true
+ });
+ });
+
+ test("a dual gateway not yet probed on direct still tries it, and keeps the relay in reserve", () => {
+ expect(resolveTransports({ gateway: { ...dual, directHeartbeat: null } })).toEqual({
+ useDirect: true,
+ useRelay: true,
+ hasTransport: true
+ });
+ });
+
+ describe("an explicit transport is honoured, because a health probe has to target one path", () => {
+ test("direct is used even when its own probe is stale", () => {
+ expect(resolveTransports({ gateway: { ...dual, directHeartbeat: stale }, transport: "direct" })).toEqual({
+ useDirect: true,
+ useRelay: false,
+ hasTransport: true
+ });
+ });
+
+ test("relay is used even when direct is healthy", () => {
+ expect(resolveTransports({ gateway: { ...dual, directHeartbeat: fresh }, transport: "relay" })).toEqual({
+ useDirect: false,
+ useRelay: true,
+ hasTransport: true
+ });
+ });
+
+ test("asking for direct on a relay-only gateway leaves nothing to dial", () => {
+ expect(
+ resolveTransports({ gateway: { ...relay, directHeartbeat: null }, transport: "direct" })
+ ).toMatchObject({ useDirect: false, hasTransport: false });
+ });
+ });
+
+ test("the TTL kill switch drops a dual gateway to its relay", () => {
+ expect(resolveTransports({ gateway: { ...dual, directHeartbeat: fresh, heartbeatTTL: 0 } })).toEqual({
+ useDirect: false,
+ useRelay: true,
+ hasTransport: true
+ });
+ });
+});
diff --git a/backend/src/ee/services/pam-session/pam-session-fns.ts b/backend/src/ee/services/pam-session/pam-session-fns.ts
index d3762ffb94..45af707928 100644
--- a/backend/src/ee/services/pam-session/pam-session-fns.ts
+++ b/backend/src/ee/services/pam-session/pam-session-fns.ts
@@ -10,7 +10,13 @@ import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-serv
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { TUserDALFactory } from "@app/services/user/user-dal";
-import { PamAccessMethod, PamAccountType, PamSessionEndReason, PamSessionStatus } from "../pam/pam-enums";
+import {
+ PAM_CANCELLATION_FLUSH_TIMEOUT_MS,
+ PamAccessMethod,
+ PamAccountType,
+ PamSessionEndReason,
+ PamSessionStatus
+} from "../pam/pam-enums";
import { TPamSessionDALFactory } from "./pam-session-dal";
export const LIVE_PAM_SESSION_STATUSES = [PamSessionStatus.Active, PamSessionStatus.Starting];
@@ -122,10 +128,17 @@ 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.
const socket = net.connect(port, "127.0.0.1", () => {
socket.end();
+ });
+ socket.setTimeout(PAM_CANCELLATION_FLUSH_TIMEOUT_MS, () => {
+ socket.destroy();
resolve();
});
+ socket.on("close", () => resolve());
socket.on("error", reject);
}),
{ ...certs, protocol: GatewayProxyProtocol.PamSessionCancellation }
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.ts
index e7b5e44169..7180ae4542 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
@@ -25,7 +25,12 @@ import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
import { TUserDALFactory } from "@app/services/user/user-dal";
-import { PamAccessMethod, PamSessionEndReason, PamSessionStatus } from "../pam/pam-enums";
+import {
+ PAM_CANCELLATION_FLUSH_TIMEOUT_MS,
+ PamAccessMethod,
+ PamSessionEndReason,
+ PamSessionStatus
+} from "../pam/pam-enums";
import { checkAccountAccess } from "../pam/pam-permission";
import { TPamAccessRequestServiceFactory } from "../pam-access-request/pam-access-request-service";
import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
@@ -399,10 +404,17 @@ 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.
const cancelSocket = net.connect(port, "127.0.0.1", () => {
cancelSocket.end();
+ });
+ cancelSocket.setTimeout(PAM_CANCELLATION_FLUSH_TIMEOUT_MS, () => {
+ cancelSocket.destroy();
resolve();
});
+ cancelSocket.on("close", () => resolve());
cancelSocket.on("error", reject);
}),
{ ...certs, protocol: GatewayProxyProtocol.PamSessionCancellation }
diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.ts
index 17409c4d49..0f1819c94b 100644
--- a/backend/src/ee/services/pam/pam-enums.ts
+++ b/backend/src/ee/services/pam/pam-enums.ts
@@ -90,3 +90,7 @@ export enum PamNotificationEvent {
AccessRequestApproved = "access-request-approved",
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.
+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.ts
index d8104eb03c..7b75a77c24 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,13 +168,13 @@ export const resourceAuthMethodServiceFactory = ({
return kmipServer ? { id: kmipServer.id, name: kmipServer.name, orgId: kmipServer.orgId, identityId: null } : null;
};
- // Bumps tokenVersion (invalidating outstanding JWTs) and clears heartbeat. Gateways
- // additionally clear heartbeatTTL; KMIP servers have neither heartbeat column.
+ // Bumps tokenVersion (invalidating outstanding JWTs) and clears every liveness probe, so a
+ // revoked resource cannot keep looking reachable. 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(
resource.id,
- { $incr: { tokenVersion: 1 }, heartbeat: null, heartbeatTTL: null },
+ { $incr: { tokenVersion: 1 }, heartbeat: null, directHeartbeat: null, heartbeatTTL: null },
tx
);
return refreshed.tokenVersion;
diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.ts
index be489212f9..cfa9c3b495 100644
--- a/backend/src/lib/gateway-v2/gateway-v2.ts
+++ b/backend/src/lib/gateway-v2/gateway-v2.ts
@@ -123,13 +123,21 @@ 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 (
relayConn: net.Socket,
gateway: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string },
protocol: GatewayProxyProtocol,
tunnelId?: string,
serverName = "localhost",
- timeoutMs = 120000
+ handshakeTimeoutMs = GATEWAY_IDLE_TIMEOUT_MS
): Promise<net.Socket> => {
const appCfg = getConfig();
@@ -175,6 +183,11 @@ 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.
+ gatewaySocket.setTimeout(GATEWAY_IDLE_TIMEOUT_MS);
+
logger.info(`Gateway mTLS connection established successfully [tunnelId=${tunnelId ?? "n/a"}]`);
resolve(gatewaySocket);
});
@@ -184,7 +197,7 @@ export const createGatewayConnection = async (
reject(new Error(`Failed to establish gateway mTLS: ${err.message}`));
});
- gatewaySocket.setTimeout(timeoutMs);
+ gatewaySocket.setTimeout(handshakeTimeoutMs);
gatewaySocket.on("timeout", () => {
destroyGatewayTunnel({ gatewayConn: gatewaySocket, tunnelId, trigger: "gatewayTimeout" });
reject(new Error("Gateway connection timeout"));
@@ -241,52 +254,75 @@ export const setupRelayServer = async ({
const openUpstream = async (): Promise<TUpstream> => {
const tunnelId = crypto.randomBytes(4).toString("hex");
- let relayConn: net.Socket;
- let gatewayServerName = "localhost";
- try {
- if (directAddress) {
- const parsed = new URL(`tcp://${directAddress}`);
- gatewayServerName = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;
- const [targetHost] = await verifyHostInputValidity({
- host: gatewayServerName,
- isGateway: true,
- isDynamicSecret: false
- });
- relayConn = net.connect({ host: targetHost, port: Number(parsed.port) });
- } else {
- if (!relayHost || !relay) throw new Error("Gateway has no reachable transport");
- relayConn = await createRelayConnection({
- relayHost,
- clientCertificate: relay.clientCertificate,
- clientPrivateKey: relay.clientPrivateKey,
- serverCertificateChain: relay.serverCertificateChain,
- tunnelId
- });
+ const hasRelayFallback = Boolean(directAddress && relayHost && relay);
+
+ const dialDirect = async () => {
+ const parsed = new URL(`tcp://${directAddress}`);
+ const serverName = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;
+ const [targetHost] = await verifyHostInputValidity({
+ host: serverName,
+ isGateway: true,
+ isDynamicSecret: false
+ });
+ return { conn: net.connect({ host: targetHost, port: Number(parsed.port) }), serverName, direct: true };
+ };
+
+ const dialRelay = async () => {
+ if (!relayHost || !relay) throw new Error("Gateway has no reachable transport");
+ const conn = await createRelayConnection({
+ relayHost,
+ clientCertificate: relay.clientCertificate,
+ clientPrivateKey: relay.clientPrivateKey,
+ serverCertificateChain: relay.serverCertificateChain,
+ tunnelId
+ });
+ 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.
+ const openOverTransport = async (
+ dial: () => Promise<{ conn: net.Socket; serverName: string; direct: boolean }>
+ ) => {
+ const { conn, serverName, direct } = await dial();
+ try {
+ const gwConn = await createGatewayConnection(
+ conn,
+ gateway,
+ protocol,
+ tunnelId,
+ serverName,
+ direct ? DIRECT_HANDSHAKE_TIMEOUT_MS : undefined
+ );
+ return { relayConn: conn, gatewayConn: gwConn };
+ } catch (err) {
+ destroyGatewayTunnel({ relayConn: conn, tunnelId, trigger: "gatewayHandshakeFailed" });
+ throw err;
}
- } catch (err) {
- tunnelLog(
- tunnelId,
- directAddress ? "direct connect failed" : "relay connect failed",
- ` [err=${err instanceof Error ? err.message : String(err)}]`
- );
- throw err;
- }
+ };
+ let relayConn: net.Socket;
let gatewayConn: net.Socket;
try {
- // Stage 2: Establish mTLS connection to gateway through the relay
- gatewayConn = await createGatewayConnection(
- relayConn,
- gateway,
- protocol,
- tunnelId,
- gatewayServerName,
- directAddress ? 3000 : undefined
- );
+ ({ relayConn, gatewayConn } = await openOverTransport(directAddress ? dialDirect : dialRelay));
} catch (err) {
- tunnelLog(tunnelId, "gateway mTLS failed", ` [err=${err instanceof Error ? err.message : String(err)}]`);
- destroyGatewayTunnel({ relayConn, tunnelId, trigger: "gatewayHandshakeFailed" });
- throw err;
+ const reason = err instanceof Error ? err.message : String(err);
+ 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));
+ } catch (relayErr) {
+ tunnelLog(
+ tunnelId,
+ "relay fallback failed",
+ ` [err=${relayErr instanceof Error ? relayErr.message : String(relayErr)}]`
+ );
+ throw relayErr;
+ }
}
relayConn.on("close", (hadError: boolean) => tunnelLog(tunnelId, "relay socket close", ` [hadError=${hadError}]`));
@@ -302,8 +338,8 @@ export const setupRelayServer = async ({
markAttemptTunnelEstablished();
if (longLived) {
- // Disable the 30s idle-activity timeout that was set during connection establishment.
- // Without this, the socket is destroyed after 30s of no data, killing idle sessions.
+ // Drop the inactivity timeout applied after the handshake. Without this, an idle session is
+ // destroyed once it goes quiet for GATEWAY_IDLE_TIMEOUT_MS.
relayConn.setTimeout(0);
gatewayConn.setTimeout(0);
diff --git a/backend/src/services/telemetry/telemetry-dal.ts b/backend/src/services/telemetry/telemetry-dal.ts
index 9a4d43affb..1b5c2e6d05 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 { HEARTBEAT_BUFFER_SECONDS } from "@app/ee/services/gateway-v2/gateway-v2-constants";
+import { buildGatewayReachableSql } from "@app/ee/services/gateway-v2/gateway-v2-constants";
import { DatabaseError } from "@app/lib/errors";
const BUILT_IN_ROLE_SLUGS = [...Object.values(OrgMembershipRole), ...Object.values(ProjectMembershipRole)] as string[];
@@ -169,13 +169,7 @@ export const telemetryDALFactory = (db: TDbClient) => {
)?.count as string;
const v2ActiveResult = (
- await db(TableName.GatewayV2)
- .whereNotNull("heartbeat")
- .whereRaw(
- `COALESCE("heartbeatTTL", 0) > 0 AND "heartbeat" + make_interval(secs => COALESCE("heartbeatTTL", 0) + ${HEARTBEAT_BUFFER_SECONDS}) > NOW()`
- )
- .count()
- .first()
+ await db(TableName.GatewayV2).whereRaw(buildGatewayReachableSql(TableName.GatewayV2)).count().first()
)?.count as string;
const activeGateways = parseInt(legacyActiveResult || "0", 10) + parseInt(v2ActiveResult || "0", 10);
diff --git a/docs/cli/commands/gateway.mdx b/docs/cli/commands/gateway.mdx
index 7e2b185cbe..59142992f8 100644
--- a/docs/cli/commands/gateway.mdx
+++ b/docs/cli/commands/gateway.mdx
@@ -18,9 +18,14 @@ description: "Run the Infisical gateway or manage its systemd service"
## Description
-The Infisical gateway provides secure access to private resources using modern TCP-based SSH tunnel architecture with enhanced security and flexible deployment options.
+The Infisical gateway gives the platform access to resources in your private network without handing out their credentials.
-The gateway system uses SSH reverse tunnels over TCP, eliminating firewall complexity and providing excellent performance for enterprise environments.
+There are two ways the gateway and Infisical reach each other:
+
+- **Direct listen.** The gateway listens on an address you register with `--listen-address`, and Infisical connects to it. No relay is needed. Self-hosted Infisical only.
+- **Relay.** The gateway opens an SSH reverse tunnel to a relay server, and Infisical reaches it back through that tunnel. No inbound ports have to be open on the gateway host.
+
+Passing `--listen-address` and `--relay` together runs both, and Infisical uses the direct address first, keeping the relay as a fallback. See [Network architecture](/documentation/platform/gateways/network-architecture) for the ports and traffic flow of each.
## Subcommands & flags
@@ -35,16 +40,25 @@ infisical gateway start <gateway-name> --enroll-method=token --token=<enrollment
The gateway name is provided as a positional argument.
<Info>
- By default, the gateway automatically connects to the relay with the lowest latency. To target a specific relay, use the `--target-relay-name=<relay-name>` flag.
+ With no `--listen-address` and no `--relay`, the gateway connects to the relay with the lowest latency. To target a specific relay, use `--relay=<relay-name>`. To skip relays entirely, use `--listen-address=<host:port>`.
</Info>
Once started, the gateway component will:
-- Automatically connect to a healthy relay with the lowest latency (unless the `--target-relay-name` flag is specified)
-- Establish outbound SSH reverse tunnel to relay server (no inbound firewall rules needed)
-- Authenticate using SSH certificates issued by Infisical
-- Automatically reconnect if the connection is lost, and fail over to a different healthy relay if the current one becomes unreachable
+- Authenticate using certificates issued by Infisical
- Provide access to private resources within your network
+- Automatically renew its certificates
+
+In relay mode it also:
+
+- Connects to a healthy relay with the lowest latency, unless `--relay` names one
+- Establishes an outbound SSH reverse tunnel to the relay, so no inbound firewall rules are needed
+- Reconnects if the connection is lost, and fails over to a different healthy relay if the current one becomes unreachable
+
+In direct listen mode it also:
+
+- Binds the port from `--listen-address` on every interface, unless `--bind` says otherwise
+- Accepts mutually authenticated TLS connections from Infisical on that port
### Flags
@@ -120,17 +134,61 @@ Once started, the gateway component will:
</Accordion>
- <Accordion title="--target-relay-name">
+ <Accordion title="--relay">
The name of the relay that this gateway should connect to. The relay must be running and registered before starting the gateway.
- If this flag is omitted, the gateway will automatically connect to a healthy relay with the lowest latency.
+ If this flag is omitted and no `--listen-address` is set, the gateway connects to a healthy relay with the lowest latency.
```bash
# Example
- infisical gateway start my-gateway --target-relay-name=my-relay --enroll-method=token --token=<token> --domain=<domain>
+ infisical gateway start my-gateway --relay=my-relay --enroll-method=token --token=<token> --domain=<domain>
```
- **Note:** For Infisical Cloud users using instance relays, the relay infrastructure is already running and managed by Infisical. If using organization relays or self-hosted instance relays, you must first start a relay server. For more information on deploying relays, refer to the [Relay Deployment Guide](/documentation/platform/gateways/relay-deployment).
+ Can also be set with the `INFISICAL_RELAY_NAME` environment variable.
+
+ For Infisical Cloud users on instance relays, the relay infrastructure is already running and managed by Infisical. If using organization relays or self-hosted instance relays, start a relay server first. See the [Relay Deployment Guide](/documentation/platform/gateways/relay-deployment).
+
+ <Note>
+ This flag was previously named `--target-relay-name`, which still works but is deprecated. An Infisical CLI older than the release that added `--relay` accepts only the old name, so a deploy command copied from a newer UI fails on it with an unknown flag error. Upgrade the CLI on the host.
+ </Note>
+
+ </Accordion>
+
+ <Accordion title="--listen-address">
+ The `host:port` address that Infisical dials to reach this gateway. Setting it runs the gateway in direct listen mode, where Infisical opens the connection and no relay is involved.
+
+ The address has to be reachable from wherever Infisical runs, and it's written into the gateway's server certificate, so it has to be stable. An internal DNS name or a load balancer in front of the gateway both work. Changing it means re-running the command so a certificate is issued for the new address.
+
+ ```bash
+ # Example
+ 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:
+
+ ```bash
+ infisical gateway start my-gateway --listen-address=gateway.internal:8443 --relay=my-relay --enroll-method=token --token=<token> --domain=<domain>
+ ```
+
+ Can also be set with the `INFISICAL_GATEWAY_LISTEN_ADDRESS` environment variable.
+
+ <Note>
+ Direct listen is available on self-hosted Infisical. On Infisical Cloud, use `--relay` or omit both flags.
+ </Note>
+
+ </Accordion>
+
+ <Accordion title="--bind">
+ The local `host:port` the gateway binds for direct connections. Defaults to every interface on the port from `--listen-address`, so you only need this flag when the address Infisical dials differs from the socket the gateway should open.
+
+ Reach for it to bind a single interface, or to listen on a different local port than the one advertised, such as behind a load balancer that terminates on 8443 and forwards to 9000.
+
+ ```bash
+ # Advertise 8443, listen locally on 9000
+ infisical gateway start my-gateway --listen-address=gateway.internal:8443 --bind=0.0.0.0:9000 --enroll-method=token --token=<token> --domain=<domain>
+ ```
+
+ Can also be set with the `INFISICAL_GATEWAY_BIND_ADDRESS` environment variable. Has no effect without `--listen-address`.
</Accordion>
@@ -208,17 +266,43 @@ sudo infisical gateway systemd install my-gateway --enroll-method=token --token=
</Accordion>
- <Accordion title="--target-relay-name">
+ <Accordion title="--relay">
The name of the relay that this gateway should connect to. The relay must be running and registered before starting the gateway.
- If this flag is omitted, the gateway will automatically connect to a healthy relay with the lowest latency.
+ If this flag is omitted and no `--listen-address` is set, the gateway connects to a healthy relay with the lowest latency.
+
+ ```bash
+ # Example
+ sudo infisical gateway systemd install my-gateway --relay=my-relay --enroll-method=token --token=<token> --domain=<domain>
+ ```
+
+ For Infisical Cloud users on instance relays, the relay infrastructure is already running and managed by Infisical. If using organization relays or self-hosted instance relays, start a relay server first. See the [Relay Deployment Guide](/documentation/platform/gateways/relay-deployment).
+
+ <Note>
+ This flag was previously named `--target-relay-name`, which still works but is deprecated.
+ </Note>
+
+ </Accordion>
+
+ <Accordion title="--listen-address">
+ The `host:port` address that Infisical dials to reach this gateway, which runs it in direct listen mode. The systemd unit captures the flag, so every restart advertises the same address.
```bash
# Example
- sudo infisical gateway systemd install my-gateway --target-relay-name=my-relay --enroll-method=token --token=<token> --domain=<domain>
+ sudo infisical gateway systemd install my-gateway --listen-address=gateway.internal:8443 --enroll-method=token --token=<token> --domain=<domain>
```
- **Note:** For Infisical Cloud users using instance relays, the relay infrastructure is already running and managed by Infisical. If using organization relays or self-hosted instance relays, you must first start a relay server. For more information on deploying relays, refer to the [Relay Deployment Guide](/documentation/platform/gateways/relay-deployment).
+ Pass it alongside `--relay` to run both modes. See the `infisical gateway start` reference above for what the address has to satisfy.
+
+ </Accordion>
+
+ <Accordion title="--bind">
+ The local `host:port` the gateway binds for direct connections. Defaults to every interface on the port from `--listen-address`.
+
+ ```bash
+ # Example
+ sudo infisical gateway systemd install my-gateway --listen-address=gateway.internal:8443 --bind=0.0.0.0:9000 --enroll-method=token --token=<token> --domain=<domain>
+ ```
</Accordion>
@@ -279,9 +363,17 @@ The gateway name is provided as a positional argument.
Yes. The CLI stores the enrollment token locally after the first successful enrollment. If you run the same command again with the same `--token` value, it detects the token has already been used and skips enrollment, proceeding directly to start the gateway. This means you can safely use the same command (e.g., via up-arrow in your shell) without getting "token already used" or "token expired" errors.
</Accordion>
<Accordion title="How are relays auto-selected?">
- If the `--target-relay-name` flag is omitted, the gateway automatically selects the optimal relay. It first checks for healthy organization relays and connects to the one with the lowest latency. If no organization relays are available, it then performs the same latency-based selection among the available managed relays.
+ If `--relay` and `--listen-address` are both omitted, the gateway automatically selects the optimal relay. It first checks for healthy organization relays and connects to the one with the lowest latency. If no organization relays are available, it then performs the same latency-based selection among the available managed relays.
+
+ If the selected relay becomes unreachable while the gateway is running, the gateway will automatically switch to a different healthy one. Gateways started with an explicit `--relay` do not switch and will keep retrying the specified relay.
+ </Accordion>
+ <Accordion title="Which mode do I get if I pass no connection flags?">
+ Relay mode, with a relay chosen automatically. Direct listen is opt-in: the gateway only listens for connections when you pass `--listen-address`.
+ </Accordion>
+ <Accordion title="Do PAM sessions work in direct listen mode?">
+ Browser-based sessions work in either mode, because the platform brokers the connection.
- If the selected relay becomes unreachable while the gateway is running, the gateway will automatically switch to a different healthy one. Gateways started with an explicit `--target-relay-name` do not switch and will keep retrying the specified relay.
+ `infisical pam access` connects to the gateway from your own machine instead, so it needs to reach the gateway's registered address. From a laptop outside the gateway's network that means a VPN into the network, or a relay running on the gateway alongside direct listen.
</Accordion>
<Accordion title="When restarting the gateway without a relay flag, does it select a new relay every time?">
No. The first time the gateway starts, it selects the optimal relay (based on latency) and caches that selection. On subsequent restarts, it will prioritize connecting to the cached relay. If it's unable to connect, it will then re-evaluate and connect to the next most optimal relay available.
diff --git a/docs/cli/commands/pam.mdx b/docs/cli/commands/pam.mdx
index 30ac62ada9..259f6b0d0c 100644
--- a/docs/cli/commands/pam.mdx
+++ b/docs/cli/commands/pam.mdx
@@ -11,6 +11,8 @@ infisical pam access <path> [flags] [-- <command>]
Open one PAM-managed account for your own use, brokered through Infisical's [Gateway](/documentation/platform/gateways/overview) so you never handle its credentials. Requires `infisical login`.
+The CLI connects to the gateway from your own machine, so you need a network path to it. A gateway in [relay mode](/documentation/platform/gateways/network-architecture) works from anywhere, because the relay is reachable from outside your network. A gateway in direct listen mode only works from a machine that can reach its registered address, so from outside that network you'll need a VPN into it, or a relay on the gateway.
+
This single command handles every account type: the CLI adapts its behavior to whichever type the account's template defines (see [Account Types and Behavior](#account-types-and-behavior) below).
SSH accounts connect you directly to a shell on the target. Every other account type starts a local proxy or credential helper that you point your own client at.
@@ -298,4 +300,6 @@ infisical pam access production/database --reason "Investigating incident INC-12
| `Invalid duration format` | Malformed `--duration` value | Use formats like `1h`, `30m`, `2h30m` |
| `a reason is required to access this account` | Policy requires reason, no TTY | Pass `--reason` flag |
| `Gateway does not support '{type}' PAM accounts` | Gateway version too old | Upgrade Infisical Gateway |
+| `direct gateway connection failed and no relay fallback is available` | The gateway only listens directly, and your machine can't reach its address | Connect from the gateway's network or over a VPN, or ask an admin to add a relay to the gateway |
+| `This gateway only supports direct connections. Upgrade the Infisical CLI to connect to it.` | CLI too old to use a direct listen gateway | Upgrade the Infisical CLI |
| `PAM response metadata is missing` | API response incomplete | Contact support |
diff --git a/docs/contributing/platform/pam-development.mdx b/docs/contributing/platform/pam-development.mdx
index 6da8a1a322..84e93e0b79 100644
--- a/docs/contributing/platform/pam-development.mdx
+++ b/docs/contributing/platform/pam-development.mdx
@@ -92,7 +92,7 @@ In a new terminal, from the CLI repository root:
go run main.go gateway start \
--token=<your-token> \
--domain=http://localhost:8080 \
- --target-relay-name=local-relay \
+ --relay=local-relay \
--name=local-gateway \
--pam-session-recording-path=$(pwd)/session
```
@@ -106,7 +106,7 @@ For all available flags, see the [Gateway CLI Reference](/cli/commands/gateway).
| Component | Command |
|-----------|---------|
| Relay | `go run main.go relay start --name=local-relay --token=<token> --domain=http://localhost:8080 --host=host.docker.internal` |
-| Gateway | `go run main.go gateway start --token=<token> --domain=http://localhost:8080 --target-relay-name=local-relay --name=local-gateway --pam-session-recording-path=$(pwd)/session` |
+| Gateway | `go run main.go gateway start --token=<token> --domain=http://localhost:8080 --relay=local-relay --name=local-gateway --pam-session-recording-path=$(pwd)/session` |
## Seed test resources
@@ -158,7 +158,7 @@ docker compose -f docker-compose.dev.yml logs -f backend
<Accordion title="Gateway cannot connect to relay">
- Verify relay is running and registered in the UI
-- Check `--target-relay-name` matches relay's `--name`
+- Check `--relay` matches relay's `--name`
- Ensure port 2222 isn't blocked
</Accordion>
diff --git a/docs/documentation/platform/gateways/gateway-deployment.mdx b/docs/documentation/platform/gateways/gateway-deployment.mdx
index e44fe4dcf9..4c70e96ac5 100644
--- a/docs/documentation/platform/gateways/gateway-deployment.mdx
+++ b/docs/documentation/platform/gateways/gateway-deployment.mdx
@@ -3,23 +3,46 @@ title: "Gateway deployment"
description: "Complete guide to deploying Infisical Gateways including network configuration and firewall requirements"
---
-Infisical Gateways enables secure communication between your private resources and the Infisical platform without exposing inbound ports in your network.
+Infisical Gateways give the platform access to resources in your private network, such as databases and internal APIs, without handing out their credentials.
This guide covers everything you need to deploy and configure Infisical Gateways.
<Tip>
For a complete Helm chart reference for Kubernetes deployments, see the [Gateway Helm chart documentation](/self-hosting/helm-charts/gateway).
</Tip>
+## 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.
+
+| | Direct listen | Relay |
+|---|---|---|
+| Who connects | Infisical connects to the Gateway | The Gateway connects out to a relay |
+| Firewall | Inbound port open to the Infisical host | Outbound only |
+| Relay required | No | Yes |
+| Needs a stable Gateway address | Yes | No |
+| PAM CLI from outside the network | No | Yes |
+| Infisical Cloud | Not available | Yes |
+
+**Use direct listen** when Infisical can already reach the Gateway host at a stable address. This is the common case when you self-host Infisical in the same network as your resources, and it means there's no relay to deploy or operate.
+
+**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.
+
+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.
+
+For the ports, certificates, and traffic flow behind each mode, see [Network architecture](/documentation/platform/gateways/network-architecture).
+
## Deployment steps
<Steps>
- <Step title="Set Up a Relay Server">
- Ensure a relay server is running and accessible before you deploy any gateways. You have two options:
+ <Step title="Set up a relay server (relay mode only)">
+ Skip this step if you're using direct listen.
+
+ For relay mode, a relay server has to be running and reachable before you deploy any gateways. You have two options:
- **Managed relay (Infisical Cloud, US/EU only):** If you're using Infisical Cloud in the US or EU regions, you can use the provided managed relay.
- - **Self-hosted relay:** For all other cases, you must deploy your own relay server. See the [Relay Deployment Guide](/documentation/platform/gateways/relay-deployment).
+ - **Self-hosted relay:** For all other cases, deploy your own relay server. See the [Relay Deployment Guide](/documentation/platform/gateways/relay-deployment).
</Step>
- <Step title="Create the Gateway in the UI">
- 1. Navigate to **Organization Settings > Networking > Gateways**.
+ <Step title="Create the gateway in the UI">
+ 1. Go to **Organization Settings > Networking > Gateways**.
2. Select **Create Gateway**.
![Create Gateway button](/images/platform/gateways/gateway-create-button.png)
3. Enter a name for the gateway, then select **Create Gateway**.
@@ -28,13 +51,19 @@ This guide covers everything you need to deploy and configure Infisical Gateways
- **Token** (default): a one-time enrollment token (1h expiry) bootstraps the gateway.
- **AWS**: the gateway authenticates by signing an `sts:GetCallerIdentity` request with whatever AWS credentials it can resolve on the host (instance role, env vars, shared profile). Configure the allowed principal ARNs and/or account IDs that match your hosts.
- **Kubernetes**: the gateway authenticates with the projected service account token of the pod it runs in, so no credential has to be distributed to the cluster. Configure the cluster's API server URL and the allowed namespaces and/or service account names.
- 5. Select **Show deploy command** in the **Deployment** card. Pick a relay (or "Auto Select Relay") and copy the generated CLI command.
+ 5. Select **Show deploy command** in the **Deployment** card.
+ 6. Under **Connection Mode**, select **Direct Listen** or **Relay**.
+ - For **Direct Listen**, enter the **Listen Address** that Infisical will dial, as `host:port`.
+ - For **Relay**, pick a relay, or leave **Auto Select Relay** so the gateway chooses the healthiest one.
+ 7. Copy the generated CLI command.
</Step>
<Step title="Install the Infisical CLI">
Make sure the Infisical CLI is installed on the target machine. See the [CLI Installation Guide](/cli/overview) for instructions.
</Step>
- <Step title="Configure Network & Firewall">
- Ensure your network and firewall settings allow the gateway to connect to all required services. All connections are outbound only; no inbound ports need to be opened.
+ <Step title="Configure network and firewall">
+ What you open depends on the connection mode you chose.
+
+ **Relay mode.** All connections are outbound, so no inbound ports need to be opened.
| Protocol | Destination | Port | Purpose |
| -------- | ------------------------------------ | ---- | ------------------------------------------ |
@@ -45,13 +74,58 @@ This guide covers everything you need to deploy and configure Infisical Gateways
If you're in a corporate environment with strict egress filtering, ensure outbound TCP 2222 to relay servers and outbound HTTPS 443 to Infisical API endpoints are allowed.
+ **Direct listen mode.** The Gateway accepts inbound connections, so one port has to be open to Infisical.
+
+ | Protocol | Direction | Source or destination | Port | Purpose |
+ | -------- | --------- | --------------------- | ---- | ------- |
+ | TCP | Inbound | Infisical instance host | the port in your listen address | Platform connects to the gateway |
+ | TCP | Outbound | Infisical instance host | 443 | API communication and certificate requests |
+
+ Scope the inbound rule to the Infisical instance host rather than opening the port broadly.
+
<Tip>
For the full connection model, a complete port reference, and firewall details (including self-hosted relays and HTTP forward proxies), see the [Network Architecture](/documentation/platform/gateways/network-architecture) page.
</Tip>
</Step>
- <Step title="Run the CLI Command">
+ <Step title="Run the CLI command">
Run the command you copied from the UI on the target machine. This single command enrolls the gateway and starts it immediately.
+ The examples below are grouped by authentication method. The connection mode is set by two flags, which you can add to any of them:
+
+ - `--listen-address=<host:port>` for direct listen, where `host:port` is the address Infisical dials
+ - `--relay=<relay-name>` to pin a relay, or omit it to let the gateway pick the healthiest one
+
+ Passing both runs the gateway in both modes.
+
+ ```bash
+ # Direct listen
+ infisical gateway start my-gateway \
+ --listen-address=gateway.internal:8443 \
+ --enroll-method=token \
+ --token=<enrollment-token> \
+ --domain=<your-infisical-domain>
+
+ # Both modes
+ infisical gateway start my-gateway \
+ --listen-address=gateway.internal:8443 \
+ --relay=my-relay \
+ --enroll-method=token \
+ --token=<enrollment-token> \
+ --domain=<your-infisical-domain>
+ ```
+
+ For Kubernetes, set `gateway.listenAddress` to the address Infisical dials:
+
+ ```bash
+ helm install infisical-gateway infisical/infisical-gateway \
+ --set gateway.name=my-gateway \
+ --set gateway.listenAddress=infisical-gateway.default.svc.cluster.local:8443 \
+ --set service.port=8443 \
+ --set gateway.enrollment.method=token \
+ --set gateway.enrollment.token.existingSecretRef=gateway-enrollment-token \
+ --set gateway.domain=<your-infisical-domain>
+ ```
+
<AccordionGroup>
<Accordion title="Token Auth">
A one-time enrollment token (1h expiry) bootstraps the gateway.
@@ -245,10 +319,10 @@ This guide covers everything you need to deploy and configure Infisical Gateways
You can safely re-run the same command to restart the gateway. The CLI detects the token has already been used locally and skips enrollment automatically.
</Info>
</Step>
- <Step title="Verify Your Gateway Deployment">
+ <Step title="Verify your gateway deployment">
After deployment, verify your gateway is working:
- 1. **Check logs** for "Gateway started successfully" message.
- 2. **Verify registration** in the Infisical UI. Navigate to **Networking > Gateways** and confirm the gateway shows a "Healthy" status.
+ 1. **Check logs** for the "Gateway started successfully" message. In direct listen mode you'll also see "Direct gateway listener started" with the address it's advertising and the port it bound.
+ 2. **Verify registration** in the Infisical UI. Go to **Networking > Gateways** and confirm the gateway shows a **Healthy** status. A gateway running both modes stays healthy while either one works.
3. **Test connectivity** by creating a resource that uses the gateway to access a private service.
</Step>
</Steps>
@@ -268,13 +342,38 @@ To migrate a gateway to a different host with zero downtime: select **Show deplo
<AccordionGroup>
<Accordion title="Do I need to open any inbound ports on my firewall?">
-No inbound ports need to be opened for gateways. The gateway only makes outbound connections:
+That depends on the connection mode.
+
+In relay mode, no. The gateway only makes outbound connections:
- **Outbound SSH** to relay servers on port 2222
- **Outbound HTTPS** to Infisical API endpoints on port 443
-- **SSH reverse tunnels** handle all communication - no return traffic configuration needed
+- **SSH reverse tunnels** carry all return traffic, so nothing needs to be configured for it
-This design maintains security by avoiding the need for inbound firewall rules that could expose your network to external threats.
+In direct listen mode, one inbound port has to be open: the port in your listen address, reachable from the Infisical instance host. Scope the rule to that host so the port isn't open to anything else.
+
+</Accordion>
+
+<Accordion title="Can I switch a gateway between relay and direct listen?">
+Yes. Open the gateway's detail page, select **Show deploy command**, choose the mode you want, and re-run the generated command on the host. The gateway re-registers with the new mode and is issued the certificate it needs for it.
+
+Switching away from a mode drops it. To keep both, pass `--relay` and `--listen-address` together.
+
+</Accordion>
+
+<Accordion title="Why does my direct listen gateway fail to register?">
+The listen address has to be `host:port`, with a port in the range 1 to 65535. An address with no port is rejected, and so is one that includes a scheme or a path, so use `gateway.internal:8443` rather than `https://gateway.internal` or `gateway.internal`.
+
+Direct listen is also unavailable on Infisical Cloud. On Cloud, use relay mode.
+
+</Accordion>
+
+<Accordion title="Do PAM CLI sessions work with direct listen?">
+Only from a machine that can reach the gateway's registered address. The CLI connects to the gateway from the user's own machine rather than through Infisical, so a laptop outside the network can't reach a gateway listening on an internal address. Give those users a VPN into the network, or run a relay on the gateway alongside direct listen.
+
+Browser-based PAM access works in either mode, because the platform brokers that connection.
+
+Using direct listen also requires a current Infisical CLI. An older CLI can't connect to a gateway that only listens directly, and reports that the gateway needs a newer CLI.
</Accordion>
@@ -303,6 +402,20 @@ If the gateway can't connect to the relay:
```
</Accordion>
+<Accordion title="How do I troubleshoot direct listen connectivity issues?">
+The gateway registers and looks healthy only once Infisical can reach it, so start from the Infisical host:
+
+1. Confirm the gateway logged "Direct gateway listener started" and check the port it bound
+2. From the Infisical instance host, test the registered address:
+ ```bash
+ nc -zv gateway.internal 8443
+ ```
+3. Check the inbound firewall rule allows the Infisical instance host on that port
+4. Confirm the registered address resolves from the Infisical host, not just from your own machine
+
+If the gateway binds a different local port than the one you advertise, such as behind a load balancer, pass `--bind` to set the local address and keep `--listen-address` as the address Infisical dials.
+</Accordion>
+
<Accordion title="How do I troubleshoot authentication failures?">
For token method: ensure the enrollment token hasn't expired or already been used. Open the gateway's detail page and select **Show deploy command** to generate a fresh token.
@@ -344,6 +457,7 @@ Yes. Each gateway stores its credentials in a separate config file scoped by nam
The gateway is designed to handle network interruptions gracefully:
- **Automatic reconnection**: The gateway will automatically attempt to reconnect to relay servers if the SSH connection is lost
+- **Transport fallback**: A gateway running both modes falls back to its relay when its direct address stops answering, and returns to direct connections once it recovers
- **Connection retry logic**: Built-in retry mechanisms handle temporary network outages without manual intervention
- **Automatic failover**: Gateways configured with automatic relay selection will switch to a different healthy relay if the current one becomes unreachable
- **Gateway Pools**: If the gateway itself becomes unavailable, a [Gateway Pool](/documentation/platform/gateways/gateway-pools) will automatically route through a healthy member
diff --git a/docs/documentation/platform/gateways/network-architecture.mdx b/docs/documentation/platform/gateways/network-architecture.mdx
index a28ffa9819..d0aa25cc6b 100644
--- a/docs/documentation/platform/gateways/network-architecture.mdx
+++ b/docs/documentation/platform/gateways/network-architecture.mdx
@@ -1,12 +1,23 @@
---
title: "Network architecture"
sidebarTitle: "Network architecture"
-description: "Ports, egress requirements, and the relay tunnel that connect the Gateway to Infisical"
+description: "Ports, egress requirements, and the two ways the Gateway and Infisical connect"
---
-The Gateway is deployed inside your private network and makes **only outbound connections** — it never accepts inbound connections. It reaches Infisical through a [**relay server**](/documentation/platform/gateways/relay-deployment/overview) using an **SSH reverse tunnel over TCP**, so the platform can access your private resources (databases, internal APIs) without any inbound firewall rules. All traffic through the relay is double-encrypted, and the relay only routes traffic — it can't decrypt it.
+The Gateway is deployed inside your private network, alongside the resources it protects. Infisical never touches those resources directly. It sends every request through the Gateway, which forwards it to the database or internal API on the other side.
-## Connection model
+There are two ways the Gateway and Infisical reach each other, and they differ in one thing: which side opens the connection.
+
+- **Relay mode.** The Gateway dials out to a [relay server](/documentation/platform/gateways/relay-deployment/overview) and keeps that tunnel open. Infisical connects to the relay, and its requests travel back down the tunnel the Gateway already established. The Gateway accepts no inbound connections, so your firewall needs no inbound rules.
+- **Direct listen mode.** The Gateway listens on an address you register, and Infisical connects to it. There's no relay to deploy, but the address has to be reachable from wherever Infisical runs.
+
+Both modes carry the same mutually authenticated TLS between Infisical and the Gateway, with certificates issued by your organization's own certificate authorities. In relay mode the relay routes bytes without holding the keys to read them.
+
+<Info>
+ Direct listen is available on self-hosted Infisical. On Infisical Cloud, gateways use relay mode.
+</Info>
+
+## Relay mode
```mermaid
%%{init: {'flowchart': {'nodeSpacing': 70, 'rankSpacing': 110, 'curve': 'basis'}}}%%
@@ -24,16 +35,12 @@ flowchart LR
PLAT -->|"TCP 8443 · TLS"| RELAY
```
-## Ports and connections
-
| Connection | Source | Destination | Port | Protocol | Purpose |
|---|---|---|---|---|---|
-| Relay tunnel | Gateway | Relay server | 2222 | TCP (SSH) | Establishes the SSH reverse tunnel — **egress** |
-| Infisical API | Gateway | Infisical instance host | 443 | TCP (HTTPS) | API communication + certificate requests — **egress** |
-| Platform ↔ relay | Infisical Platform | Relay server | 8443 | TCP + TLS | Platform connects to the relay; traffic is then routed over the gateway's existing tunnel |
-| Resource access | Gateway | Private resource | the resource's own port (e.g. 5432) | TCP or HTTP | Gateway forwards platform requests to the internal service — raw TCP for most resources (e.g. databases), HTTP for resources like Kubernetes — **local** |
-
-## Firewall / egress allowlist
+| Relay tunnel | Gateway | Relay server | 2222 | TCP (SSH) | Establishes the SSH reverse tunnel. **Egress** |
+| Infisical API | Gateway | Infisical instance host | 443 | TCP (HTTPS) | API communication and certificate requests. **Egress** |
+| Platform to relay | Infisical Platform | Relay server | 8443 | TCP + TLS | Platform connects to the relay, which routes the traffic over the gateway's existing tunnel |
+| Resource access | Gateway | Private resource | the resource's own port (e.g. 5432) | TCP or HTTP | Gateway forwards platform requests to the internal service. Raw TCP for most resources such as databases, HTTP for resources like Kubernetes. **Local** |
On the Gateway host, allow **outbound** access only:
@@ -42,21 +49,72 @@ On the Gateway host, allow **outbound** access only:
No inbound rules are required.
-With the default **Auto Select Relay** option there is no single relay address to allowlist, since the gateway may fail over between managed relays — see [Which relay address do I need to allowlist?](#frequently-asked-questions) below for the endpoints to include and how to pin to a single relay.
+With the default **Auto Select Relay** option there is no single relay address to allowlist, since the gateway may fail over between managed relays. See [Which relay address do I need to allowlist?](#frequently-asked-questions) below for the endpoints to include and how to pin to a single relay.
+
+## Direct listen mode
+
+```mermaid
+%%{init: {'flowchart': {'nodeSpacing': 70, 'rankSpacing': 110, 'curve': 'basis'}}}%%
+flowchart LR
+ subgraph customer["Customer Private Network"]
+ direction TB
+ GW["Infisical Gateway"]
+ RES[("Private Resource")]
+ GW -->|"TCP or HTTP forwarding"| RES
+ end
+ PLAT["Infisical Platform"]
+ GW -->|"TCP 443 · HTTPS"| PLAT
+ PLAT -->|"TCP 8443 · mTLS"| GW
+```
+
+| Connection | Source | Destination | Port | Protocol | Purpose |
+|---|---|---|---|---|---|
+| Gateway listener | Infisical Platform | Gateway's registered address | the port you set with `--listen-address` | TCP + mTLS | Platform connects to the gateway to serve every operation. **Ingress** on the Gateway host |
+| Infisical API | Gateway | Infisical instance host | 443 | TCP (HTTPS) | API communication and certificate requests. **Egress** |
+| Resource access | Gateway | Private resource | the resource's own port (e.g. 5432) | TCP or HTTP | Gateway forwards platform requests to the internal service. **Local** |
+
+On the Gateway host, allow:
+
+- **Inbound** access on the port you set with `--listen-address`, from the Infisical instance host only
+- **Outbound TCP 443** to the Infisical instance host
+
+The address you register is the one Infisical dials, and it's written into the Gateway's server certificate, so it has to be stable. An internal DNS name or a load balancer in front of the Gateway both work. Changing it means re-running the deploy command so the Gateway is issued a certificate for the new address.
+
+By default the Gateway binds the port from `--listen-address` on every interface. To bind somewhere else, such as one interface or a different local port behind a load balancer, pass `--bind` as well.
+
+## Running both modes
+
+A 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.
## Self-hosted relay (optional)
If you run a self-hosted relay, that host needs:
- **Inbound TCP 2222** from your gateways (SSH reverse tunnels)
-- **Inbound TCP 8443** from the Infisical instance host (platform ↔ relay)
+- **Inbound TCP 8443** from the Infisical instance host (platform to relay)
- **Outbound TCP 443** to the Infisical instance host (relay API + certificates)
## Frequently asked questions
<AccordionGroup>
<Accordion title="Does the Gateway require any inbound ports?">
- No. The Gateway makes only outbound connections (TCP 2222 to the relay and TCP 443 to the Infisical API). The platform reaches the Gateway back over its own outbound SSH tunnel via the relay, so no inbound firewall rules are needed.
+ In relay mode, no. The Gateway makes only outbound connections (TCP 2222 to the relay and TCP 443 to the Infisical API), and the platform reaches it back over that same tunnel.
+
+ In direct listen mode, yes. The Gateway accepts inbound connections on the port you set with `--listen-address`, and that port needs to be open to the Infisical instance host. Scope the rule to that host rather than opening the port broadly.
+ </Accordion>
+
+ <Accordion title="Which mode should I use?">
+ Use direct listen when Infisical can already reach the Gateway host at a stable address, which is the common case when you self-host Infisical in the same network as your resources. It needs no relay.
+
+ 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. See [Gateway deployment](/documentation/platform/gateways/gateway-deployment) for the full comparison.
+ </Accordion>
+
+ <Accordion title="Do PAM CLI sessions work in direct listen mode?">
+ Only from a machine that can reach the Gateway's registered address. The CLI opens its own connection to the Gateway rather than going through Infisical, so a user on a laptop outside the network can't reach a Gateway that only listens on an internal address. Those users need a VPN into the network, or a relay on the Gateway.
+
+ Browser-based PAM access is unaffected, because the platform brokers that connection.
</Accordion>
<Accordion title="Does the Gateway only proxy raw TCP?">
@@ -64,11 +122,11 @@ If you run a self-hosted relay, that host needs:
</Accordion>
<Accordion title="Which relay address do I need to allowlist?">
- With the default **Auto Select Relay**, the Gateway may connect to, and fail over between, any managed relay Infisical operates for your region, so a strict outbound TCP 2222 allowlist must include every managed relay endpoint. You can find these under **Organization Settings → Networking**, or ask Infisical support. To allowlist a single address instead, pin the Gateway to one relay at enrollment with the `--target-relay-name` option; this removes automatic failover to other relays.
+ With the default **Auto Select Relay**, the Gateway may connect to, and fail over between, any managed relay Infisical operates for your region, so a strict outbound TCP 2222 allowlist must include every managed relay endpoint. You can find these under **Organization Settings → Networking**, or ask Infisical support. To allowlist a single address instead, pin the Gateway to one relay at enrollment with the `--relay` option; this removes automatic failover to other relays.
</Accordion>
<Accordion title="Can Gateway traffic egress through an HTTP forward proxy?">
- Not currently. The Gateway's connection to the relay is a raw SSH tunnel over TCP (port 2222), and its connection to the Infisical API is TLS over TCP (port 443). Neither is HTTP, so an HTTP forward proxy can't transparently carry this traffic.
+ Not currently. In relay mode, the Gateway's connection to the relay is a raw SSH tunnel over TCP (port 2222), and its connection to the Infisical API is TLS over TCP (port 443). Neither is HTTP, so an HTTP forward proxy can't transparently carry this traffic.
If an HTTP proxy is mandatory in your environment, you have two options:
diff --git a/docs/documentation/platform/gateways/relay-deployment/overview.mdx b/docs/documentation/platform/gateways/relay-deployment/overview.mdx
index 7bd608fc13..30873a08c1 100644
--- a/docs/documentation/platform/gateways/relay-deployment/overview.mdx
+++ b/docs/documentation/platform/gateways/relay-deployment/overview.mdx
@@ -7,11 +7,23 @@ Infisical Relay is a secure routing layer that allows Infisical to connect to yo
The relay acts as an intermediary, forwarding encrypted traffic between Infisical and your deployed gateways. This ensures that your sensitive data remains protected and never leaves your network unencrypted.
With this architecture, you can achieve secure, firewall-friendly access across network boundaries, making it possible for Infisical to interact with resources even in highly restricted environments.
-Before diving in, it's important to determine whether you actually need to deploy your own relay server or if you can use Infisical's managed infrastructure.
+Before diving in, work out whether you need a relay at all, and if you do, whether you can use Infisical's managed infrastructure.
-## Do you need to deploy a Relay?
+## Do you need a relay at all?
-Not all users need to deploy their own relay servers. Infisical provides managed relay infrastructure in US/EU regions for Infisical Cloud users, which requires no setup or maintenance. You only need to deploy a relay if you:
+If you self-host Infisical and it can reach your gateway host at a stable address, you can skip relays entirely. Deploy the gateway in [direct listen mode](/documentation/platform/gateways/gateway-deployment) instead, and Infisical connects to it.
+
+A relay is what you need when:
+
+- The gateway sits behind NAT or a firewall you can't open for inbound connections
+- You're on Infisical Cloud, where gateways use relay mode
+- PAM CLI users connect from outside the gateway's network, since the CLI dials the gateway from their own machine
+
+A gateway can also run both, giving you direct connections for platform operations and a relay for CLI users outside the network.
+
+## Do you need to deploy your own relay?
+
+Infisical provides managed relay infrastructure in US/EU regions for Infisical Cloud users, which requires no setup or maintenance. You only need to deploy your own relay if you:
- Are self-hosting Infisical
- Have a dedicated enterprise instance of Infisical (managed by Infisical)
diff --git a/docs/self-hosting/helm-charts/gateway.mdx b/docs/self-hosting/helm-charts/gateway.mdx
index 41e81c2fa0..2a00d6e706 100644
--- a/docs/self-hosting/helm-charts/gateway.mdx
+++ b/docs/self-hosting/helm-charts/gateway.mdx
@@ -103,6 +103,7 @@ helm uninstall infisical-gateway --namespace infisical-gateway
| `gateway.enrollment.kubernetes.externalTokenReview` | `false` | Set true when TokenReview permission comes from outside this chart, either a token reviewer JWT configured in Infisical or a binding you manage. Required to install with `serviceAccount.createAsAuthDelegator` disabled. |
| `gateway.enrollment.credentialsSecretRef` | `""` | Kubernetes secret with credentials injected as env vars. |
| `gateway.relayName` | `""` | Specific relay to connect to. Empty for automatic selection. |
+| `gateway.listenAddress` | `""` | `host:port` that Infisical dials to reach the gateway, which runs it in direct listen mode. Empty for relay mode. |
| `persistence.enabled` | `true` | Enable persistent storage. Required for token auth, optional for AWS and Kubernetes auth. |
| `persistence.storageClass` | `""` | Storage class for the PVC. |
| `persistence.size` | `5Gi` | PVC size. |
@@ -122,6 +123,37 @@ helm uninstall infisical-gateway --namespace infisical-gateway
| `extraEnvFrom` | `[]` | Load environment variables from Secrets or ConfigMaps. |
| `extraArgs` | `[]` | Extra arguments appended to the gateway container command. |
| `extraObjects` | `[]` | Extra Kubernetes manifests to deploy with this chart. |
+| `service.type` | `ClusterIP` | Type of the Service created in direct listen mode. |
+| `service.port` | `80` | Port the Service exposes. It forwards to the port in `gateway.listenAddress`, so the two don't have to match. |
+
+## Direct listen mode
+
+By default the gateway connects out to a relay. To have Infisical connect to the gateway instead, set `gateway.listenAddress` to the address Infisical dials.
+
+<Warning>
+ `gateway.listenAddress` needs an `image.tag` whose CLI supports `--listen-address`. An older image rejects the flag and the pod crash-loops with `unknown flag: --listen-address`, so check the tag before setting it.
+</Warning>
+
+
+```bash
+helm install infisical-gateway infisical-helm-charts/infisical-gateway \
+ --namespace infisical-gateway \
+ --create-namespace \
+ --set gateway.name=<gateway-name> \
+ --set gateway.listenAddress=infisical-gateway.infisical-gateway.svc.cluster.local:8443 \
+ --set service.port=8443 \
+ --set gateway.enrollment.method=token \
+ --set gateway.enrollment.token.value=<enrollment-token> \
+ --set gateway.domain=<your-infisical-domain>
+```
+
+The chart takes the container port from `gateway.listenAddress` and points the Service at it, so they can't drift apart. `service.port` is the port the Service itself exposes, which is why the example sets it to 8443 as well: the address you register has to name the port callers reach the Service on. A `host:port` value is required, and the chart fails the render if the port is missing.
+
+The Service is created only in direct listen mode. In relay mode the gateway accepts no connections, so the chart creates none.
+
+The address has to be one Infisical can resolve and reach. An in-cluster Service DNS name works when you self-host Infisical in the same cluster. From outside the cluster, expose the gateway through an Ingress or a `LoadBalancer` Service and register that address instead.
+
+Direct listen is available on self-hosted Infisical. On Infisical Cloud, leave `gateway.listenAddress` empty and use a relay.
## Default Helm values
@@ -181,6 +213,9 @@ gateway:
# Specific relay to connect to. Leave empty for automatic selection.
relayName: ""
+ # Stable host:port advertised by a gateway accepting direct connections.
+ listenAddress: ""
+
pamSessionRecordingsDirectory: /var/lib/infisical/session_recordings
# Persistent storage for the gateway (credentials and session recordings).
diff --git a/frontend/src/hooks/api/gateway-pools/types.ts b/frontend/src/hooks/api/gateway-pools/types.ts
index e40af7b39a..88fe5261ba 100644
--- a/frontend/src/hooks/api/gateway-pools/types.ts
+++ b/frontend/src/hooks/api/gateway-pools/types.ts
@@ -47,6 +47,8 @@ export type TGatewayPoolMember = {
name: string;
heartbeat: string | null;
heartbeatTTL: number | null;
+ directAddress: string | null;
+ directHeartbeat: string | null;
};
export type TGatewayPoolWithMembers = {
diff --git a/frontend/src/hooks/api/gateways-v2/utils.ts b/frontend/src/hooks/api/gateways-v2/utils.ts
index d1bbf215ee..e66f9d4717 100644
--- a/frontend/src/hooks/api/gateways-v2/utils.ts
+++ b/frontend/src/hooks/api/gateways-v2/utils.ts
@@ -6,11 +6,27 @@ export const isGatewayHealthy = (gateway: {
directHeartbeat?: string | null;
heartbeatTTL?: number | null;
}): boolean => {
- const heartbeat = gateway.directAddress ? gateway.directHeartbeat : gateway.heartbeat;
- if (!heartbeat) return false;
if (!gateway.heartbeatTTL) return false;
- return (
- new Date(heartbeat).getTime() + (gateway.heartbeatTTL + HEARTBEAT_BUFFER_SECONDS) * 1000 >
- Date.now()
+
+ const isFresh = (probedAt?: string | null) =>
+ Boolean(probedAt) &&
+ new Date(probedAt as string).getTime() +
+ ((gateway.heartbeatTTL as number) + HEARTBEAT_BUFFER_SECONDS) * 1000 >
+ Date.now();
+
+ // 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.
+ if (gateway.directAddress) return isFresh(gateway.directHeartbeat) || isFresh(gateway.heartbeat);
+ return isFresh(gateway.heartbeat);
+};
+
+export const getLastSeenHeartbeat = (gateway: {
+ heartbeat?: string | null;
+ directHeartbeat?: string | null;
+}): string | null => {
+ const probes = [gateway.directHeartbeat, gateway.heartbeat].filter(Boolean) as string[];
+ if (!probes.length) return null;
+ return probes.reduce((latest, probe) =>
+ new Date(probe).getTime() > new Date(latest).getTime() ? probe : latest
);
};
diff --git a/frontend/src/hooks/api/gateways/queries.tsx b/frontend/src/hooks/api/gateways/queries.tsx
index e8919d73e2..4af8234145 100644
--- a/frontend/src/hooks/api/gateways/queries.tsx
+++ b/frontend/src/hooks/api/gateways/queries.tsx
@@ -19,7 +19,7 @@ export const gatewaysQueryKeys = {
// Filter out enrollment-flow gateways that haven't connected yet
// so gateway pickers don't show them as selectable options.
- const connectedV2 = dataV2.filter((g) => g.identityId || g.heartbeat);
+ const connectedV2 = dataV2.filter((g) => g.identityId || g.heartbeat || g.directHeartbeat);
return [
...data.gateways.map((g) => ({
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/AwsStartCommandDialog.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/AwsStartCommandDialog.tsx
index 58624d3ede..f116c1b2ab 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/AwsStartCommandDialog.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/AwsStartCommandDialog.tsx
@@ -35,7 +35,7 @@ export const AwsStartCommandContent = ({
const { data: relays, isPending: isRelaysLoading } = useGetRelays();
const [relay, setRelay] = useState<{ id: string; name: string }>(AUTO_RELAY_OPTION);
- const resolvedRelayName = relay.id === "_auto" ? "" : relay.name;
+ const resolvedRelayName = isDirect || relay.id === "_auto" ? "" : relay.name;
const cliCommand = useMemo(() => {
const relayPart = resolvedRelayName ? ` --relay=${resolvedRelayName}` : "";
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/EnrollmentTokenDialog.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/EnrollmentTokenDialog.tsx
index 5d64f5d5aa..499a42af00 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/EnrollmentTokenDialog.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/EnrollmentTokenDialog.tsx
@@ -66,13 +66,13 @@ export const EnrollmentTokenContent = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [enrollmentToken]);
- const isCommandDirty = relay.id !== commandRelay.id;
+ const isCommandDirty = !isDirect && relay.id !== commandRelay.id;
useEffect(() => {
onCommandDirtyChange(isCommandDirty);
}, [isCommandDirty, onCommandDirtyChange]);
- const resolvedRelayName = commandRelay.id === "_auto" ? "" : commandRelay.name;
+ const resolvedRelayName = isDirect || commandRelay.id === "_auto" ? "" : commandRelay.name;
const expiryLabel = formatTimeRemaining(expiresAt, now);
const isExpired = expiryLabel === "Expired";
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/KubernetesStartCommandDialog.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/KubernetesStartCommandDialog.tsx
index 6dbfceeb42..60e124a80d 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/KubernetesStartCommandDialog.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/KubernetesStartCommandDialog.tsx
@@ -43,7 +43,7 @@ export const KubernetesStartCommandContent = ({
const { data: relays, isPending: isRelaysLoading } = useGetRelays();
const [relay, setRelay] = useState<{ id: string; name: string }>(AUTO_RELAY_OPTION);
- const resolvedRelayName = relay.id === "_auto" ? "" : relay.name;
+ const resolvedRelayName = isDirect || relay.id === "_auto" ? "" : relay.name;
const helmCommand = useMemo(() => {
const advertisedAddress = listenAddress.trim() || "<gateway-address>:8443";
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDeploySection/GatewayDeploySection.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDeploySection/GatewayDeploySection.tsx
index f11d04ac0a..1cc37f69a4 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDeploySection/GatewayDeploySection.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDeploySection/GatewayDeploySection.tsx
@@ -1,11 +1,12 @@
import { useState } from "react";
-import { LockKeyholeIcon, RefreshCwIcon, RocketIcon } from "lucide-react";
+import { InfoIcon, LockKeyholeIcon, RefreshCwIcon, RocketIcon } from "lucide-react";
import { createNotification } from "@app/components/notifications";
import {
Alert,
AlertDescription,
AlertTitle,
+ Badge,
Button,
Card,
CardAction,
@@ -15,14 +16,14 @@ import {
CardTitle,
DocumentationLinkBadge,
Field,
+ FieldContent,
FieldDescription,
+ FieldError,
FieldLabel,
+ FieldTitle,
Input,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
+ RadioGroup,
+ RadioGroupItem,
Tabs,
TabsList,
TabsTrigger
@@ -40,6 +41,28 @@ import { AwsStartCommandContent } from "../GatewayAuthMethod/AwsStartCommandDial
import { EnrollmentTokenContent } from "../GatewayAuthMethod/EnrollmentTokenDialog";
import { KubernetesStartCommandContent } from "../GatewayAuthMethod/KubernetesStartCommandDialog";
+// Mirrors the backend's parseDirectAddress so the form rejects exactly what the API would.
+const isValidListenAddress = (address: string) => {
+ try {
+ const parsed = new URL(`tcp://${address}`);
+ if (
+ !parsed.hostname ||
+ !parsed.port ||
+ parsed.username ||
+ parsed.password ||
+ parsed.pathname ||
+ parsed.search ||
+ parsed.hash
+ ) {
+ return false;
+ }
+ const port = Number(parsed.port);
+ return Number.isInteger(port) && port >= 1 && port <= 65535;
+ } catch {
+ return false;
+ }
+};
+
type Props = {
gatewayId: string;
gatewayName: string;
@@ -55,10 +78,15 @@ export const GatewayDeploySection = ({
}: Props) => {
const isCloud = isInfisicalCloud();
const isKubernetes = authMethod.method === "kubernetes";
+ // Relay unless the gateway already listens directly. Defaulting to direct on a gateway with no
+ // address yet would render a command carrying the placeholder address.
const [connectionMode, setConnectionMode] = useState<"relay" | "direct">(
- isCloud ? "relay" : "direct"
+ !isCloud && directAddress ? "direct" : "relay"
);
const [listenAddress, setListenAddress] = useState(directAddress ?? "");
+ const trimmedListenAddress = listenAddress.trim();
+ const hasListenAddressError =
+ trimmedListenAddress.length > 0 && !isValidListenAddress(trimmedListenAddress);
const [deploymentMethod, setDeploymentMethod] = useState("");
const [mintedEnrollment, setMintedEnrollment] = useState<
(TGatewayEnrollmentToken & { gatewayId: string }) | null
@@ -135,37 +163,79 @@ export const GatewayDeploySection = ({
<>
{!isCloud && (
<Field>
- <FieldLabel htmlFor="gateway-connection-mode">Connection Mode</FieldLabel>
- <Select
+ <FieldLabel>Connection Mode</FieldLabel>
+ <FieldDescription className="-mt-1 mb-1">
+ Pick which side opens the connection. Both use the same mutually authenticated
+ TLS.
+ </FieldDescription>
+ <RadioGroup
value={connectionMode}
onValueChange={(value) => setConnectionMode(value as "relay" | "direct")}
>
- <SelectTrigger id="gateway-connection-mode">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="direct">Direct Listen</SelectItem>
- <SelectItem value="relay">Relay</SelectItem>
- </SelectContent>
- </Select>
+ <FieldLabel htmlFor="gateway-connection-mode-direct" variant="org">
+ <Field orientation="horizontal">
+ <FieldContent>
+ <FieldTitle>
+ Direct Listen
+ <Badge variant="org">Recommended</Badge>
+ </FieldTitle>
+ <FieldDescription>
+ Infisical opens the connection to the gateway. Choose this when the
+ gateway has a stable address Infisical can reach, with no relay to
+ deploy.
+ </FieldDescription>
+ </FieldContent>
+ <RadioGroupItem value="direct" id="gateway-connection-mode-direct" />
+ </Field>
+ </FieldLabel>
+ <FieldLabel htmlFor="gateway-connection-mode-relay" variant="org">
+ <Field orientation="horizontal">
+ <FieldContent>
+ <FieldTitle>Relay</FieldTitle>
+ <FieldDescription>
+ The gateway opens the connection out to a relay. Choose this when
+ inbound connections to the gateway are blocked by NAT or a firewall.
+ </FieldDescription>
+ </FieldContent>
+ <RadioGroupItem value="relay" id="gateway-connection-mode-relay" />
+ </Field>
+ </FieldLabel>
+ </RadioGroup>
</Field>
)}
{connectionMode === "direct" && (
- <Field>
+ <Field data-invalid={hasListenAddressError}>
<FieldLabel htmlFor="gateway-listen-address">Listen Address</FieldLabel>
<Input
id="gateway-listen-address"
value={listenAddress}
onChange={(event) => setListenAddress(event.target.value)}
placeholder="gateway.internal:8443"
+ isError={hasListenAddressError}
/>
<FieldDescription>
- Enter the stable address Infisical will use to reach this gateway.
+ The host and port Infisical dials. The gateway binds this port on every
+ interface.
</FieldDescription>
+ <FieldError isOpen={hasListenAddressError}>
+ Enter a host and port, such as gateway.internal:8443.
+ </FieldError>
</Field>
)}
+ {connectionMode === "direct" && (
+ <Alert variant="info" appearance="borderless">
+ <InfoIcon />
+ <AlertTitle>PAM CLI sessions dial this address directly</AlertTitle>
+ <AlertDescription>
+ The CLI connects from the user&apos;s own machine, not from Infisical, so that
+ machine has to reach this address as well. Users outside this network need a VPN
+ into it, or a relay on this gateway. Browser-based PAM access is unaffected.
+ </AlertDescription>
+ </Alert>
+ )}
+
{authMethod.method === "aws" && (
<AwsStartCommandContent
gatewayId={gatewayId}
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx
index d8764e5406..25f218f555 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx
@@ -32,7 +32,7 @@ import {
import { useTimedReset } from "@app/hooks";
import { useUpdateGateway } from "@app/hooks/api/gateways-v2";
import { TGatewayV2, TGatewayV2WithAuthMethod } from "@app/hooks/api/gateways-v2/types";
-import { isGatewayHealthy } from "@app/hooks/api/gateways-v2/utils";
+import { getLastSeenHeartbeat, isGatewayHealthy } from "@app/hooks/api/gateways-v2/utils";
import {
NetworkingAuthMethodForm,
@@ -40,7 +40,7 @@ import {
} from "../../../components/NetworkingAuthMethodForm";
const HealthBadge = ({ gateway }: { gateway: TGatewayV2 }) => {
- const heartbeat = gateway.directAddress ? gateway.directHeartbeat : gateway.heartbeat;
+ const heartbeat = getLastSeenHeartbeat(gateway);
if (
!heartbeat &&
gateway.heartbeatTTL === null &&
@@ -65,7 +65,7 @@ export const GatewayDetailsCard = ({ gateway }: { gateway: TGatewayV2WithAuthMet
const { authMethod } = gateway;
const isIdentityGateway = authMethod.method === "identity";
- const effectiveHeartbeat = gateway.directAddress ? gateway.directHeartbeat : gateway.heartbeat;
+ const effectiveHeartbeat = getLastSeenHeartbeat(gateway);
const connection = gateway.directAddress
? `${gateway.relayId ? "Direct + Relay" : "Direct"} (${gateway.directAddress})`
: gateway.relayId
diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayHealthStatus.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayHealthStatus.tsx
index 1fb5abcb61..814a276761 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayHealthStatus.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayHealthStatus.tsx
@@ -2,7 +2,7 @@ import { format } from "date-fns";
import { CircleCheckIcon, CircleDashedIcon, CircleXIcon } from "lucide-react";
import { Badge, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
-import { isGatewayHealthy } from "@app/hooks/api/gateways-v2/utils";
+import { getLastSeenHeartbeat, isGatewayHealthy } from "@app/hooks/api/gateways-v2/utils";
export const GatewayHealthStatus = ({
heartbeat,
@@ -17,8 +17,8 @@ export const GatewayHealthStatus = ({
directHeartbeat?: string | null;
heartbeatTTL?: number | null;
}) => {
- const effectiveHeartbeat = directAddress ? directHeartbeat : heartbeat;
- if (!effectiveHeartbeat && heartbeatTTL === null && !directAddress && !relayId) {
+ const lastSeen = getLastSeenHeartbeat({ heartbeat, directHeartbeat });
+ if (!lastSeen && heartbeatTTL === null && !directAddress && !relayId) {
return (
<Badge variant="warning" iconPosition="left">
<CircleDashedIcon />
@@ -27,7 +27,7 @@ export const GatewayHealthStatus = ({
);
}
- const heartbeatDate = effectiveHeartbeat ? new Date(effectiveHeartbeat) : null;
+ const heartbeatDate = lastSeen ? new Date(lastSeen) : null;
const isHealthy = isGatewayHealthy({ heartbeat, directAddress, directHeartbeat, heartbeatTTL });
return (
diff --git a/helm-charts/infisical-gateway/templates/_helpers.tpl b/helm-charts/infisical-gateway/templates/_helpers.tpl
index b983e79df5..8968a82909 100644
--- a/helm-charts/infisical-gateway/templates/_helpers.tpl
+++ b/helm-charts/infisical-gateway/templates/_helpers.tpl
@@ -60,3 +60,16 @@ Create the name of the service account to use
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- 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.
+*/}}
+{{- define "infisical-gateway.listenPort" -}}
+{{- $addr := .Values.gateway.listenAddress -}}
+{{- $port := splitList ":" $addr | last -}}
+{{- if or (eq $port $addr) (not (regexMatch "^[0-9]+$" $port)) -}}
+{{- fail (printf "gateway.listenAddress must be host:port, got %q" $addr) -}}
+{{- end -}}
+{{- $port -}}
+{{- end }}
diff --git a/helm-charts/infisical-gateway/templates/deployment.yaml b/helm-charts/infisical-gateway/templates/deployment.yaml
index 28891146ae..daea4d9872 100644
--- a/helm-charts/infisical-gateway/templates/deployment.yaml
+++ b/helm-charts/infisical-gateway/templates/deployment.yaml
@@ -134,7 +134,7 @@ spec:
{{- if .Values.gateway.listenAddress }}
ports:
- name: http
- containerPort: {{ .Values.service.port }}
+ containerPort: {{ include "infisical-gateway.listenPort" . }}
protocol: TCP
{{- end }}
volumeMounts:
diff --git a/helm-charts/infisical-gateway/templates/service.yaml b/helm-charts/infisical-gateway/templates/service.yaml
index c1457f80e4..b254ad3442 100644
--- a/helm-charts/infisical-gateway/templates/service.yaml
+++ b/helm-charts/infisical-gateway/templates/service.yaml
@@ -1,3 +1,4 @@
+{{- if .Values.gateway.listenAddress }}
apiVersion: v1
kind: Service
metadata:
@@ -8,8 +9,9 @@ spec:
type: {{ .Values.service.type }}
ports:
- port: {{ .Values.service.port }}
- targetPort: http
+ targetPort: {{ include "infisical-gateway.listenPort" . }}
protocol: TCP
name: http
selector:
{{- include "infisical-gateway.selectorLabels" . | nindent 4 }}
+{{- end }}
diff --git a/helm-charts/infisical-gateway/values.yaml b/helm-charts/infisical-gateway/values.yaml
index 495177bb8e..a105836108 100644
--- a/helm-charts/infisical-gateway/values.yaml
+++ b/helm-charts/infisical-gateway/values.yaml
@@ -55,6 +55,8 @@ gateway:
relayName: ""
# Stable host:port advertised by a gateway accepting direct connections.
+ # Requires an image.tag whose CLI supports --listen-address; older images reject the flag and the
+ # pod crash-loops on startup.
listenAddress: ""
pamSessionRecordingsDirectory: /var/lib/infisical/session_recordings