Skip to content

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

feat(gateway): support direct listen connections

bernie-g884aae9d4c97
diff --git a/backend/src/db/migrations/20260904120000_add-direct-gateway-transport.ts b/backend/src/db/migrations/20260904120000_add-direct-gateway-transport.ts
new file mode 100644
index 0000000000..a405ca0c37
--- /dev/null
+++ b/backend/src/db/migrations/20260904120000_add-direct-gateway-transport.ts
@@ -0,0 +1,16 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ await knex.schema.alterTable(TableName.GatewayV2, (table) => {
+ table.text("directAddress").nullable();
+ table.timestamp("directHeartbeat", { useTz: true }).nullable();
+ });
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.schema.alterTable(TableName.GatewayV2, (table) => {
+ table.dropColumns("directAddress", "directHeartbeat");
+ });
+}
diff --git a/backend/src/db/sanitized-schema.yaml b/backend/src/db/sanitized-schema.yaml
index edb002b8f4..535fa20a92 100644
--- a/backend/src/db/sanitized-schema.yaml
+++ b/backend/src/db/sanitized-schema.yaml
@@ -203,6 +203,8 @@ tables:
- relayId
- name
- heartbeat
+ - directAddress
+ - directHeartbeat
- healthAlertedAt
- name: groups
diff --git a/backend/src/db/schemas/gateways-v2.ts b/backend/src/db/schemas/gateways-v2.ts
index 88e73d6608..e15b2c953c 100644
--- a/backend/src/db/schemas/gateways-v2.ts
+++ b/backend/src/db/schemas/gateways-v2.ts
@@ -22,7 +22,9 @@ export const GatewaysV2Schema = z.object({
healthAlertedAt: z.date().nullable().optional(),
tokenVersion: z.number().default(0),
heartbeatTTL: z.number().nullable().optional(),
- capabilities: z.unknown().nullable().optional()
+ capabilities: z.unknown().nullable().optional(),
+ directAddress: z.string().nullable().optional(),
+ directHeartbeat: z.date().nullable().optional()
});
export type TGatewaysV2 = z.infer<typeof GatewaysV2Schema>;
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 9a61598049..7a6b553eba 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
@@ -323,7 +323,11 @@ export const registerPamWebAccessRouter = async (server: FastifyZodProvider) =>
.max(255)
.regex(hostPattern, "Must be a valid hostname or IP address")
.optional()
- .describe("Target host to connect to, for accounts that allow multiple hosts")
+ .describe("Target host to connect to, for accounts that allow multiple hosts"),
+ supportedTransports: z
+ .array(z.enum(["relay", "direct"]))
+ .max(2)
+ .optional()
}),
response: {
200: z.object({
@@ -331,6 +335,7 @@ export const registerPamWebAccessRouter = async (server: FastifyZodProvider) =>
accountType: z.nativeEnum(PamAccountType).describe("The account type"),
metadata: z.record(z.string()).optional().describe("Account-type-specific metadata (e.g., username)"),
relayHost: z.string().optional().describe("The relay host to connect to"),
+ directAddress: z.string().optional().describe("The gateway address for a direct connection"),
relayClientCertificate: z.string().optional().describe("Client certificate for the relay connection"),
relayClientPrivateKey: z.string().optional().describe("Client private key for the relay connection"),
relayServerCertificateChain: z
@@ -377,7 +382,9 @@ export const registerPamWebAccessRouter = async (server: FastifyZodProvider) =>
mfaSessionId: req.body.mfaSessionId,
tokenVersionId: isUserSessionAuth(req.auth) ? req.auth.tokenVersionId : undefined,
accessMethod: req.body.accessMethod === "web" ? PamAccessMethod.Web : PamAccessMethod.Cli,
- targetHost: req.body.targetHost
+ targetHost: req.body.targetHost,
+ supportedTransports:
+ req.body.accessMethod === PamAccessMethod.Web ? undefined : (req.body.supportedTransports ?? [])
});
await server.services.auditLog.createAuditLog({
@@ -414,6 +421,7 @@ export const registerPamWebAccessRouter = async (server: FastifyZodProvider) =>
accountType: result.accountType,
metadata: result.metadata,
relayHost: result.relayHost,
+ directAddress: result.directAddress,
relayClientCertificate: result.relayClientCertificate,
relayClientPrivateKey: result.relayClientPrivateKey,
relayServerCertificateChain: result.relayServerCertificateChain,
diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.ts
index 398776ef3d..4021d2e29a 100644
--- a/backend/src/ee/routes/v2/gateway-router.ts
+++ b/backend/src/ee/routes/v2/gateway-router.ts
@@ -11,10 +11,13 @@ import { AuthMode } from "@app/services/auth/auth-type";
const SanitizedGatewayV2Schema = GatewaysV2Schema.pick({
id: true,
identityId: true,
+ relayId: true,
name: true,
createdAt: true,
updatedAt: true,
heartbeat: true,
+ directAddress: true,
+ directHeartbeat: true,
heartbeatTTL: true,
capabilities: true
});
@@ -26,23 +29,27 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
schema: {
operationId: "registerGateway",
body: z.object({
- relayName: slugSchema({ min: 1, max: 32, field: "relayName" }),
+ 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" })
}),
response: {
200: z.object({
gatewayId: z.string(),
- relayHost: z.string(),
+ directAddress: z.string().optional(),
+ relayHost: z.string().optional(),
pki: z.object({
serverCertificate: z.string(),
serverPrivateKey: z.string(),
clientCertificateChain: z.string()
}),
- ssh: z.object({
- clientCertificate: z.string(),
- clientPrivateKey: z.string(),
- serverCAPublicKey: z.string()
- })
+ ssh: z
+ .object({
+ clientCertificate: z.string(),
+ clientPrivateKey: z.string(),
+ serverCAPublicKey: z.string()
+ })
+ .optional()
})
}
},
@@ -57,6 +64,7 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorType: req.permission.type,
actorAuthMethod: req.permission.authMethod,
+ directAddress: req.body.directAddress,
name: req.body.name
});
}
diff --git a/backend/src/ee/routes/v3/gateway-router.ts b/backend/src/ee/routes/v3/gateway-router.ts
index df82c7ba19..b81369388d 100644
--- a/backend/src/ee/routes/v3/gateway-router.ts
+++ b/backend/src/ee/routes/v3/gateway-router.ts
@@ -28,11 +28,14 @@ const loginRateLimit = { windowMs: 60 * 1000, max: 10 };
const SanitizedGatewayV2Schema = GatewaysV2Schema.pick({
id: true,
identityId: true,
+ relayId: true,
name: true,
createdAt: true,
updatedAt: true,
heartbeat: true,
- heartbeatTTL: true
+ heartbeatTTL: true,
+ directAddress: true,
+ directHeartbeat: true
}).extend({
canRevoke: z.boolean()
});
@@ -717,22 +720,26 @@ export const registerGatewayV3Router = async (server: FastifyZodProvider) => {
schema: {
operationId: "connectGateway",
body: z.object({
- relayName: z.string().trim().min(1).max(32).optional()
+ relayName: z.string().trim().min(1).max(32).optional(),
+ directAddress: z.string().trim().min(3).max(255).optional()
}),
response: {
200: z.object({
gatewayId: z.string(),
- relayHost: z.string(),
+ directAddress: z.string().optional(),
+ relayHost: z.string().optional(),
pki: z.object({
serverCertificate: z.string(),
serverPrivateKey: z.string(),
clientCertificateChain: z.string()
}),
- ssh: z.object({
- clientCertificate: z.string(),
- clientPrivateKey: z.string(),
- serverCAPublicKey: z.string()
- })
+ ssh: z
+ .object({
+ clientCertificate: z.string(),
+ clientPrivateKey: z.string(),
+ serverCAPublicKey: z.string()
+ })
+ .optional()
})
}
},
@@ -742,7 +749,8 @@ export const registerGatewayV3Router = async (server: FastifyZodProvider) => {
orgId: req.permission.orgId,
actorId: req.permission.id,
actorType: req.permission.type,
- relayName: req.body.relayName
+ relayName: req.body.relayName,
+ directAddress: req.body.directAddress
});
}
});
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 fa5f8f46e6..2ff7108718 100644
--- a/backend/src/ee/services/gateway-pool/gateway-pool-dal.ts
+++ b/backend/src/ee/services/gateway-pool/gateway-pool-dal.ts
@@ -14,6 +14,7 @@ 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)
@@ -27,7 +28,7 @@ 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 ${TableName.GatewayV2}."heartbeat" + make_interval(secs => COALESCE(${TableName.GatewayV2}."heartbeatTTL", 0) + ${HEARTBEAT_BUFFER_SECONDS}) > NOW() THEN ${TableName.GatewayPoolMembership}."gatewayId" END) AS "healthyMemberCount"`
+ `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"`
),
db.raw(
`COALESCE(array_agg(DISTINCT ${TableName.GatewayPoolMembership}."gatewayId") FILTER (WHERE ${TableName.GatewayPoolMembership}."gatewayId" IS NOT NULL), '{}') AS "memberGatewayIds"`
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 3d6415408e..10cfcec6ad 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
@@ -12,12 +12,13 @@ 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 "${TableName.GatewayV2}"."heartbeat" + make_interval(secs => COALESCE("${TableName.GatewayV2}"."heartbeatTTL", 0) + ${HEARTBEAT_BUFFER_SECONDS}) > NOW()`
+ `COALESCE("${TableName.GatewayV2}"."heartbeatTTL", 0) > 0 AND ${effectiveHeartbeat} + make_interval(secs => COALESCE("${TableName.GatewayV2}"."heartbeatTTL", 0) + ${HEARTBEAT_BUFFER_SECONDS}) > NOW()`
)
.select(`${TableName.GatewayV2}.*`);
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 ed16bd5c16..1d0cfc6061 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-dal.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-dal.ts
@@ -27,14 +27,13 @@ export const gatewayV2DalFactory = (db: TDbClient) => {
.select(db.ref("name").withSchema(TableName.Identity).as("identityName"));
if (isHeartbeatStale) {
- // Gateway is stale when: heartbeat + heartbeatTTL + buffer < NOW(), OR heartbeatTTL = 0
- // Only consider gateways that have heartbeat (registered and probed at least once)
- void query.whereNotNull(`${TableName.GatewayV2}.heartbeat`);
+ 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(
- `"${TableName.GatewayV2}"."heartbeat" + make_interval(secs => COALESCE("${TableName.GatewayV2}"."heartbeatTTL", 0) + ${HEARTBEAT_BUFFER_SECONDS}) < NOW()`
+ `${effectiveHeartbeat} + make_interval(secs => COALESCE("${TableName.GatewayV2}"."heartbeatTTL", 0) + ${HEARTBEAT_BUFFER_SECONDS}) < NOW()`
)
)
.orWhere(`${TableName.GatewayV2}.heartbeatTTL`, 0);
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 610cc827bf..7ce9316013 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -5,6 +5,7 @@ import * as x509 from "@peculiar/x509";
import { OrganizationActionScope, OrgMembershipRole, OrgMembershipStatus, TRelays } from "@app/db/schemas";
import { PgSqlLock } from "@app/keystore/keystore";
+import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
@@ -54,6 +55,35 @@ import { TOrgGatewayConfigV2DALFactory } from "./org-gateway-config-v2-dal";
// Temporary limit until gateway limiting is implemented at the relay level
const MAX_GATEWAYS_PER_ORG = 50;
+const parseDirectAddress = (address: string) => {
+ let parsed: URL;
+ try {
+ parsed = new URL(`tcp://${address}`);
+ } catch {
+ throw new BadRequestError({ message: `Gateway direct address "${address}" must use the host:port format` });
+ }
+
+ if (
+ !parsed.hostname ||
+ !parsed.port ||
+ parsed.username ||
+ parsed.password ||
+ parsed.pathname ||
+ parsed.search ||
+ parsed.hash
+ ) {
+ throw new BadRequestError({ message: `Gateway direct address "${address}" must use the host:port format` });
+ }
+
+ const port = Number(parsed.port);
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
+ throw new BadRequestError({ message: `Gateway direct address "${address}" must include a port from 1 to 65535` });
+ }
+
+ const host = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;
+ return { host, port };
+};
+
type TGatewayV2ServiceFactoryDep = {
orgGatewayConfigV2DAL: Pick<TOrgGatewayConfigV2DALFactory, "findOne" | "create" | "transaction" | "findById">;
kmsService: TKmsServiceFactory;
@@ -342,11 +372,13 @@ export const gatewayV2ServiceFactory = ({
const getPlatformConnectionDetailsByGatewayId = async ({
gatewayId,
targetHost,
- targetPort
+ targetPort,
+ transport
}: {
gatewayId: string;
targetHost: string;
targetPort: number;
+ transport?: "direct" | "relay";
}): Promise<TGatewayV2ConnectionDetails | undefined> => {
const gateway = await gatewayV2DAL.findById(gatewayId);
if (!gateway) {
@@ -358,9 +390,12 @@ export const gatewayV2ServiceFactory = ({
throw new NotFoundError({ message: `Gateway Config for org ${gateway.orgId} not found.` });
}
- if (!gateway.relayId) {
+ const useDirect = transport !== "relay" && Boolean(gateway.directAddress);
+ const useRelay = transport === "relay" || !useDirect;
+
+ if ((transport === "direct" && !gateway.directAddress) || (useRelay && !gateway.relayId)) {
throw new BadRequestError({
- message: "Gateway is not associated with a relay"
+ message: `Gateway does not have a ${transport ?? "reachable"} transport configured`
});
}
@@ -458,27 +493,33 @@ export const gatewayV2ServiceFactory = ({
const gatewayClientCertPrivateKey = crypto.nativeCrypto.KeyObject.from(clientKeys.privateKey);
- const relayCredentials = await relayService.getCredentialsForClient({
- relayId: gateway.relayId,
- orgId: gateway.orgId,
- orgName: gateway.orgName,
- gatewayId,
- gatewayName: gateway.name
- });
+ const relayCredentials =
+ useRelay && gateway.relayId
+ ? await relayService.getCredentialsForClient({
+ relayId: gateway.relayId,
+ orgId: gateway.orgId,
+ orgName: gateway.orgName,
+ gatewayId,
+ gatewayName: gateway.name
+ })
+ : undefined;
return {
gatewayId,
- relayHost: relayCredentials.relayHost,
+ directAddress: useDirect ? (gateway.directAddress ?? undefined) : undefined,
+ relayHost: relayCredentials?.relayHost,
gateway: {
clientCertificate: clientCert.toString("pem"),
clientPrivateKey: gatewayClientCertPrivateKey.export({ format: "pem", type: "pkcs8" }).toString(),
serverCertificateChain: constructPemChainFromCerts([gatewayServerCaCert, rootGatewayCaCert])
},
- relay: {
- clientCertificate: relayCredentials.clientCertificate,
- clientPrivateKey: relayCredentials.clientPrivateKey,
- serverCertificateChain: relayCredentials.serverCertificateChain
- }
+ relay: relayCredentials
+ ? {
+ clientCertificate: relayCredentials.clientCertificate,
+ clientPrivateKey: relayCredentials.clientPrivateKey,
+ serverCertificateChain: relayCredentials.serverCertificateChain
+ }
+ : undefined
};
};
@@ -489,7 +530,8 @@ export const gatewayV2ServiceFactory = ({
accountType,
host,
port,
- actorMetadata
+ actorMetadata,
+ supportedTransports
}: {
gatewayId: string;
sessionId: string;
@@ -498,6 +540,7 @@ export const gatewayV2ServiceFactory = ({
host: string;
port?: number;
actorMetadata: { id: string; type: ActorType; name: string };
+ supportedTransports?: ("relay" | "direct")[];
}) => {
const gateway = await gatewayV2DAL.findById(gatewayId);
if (!gateway) {
@@ -509,9 +552,17 @@ export const gatewayV2ServiceFactory = ({
throw new NotFoundError({ message: `Gateway Config for org ${gateway.orgId} not found.` });
}
- if (!gateway.relayId) {
+ const allowDirect = supportedTransports === undefined || supportedTransports.includes("direct");
+ const allowRelay =
+ supportedTransports === undefined || supportedTransports.length === 0 || supportedTransports.includes("relay");
+ if (gateway.directAddress && !gateway.relayId && !allowDirect) {
+ throw new BadRequestError({
+ message: "This gateway only supports direct connections. Upgrade the Infisical CLI to connect to it."
+ });
+ }
+ if ((!gateway.directAddress || !allowDirect) && (!gateway.relayId || !allowRelay)) {
throw new BadRequestError({
- message: "Gateway is not associated with a relay"
+ message: "Gateway has no configured connection transport"
});
}
@@ -621,28 +672,34 @@ export const gatewayV2ServiceFactory = ({
const gatewayClientCertPrivateKey = crypto.nativeCrypto.KeyObject.from(clientKeys.privateKey);
- const relayCredentials = await relayService.getCredentialsForClient({
- relayId: gateway.relayId,
- orgId: gateway.orgId,
- orgName: gateway.orgName,
- gatewayId,
- gatewayName: gateway.name,
- duration
- });
+ const relayCredentials =
+ allowRelay && gateway.relayId
+ ? await relayService.getCredentialsForClient({
+ relayId: gateway.relayId,
+ orgId: gateway.orgId,
+ orgName: gateway.orgName,
+ gatewayId,
+ gatewayName: gateway.name,
+ duration
+ })
+ : undefined;
return {
gatewayId,
- relayHost: relayCredentials.relayHost,
+ directAddress: allowDirect ? (gateway.directAddress ?? undefined) : undefined,
+ relayHost: relayCredentials?.relayHost,
gateway: {
clientCertificate: clientCert.toString("pem"),
clientPrivateKey: gatewayClientCertPrivateKey.export({ format: "pem", type: "pkcs8" }).toString(),
serverCertificateChain: constructPemChainFromCerts([gatewayServerCaCert, rootGatewayCaCert])
},
- relay: {
- clientCertificate: relayCredentials.clientCertificate,
- clientPrivateKey: relayCredentials.clientPrivateKey,
- serverCertificateChain: relayCredentials.serverCertificateChain
- }
+ relay: relayCredentials
+ ? {
+ clientCertificate: relayCredentials.clientCertificate,
+ clientPrivateKey: relayCredentials.clientPrivateKey,
+ serverCertificateChain: relayCredentials.serverCertificateChain
+ }
+ : undefined
};
};
@@ -654,8 +711,8 @@ export const gatewayV2ServiceFactory = ({
}: {
orgId: string;
orgCAs: Awaited<ReturnType<typeof $getOrgCAs>>;
- relayName: string;
- gateway: { id: string; name: string };
+ relayName?: string;
+ gateway: { id: string; name: string; directAddress?: string | null };
}) => {
const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048);
const gatewayServerCaCert = new x509.X509Certificate(orgCAs.gatewayServerCaCertificate);
@@ -680,6 +737,16 @@ export const gatewayV2ServiceFactory = ({
const gatewayServerCertExpireAt = new Date(new Date().setDate(new Date().getDate() + 1));
const gatewayServerCertPrivateKey = crypto.nativeCrypto.KeyObject.from(gatewayServerKeys.privateKey);
+ const subjectAlternativeNames: x509.JsonGeneralName[] = [
+ { type: "dns", value: "localhost" },
+ { type: "ip", value: "127.0.0.1" },
+ { type: "ip", value: "::1" }
+ ];
+ if (gateway.directAddress) {
+ const { host } = parseDirectAddress(gateway.directAddress);
+ subjectAlternativeNames.push(net.isIP(host) ? { type: "ip", value: host } : { type: "dns", value: host });
+ }
+
const gatewayServerCertExtensions: x509.Extension[] = [
new x509.BasicConstraintsExtension(false),
await x509.AuthorityKeyIdentifierExtension.create(gatewayServerCaCert, false),
@@ -691,11 +758,7 @@ export const gatewayV2ServiceFactory = ({
true
),
new x509.ExtendedKeyUsageExtension([x509.ExtendedKeyUsage[CertExtendedKeyUsage.SERVER_AUTH]], true),
- new x509.SubjectAlternativeNameExtension([
- { type: "dns", value: "localhost" },
- { type: "ip", value: "127.0.0.1" },
- { type: "ip", value: "::1" }
- ])
+ new x509.SubjectAlternativeNameExtension(subjectAlternativeNames)
];
const gatewayServerSerialNumber = createSerialNumber();
@@ -711,26 +774,31 @@ export const gatewayV2ServiceFactory = ({
extensions: gatewayServerCertExtensions
});
- const relayCredentials = await relayService.getCredentialsForGateway({
- relayName,
- orgId,
- gatewayId: gateway.id,
- gatewayName: gateway.name
- });
+ const relayCredentials = relayName
+ ? await relayService.getCredentialsForGateway({
+ relayName,
+ orgId,
+ gatewayId: gateway.id,
+ gatewayName: gateway.name
+ })
+ : undefined;
return {
gatewayId: gateway.id,
- relayHost: relayCredentials.relayHost,
+ directAddress: gateway.directAddress ?? undefined,
+ relayHost: relayCredentials?.relayHost,
pki: {
serverCertificate: gatewayServerCertificate.toString("pem"),
serverPrivateKey: gatewayServerCertPrivateKey.export({ format: "pem", type: "pkcs8" }).toString(),
clientCertificateChain: constructPemChainFromCerts([gatewayClientCaCert, rootGatewayCaCert])
},
- ssh: {
- clientCertificate: relayCredentials.clientSshCert,
- clientPrivateKey: relayCredentials.clientSshPrivateKey,
- serverCAPublicKey: relayCredentials.serverCAPublicKey
- }
+ ssh: relayCredentials
+ ? {
+ clientCertificate: relayCredentials.clientSshCert,
+ clientPrivateKey: relayCredentials.clientSshPrivateKey,
+ serverCAPublicKey: relayCredentials.serverCAPublicKey
+ }
+ : undefined
};
};
@@ -740,6 +808,7 @@ export const gatewayV2ServiceFactory = ({
actorType,
actorAuthMethod,
relayName,
+ directAddress,
name
}: {
orgId: string;
@@ -747,8 +816,15 @@ export const gatewayV2ServiceFactory = ({
actorType: ActorType;
actorAuthMethod: ActorAuthMethod;
relayName?: string;
+ directAddress?: string;
name?: string;
}) => {
+ if (directAddress) {
+ if (getConfig().isCloud) {
+ throw new BadRequestError({ message: "Direct gateway connections are not available on Infisical Cloud" });
+ }
+ parseDirectAddress(directAddress);
+ }
const orgCAs = await $getOrgCAs(orgId);
// Enrollment-flow gateways authenticate with GATEWAY_ACCESS_TOKEN — the gateway row
@@ -764,17 +840,21 @@ export const gatewayV2ServiceFactory = ({
resolvedRelay = await relayDAL.findOne({ orgId, name: relayName });
if (!resolvedRelay) resolvedRelay = await relayDAL.findOne({ name: relayName, orgId: null });
if (!resolvedRelay) throw new NotFoundError({ message: `Relay ${relayName} not found` });
-
- if (resolvedRelay.id !== gateway.relayId) {
- await gatewayV2DAL.updateById(gateway.id, { relayId: resolvedRelay.id });
- }
- } else {
- if (!gateway.relayId) throw new NotFoundError({ message: "No relay associated with this gateway" });
+ } else if (!directAddress && gateway.relayId) {
resolvedRelay = await relayDAL.findById(gateway.relayId);
if (!resolvedRelay) throw new NotFoundError({ message: "No relay associated with this gateway" });
+ } else if (!directAddress) {
+ throw new NotFoundError({ message: "No connection transport associated with this gateway" });
}
- return $issueGatewayCerts({ orgId, orgCAs, relayName: resolvedRelay.name, gateway });
+ const registeredGateway = await gatewayV2DAL.updateById(gateway.id, {
+ directAddress: directAddress ?? null,
+ directHeartbeat: directAddress === gateway.directAddress ? gateway.directHeartbeat : null,
+ heartbeat: resolvedRelay?.id === gateway.relayId ? gateway.heartbeat : null,
+ relayId: resolvedRelay?.id ?? null
+ });
+
+ return $issueGatewayCerts({ orgId, orgCAs, relayName: resolvedRelay?.name, gateway: registeredGateway });
}
// Identity-based flow: upsert the gateway row then issue certs.
@@ -784,13 +864,16 @@ export const gatewayV2ServiceFactory = ({
throw new BadRequestError({ message: "Gateway name is required" });
}
- if (!relayName) {
- throw new BadRequestError({ message: "Relay name is required" });
+ if (!relayName && !directAddress) {
+ throw new BadRequestError({ message: "A relay name or direct address is required" });
}
- let relay: TRelays = await relayDAL.findOne({ orgId, name: relayName });
- if (!relay) relay = await relayDAL.findOne({ name: relayName, orgId: null });
- if (!relay) throw new NotFoundError({ message: `Relay ${relayName} not found` });
+ let relay: TRelays | undefined;
+ if (relayName) {
+ relay = await relayDAL.findOne({ orgId, name: relayName });
+ if (!relay) relay = await relayDAL.findOne({ name: relayName, orgId: null });
+ if (!relay) throw new NotFoundError({ message: `Relay ${relayName} not found` });
+ }
try {
const gateway = await gatewayV2DAL.transaction(async (tx) => {
@@ -800,7 +883,10 @@ export const gatewayV2ServiceFactory = ({
orgId,
name,
identityId: actorId,
- relayId: relay.id
+ relayId: relay?.id ?? null,
+ directAddress: directAddress ?? null,
+ directHeartbeat: null,
+ heartbeat: null
}
],
["identityId"],
@@ -810,7 +896,7 @@ export const gatewayV2ServiceFactory = ({
return upserted;
});
- return await $issueGatewayCerts({ orgId, orgCAs, relayName, gateway });
+ return await $issueGatewayCerts({ orgId, orgCAs, relayName: relay?.name, gateway });
} catch (err) {
if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
throw new BadRequestError({ message: "A gateway with this name already exists" });
@@ -820,93 +906,86 @@ export const gatewayV2ServiceFactory = ({
}
};
- const $checkGatewayHealth = async (gatewayId: string) => {
+ const $checkGatewayHealth = async (gatewayId: string, transport?: "direct" | "relay") => {
const gatewayV2ConnectionDetails = await getPlatformConnectionDetailsByGatewayId({
gatewayId,
targetHost: "health-check",
- targetPort: 443
+ targetPort: 443,
+ transport
});
if (!gatewayV2ConnectionDetails) {
throw new NotFoundError({ message: `Gateway connection details for gateway ${gatewayId} not found.` });
}
- let probeResponse: string | undefined;
- try {
- probeResponse = await withGatewayV2Proxy(
- async (port) => {
- return new Promise<string>((resolve, reject) => {
- const socket = new net.Socket();
- let isResolved = false;
- const chunks: Buffer[] = [];
-
- socket.setTimeout(10000);
-
- const cleanup = () => {
- if (!socket.destroyed) {
- socket.destroy();
- }
- };
-
- socket.on("data", (data: Buffer) => {
- chunks.push(data);
- const totalLength = chunks.reduce((sum, c) => sum + c.length, 0);
- if (totalLength > 1024) {
- if (!isResolved) {
- isResolved = true;
- cleanup();
- reject(new Error("Probe response exceeded 1KB limit"));
- }
- return;
- }
- const response = Buffer.concat(chunks).toString().trim();
- if ((response === "PONG" || response.includes("\n") || response.endsWith("}")) && !isResolved) {
- isResolved = true;
- cleanup();
- resolve(response);
- }
- });
+ const probeResponse = await withGatewayV2Proxy(
+ async (port) => {
+ return new Promise<string>((resolve, reject) => {
+ const socket = new net.Socket();
+ let isResolved = false;
+ const chunks: Buffer[] = [];
- socket.on("error", (err: Error) => {
- if (!isResolved) {
- isResolved = true;
- cleanup();
- reject(new Error(`TCP connection error: ${err.message}`));
- }
- });
+ socket.setTimeout(10000);
- socket.on("timeout", () => {
- if (!isResolved) {
- isResolved = true;
- cleanup();
- reject(new Error("TCP connection timeout"));
- }
- });
+ const cleanup = () => {
+ if (!socket.destroyed) {
+ socket.destroy();
+ }
+ };
- socket.on("close", () => {
+ socket.on("data", (data: Buffer) => {
+ chunks.push(data);
+ const totalLength = chunks.reduce((sum, c) => sum + c.length, 0);
+ if (totalLength > 1024) {
if (!isResolved) {
isResolved = true;
cleanup();
- reject(new Error("Connection closed without receiving response"));
+ reject(new Error("Probe response exceeded 1KB limit"));
}
- });
+ return;
+ }
+ const response = Buffer.concat(chunks).toString().trim();
+ if ((response === "PONG" || response.includes("\n") || response.endsWith("}")) && !isResolved) {
+ isResolved = true;
+ cleanup();
+ resolve(response);
+ }
+ });
- socket.connect(port, "localhost");
+ socket.on("error", (err: Error) => {
+ if (!isResolved) {
+ isResolved = true;
+ cleanup();
+ reject(new Error(`TCP connection error: ${err.message}`));
+ }
+ });
+
+ socket.on("timeout", () => {
+ if (!isResolved) {
+ isResolved = true;
+ cleanup();
+ reject(new Error("TCP connection timeout"));
+ }
});
- },
- {
- protocol: GatewayProxyProtocol.Health,
- ...gatewayV2ConnectionDetails
- }
- );
- } catch (err) {
- // Probe failed — gateway is unreachable. Mark TTL as 0 but preserve the last successful heartbeat timestamp.
- await gatewayV2DAL.updateById(gatewayId, { heartbeatTTL: 0 });
- throw err;
- }
+
+ socket.on("close", () => {
+ if (!isResolved) {
+ isResolved = true;
+ cleanup();
+ reject(new Error("Connection closed without receiving response"));
+ }
+ });
+
+ socket.connect(port, "localhost");
+ });
+ },
+ {
+ protocol: GatewayProxyProtocol.Health,
+ ...gatewayV2ConnectionDetails
+ }
+ );
if (!probeResponse) {
- await gatewayV2DAL.updateById(gatewayId, { heartbeatTTL: 0 });
throw new BadRequestError({ message: `Gateway ${gatewayId} is not reachable` });
}
@@ -926,10 +1005,29 @@ export const gatewayV2ServiceFactory = ({
}
}
- await gatewayV2DAL.updateById(gatewayId, {
- heartbeat: new Date(),
- heartbeatTTL
- });
+ await gatewayV2DAL.updateById(
+ gatewayId,
+ transport === "direct" ? { directHeartbeat: new Date(), heartbeatTTL } : { heartbeat: new Date(), heartbeatTTL }
+ );
+ };
+
+ const $checkAllGatewayTransports = async (gatewayId: string) => {
+ const gateway = await gatewayV2DAL.findById(gatewayId);
+ if (!gateway) throw new NotFoundError({ message: `Gateway ${gatewayId} not found` });
+
+ const transports: ("direct" | "relay")[] = [];
+ if (gateway.directAddress) transports.push("direct");
+ if (gateway.relayId) transports.push("relay");
+ if (transports.length === 0) {
+ throw new BadRequestError({ message: `Gateway ${gatewayId} has no configured connection transport` });
+ }
+
+ const results = await Promise.allSettled(transports.map((transport) => $checkGatewayHealth(gatewayId, transport)));
+ 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;
+ }
};
const triggerHeartbeat = async ({ orgPermission, id }: { orgPermission: OrgServiceActor; id: string }) => {
@@ -952,7 +1050,7 @@ export const gatewayV2ServiceFactory = ({
OrgPermissionSubjects.Gateway
);
- await $checkGatewayHealth(gateway.id);
+ await $checkAllGatewayTransports(gateway.id);
};
const heartbeat = async ({
@@ -970,7 +1068,7 @@ export const gatewayV2ServiceFactory = ({
throw new NotFoundError({ message: `Gateway ${orgPermission.id} not found.` });
}
await gatewayV2DAL.updateById(gateway.id, { capabilities: nextCapabilities });
- await $checkGatewayHealth(gateway.id);
+ await $checkAllGatewayTransports(gateway.id);
return;
}
@@ -986,7 +1084,7 @@ export const gatewayV2ServiceFactory = ({
}
await gatewayV2DAL.updateById(gateway.id, { capabilities: nextCapabilities });
- await $checkGatewayHealth(gateway.id);
+ await $checkAllGatewayTransports(gateway.id);
};
const reportMetrics = async ({
@@ -1309,13 +1407,21 @@ export const gatewayV2ServiceFactory = ({
orgId,
actorId,
actorType,
- relayName
+ relayName,
+ directAddress
}: {
orgId: string;
actorId: string;
actorType: ActorType;
relayName?: string;
+ directAddress?: string;
}) => {
+ if (directAddress) {
+ if (getConfig().isCloud) {
+ throw new BadRequestError({ message: "Direct gateway connections are not available on Infisical Cloud" });
+ }
+ parseDirectAddress(directAddress);
+ }
const orgCAs = await $getOrgCAs(orgId);
if (actorType === ActorType.GATEWAY) {
@@ -1329,18 +1435,21 @@ export const gatewayV2ServiceFactory = ({
resolvedRelay = await relayDAL.findOne({ orgId, name: relayName });
if (!resolvedRelay) resolvedRelay = await relayDAL.findOne({ name: relayName, orgId: null });
if (!resolvedRelay) throw new NotFoundError({ message: `Relay ${relayName} not found` });
-
- // Persist the relay change so future restarts use the new relay
- if (resolvedRelay.id !== gateway.relayId) {
- await gatewayV2DAL.updateById(gateway.id, { relayId: resolvedRelay.id });
- }
- } else {
- if (!gateway.relayId) throw new NotFoundError({ message: "No relay associated with this gateway" });
+ } else if (!directAddress && gateway.relayId) {
resolvedRelay = await relayDAL.findById(gateway.relayId);
if (!resolvedRelay) throw new NotFoundError({ message: "No relay associated with this gateway" });
+ } else if (!directAddress) {
+ throw new NotFoundError({ message: "No connection transport associated with this gateway" });
}
- return $issueGatewayCerts({ orgId, orgCAs, relayName: resolvedRelay.name, gateway });
+ const registeredGateway = await gatewayV2DAL.updateById(gateway.id, {
+ directAddress: directAddress ?? null,
+ directHeartbeat: directAddress === gateway.directAddress ? gateway.directHeartbeat : null,
+ heartbeat: resolvedRelay?.id === gateway.relayId ? gateway.heartbeat : null,
+ relayId: resolvedRelay?.id ?? null
+ });
+
+ return $issueGatewayCerts({ orgId, orgCAs, relayName: resolvedRelay?.name, gateway: registeredGateway });
}
throw new BadRequestError({ message: "Invalid actor type for gateway connect" });
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-types.ts b/backend/src/ee/services/gateway-v2/gateway-v2-types.ts
index 351cc24702..c11dbfe227 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-types.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-types.ts
@@ -1,12 +1,13 @@
export type TGatewayV2ConnectionDetails = {
gatewayId: string;
- relayHost: string;
+ directAddress?: string;
+ relayHost?: string;
gateway: {
clientCertificate: string;
clientPrivateKey: string;
serverCertificateChain: string;
};
- relay: {
+ relay?: {
clientCertificate: string;
clientPrivateKey: string;
serverCertificateChain: string;
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 88054eb5bc..d3762ffb94 100644
--- a/backend/src/ee/services/pam-session/pam-session-fns.ts
+++ b/backend/src/ee/services/pam-session/pam-session-fns.ts
@@ -3,7 +3,7 @@ import net from "net";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { GatewayProxyProtocol } from "@app/lib/gateway/types";
-import { createGatewayConnection, createRelayConnection, destroyGatewayTunnel } from "@app/lib/gateway-v2/gateway-v2";
+import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { logger } from "@app/lib/logger";
import { ActorType } from "@app/services/auth/auth-type";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
@@ -103,9 +103,6 @@ export const sendPamSessionCancellationSignal = ({
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
}) => {
void (async () => {
- let relayConn: net.Socket | null = null;
- let cancelConn: net.Socket | null = null;
- const tunnelId = sessionId;
try {
const certs = await gatewayV2Service.getPAMConnectionDetails({
gatewayId,
@@ -122,26 +119,19 @@ export const sendPamSessionCancellationSignal = ({
);
return;
}
- relayConn = await createRelayConnection({
- relayHost: certs.relayHost,
- clientCertificate: certs.relay.clientCertificate,
- clientPrivateKey: certs.relay.clientPrivateKey,
- serverCertificateChain: certs.relay.serverCertificateChain,
- tunnelId
- });
- cancelConn = await createGatewayConnection(
- relayConn,
- certs.gateway,
- GatewayProxyProtocol.PamSessionCancellation,
- tunnelId
+ await withGatewayV2Proxy(
+ (port) =>
+ new Promise<void>((resolve, reject) => {
+ const socket = net.connect(port, "127.0.0.1", () => {
+ socket.end();
+ resolve();
+ });
+ socket.on("error", reject);
+ }),
+ { ...certs, protocol: GatewayProxyProtocol.PamSessionCancellation }
);
- cancelConn.end();
} catch (err) {
logger.error({ sessionId, err }, `Session [sessionId=${sessionId}] termination ALPN signal failed (best-effort)`);
- } finally {
- // end() leaves the inner TLS session reading the gateway's close_notify through relayConn, so
- // the transport must not be destroyed first.
- destroyGatewayTunnel({ relayConn, gatewayConn: cancelConn });
}
})();
};
diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.ts
index 1923c55af8..dca3ae3b5b 100644
--- a/backend/src/ee/services/pam-session/pam-session-service.ts
+++ b/backend/src/ee/services/pam-session/pam-session-service.ts
@@ -441,7 +441,8 @@ export const pamSessionServiceFactory = ({
mfaSessionId,
tokenVersionId,
accessMethod = PamAccessMethod.Cli,
- targetHost
+ targetHost,
+ supportedTransports
}: {
path: string;
projectId: string;
@@ -456,6 +457,7 @@ export const pamSessionServiceFactory = ({
tokenVersionId?: string;
accessMethod?: PamAccessMethod;
targetHost?: string;
+ supportedTransports?: ("relay" | "direct")[];
}) => {
const account = await resolveAccountByPath(projectId, path);
@@ -711,7 +713,8 @@ export const pamSessionServiceFactory = ({
id: actor.actorId,
type: actor.actor,
name: user?.email ?? actorName
- }
+ },
+ supportedTransports
});
if (!certs) {
@@ -759,9 +762,10 @@ export const pamSessionServiceFactory = ({
sessionDurationMs,
accessMethod: PamAccessMethod.Cli,
relayHost: certs.relayHost,
- relayClientCertificate: certs.relay.clientCertificate,
- relayClientPrivateKey: certs.relay.clientPrivateKey,
- relayServerCertificateChain: certs.relay.serverCertificateChain,
+ directAddress: certs.directAddress,
+ relayClientCertificate: certs.relay?.clientCertificate,
+ relayClientPrivateKey: certs.relay?.clientPrivateKey,
+ relayServerCertificateChain: certs.relay?.serverCertificateChain,
gatewayClientCertificate: certs.gateway.clientCertificate,
gatewayClientPrivateKey: certs.gateway.clientPrivateKey,
gatewayServerCertificateChain: certs.gateway.serverCertificateChain
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 60f2028b21..e7b5e44169 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
@@ -1,4 +1,3 @@
-import crypto from "node:crypto";
import net from "node:net";
import type WebSocket from "ws";
@@ -6,6 +5,7 @@ import type WebSocket from "ws";
import { AuditLogInfo, EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { TGatewayV2ConnectionDetails } from "@app/ee/services/gateway-v2/gateway-v2-types";
import { PamAccountType } from "@app/ee/services/pam/pam-enums";
import { enforceMfa } from "@app/ee/services/pam/pam-mfa";
import { resolveAccessControls } from "@app/ee/services/pam/pam-policies";
@@ -13,12 +13,7 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissio
import { ResourcePermissionPamResourceActions } from "@app/ee/services/permission/resource-permission";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { GatewayProxyProtocol } from "@app/lib/gateway/types";
-import {
- createGatewayConnection,
- createRelayConnection,
- destroyGatewayTunnel,
- setupRelayServer
-} from "@app/lib/gateway-v2/gateway-v2";
+import { setupRelayServer, withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { logger } from "@app/lib/logger";
import { ActorType } from "@app/services/auth/auth-type";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
@@ -327,11 +322,7 @@ export const pamWebAccessServiceFactory = ({
let cleanedUp = false;
let handlerResult: TSessionHandlerResult | null = null;
let relayServer: { port: number; cleanup: () => Promise<void> } | null = null;
- let relayCerts: {
- relay: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string };
- gateway: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string };
- relayHost: string;
- } | null = null;
+ let relayCerts: TGatewayV2ConnectionDetails | null = null;
let expiryTimer: ReturnType<typeof setTimeout> | null = null;
let pingInterval: ReturnType<typeof setInterval> | null = null;
let idleTimer: ReturnType<typeof setTimeout> | null = null;
@@ -404,30 +395,20 @@ export const pamWebAccessServiceFactory = ({
const certs = relayCerts;
relayCerts = null;
void (async () => {
- let relayConn: net.Socket | null = null;
- let cancelConn: net.Socket | null = null;
- const tunnelId = crypto.randomBytes(4).toString("hex");
try {
- relayConn = await createRelayConnection({
- relayHost: certs.relayHost,
- clientCertificate: certs.relay.clientCertificate,
- clientPrivateKey: certs.relay.clientPrivateKey,
- serverCertificateChain: certs.relay.serverCertificateChain,
- tunnelId
- });
- cancelConn = await createGatewayConnection(
- relayConn,
- certs.gateway,
- GatewayProxyProtocol.PamSessionCancellation,
- tunnelId
+ await withGatewayV2Proxy(
+ (port) =>
+ new Promise<void>((resolve, reject) => {
+ const cancelSocket = net.connect(port, "127.0.0.1", () => {
+ cancelSocket.end();
+ resolve();
+ });
+ cancelSocket.on("error", reject);
+ }),
+ { ...certs, protocol: GatewayProxyProtocol.PamSessionCancellation }
);
- cancelConn.end();
} catch (err) {
logger.debug(err, "Session cancellation signal failed (best-effort)");
- } finally {
- // end() leaves the inner TLS session reading the gateway's close_notify through
- // relayConn, so the transport must not be destroyed first.
- destroyGatewayTunnel({ relayConn, gatewayConn: cancelConn });
}
})();
}
@@ -588,11 +569,7 @@ export const pamWebAccessServiceFactory = ({
await pamSessionDAL.updateById(createdSession.id, { gatewayId: attempt.gatewayId });
}
- relayCerts = {
- relayHost: certs.relayHost,
- relay: certs.relay,
- gateway: certs.gateway
- };
+ relayCerts = certs;
const isNearSessionExpiry = () => Date.now() >= expiresAt.getTime() - 30_000;
diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.ts
index b63472b074..be489212f9 100644
--- a/backend/src/lib/gateway-v2/gateway-v2.ts
+++ b/backend/src/lib/gateway-v2/gateway-v2.ts
@@ -127,7 +127,9 @@ export const createGatewayConnection = async (
relayConn: net.Socket,
gateway: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string },
protocol: GatewayProxyProtocol,
- tunnelId?: string
+ tunnelId?: string,
+ serverName = "localhost",
+ timeoutMs = 120000
): Promise<net.Socket> => {
const appCfg = getConfig();
@@ -154,6 +156,7 @@ export const createGatewayConnection = async (
minVersion: "TLSv1.2",
maxVersion: "TLSv1.3",
rejectUnauthorized: true,
+ servername: serverName,
ALPNProtocols: protocolToAlpn[protocol],
checkServerIdentity: appCfg.isDevelopmentMode ? () => undefined : tls.checkServerIdentity
};
@@ -181,7 +184,7 @@ export const createGatewayConnection = async (
reject(new Error(`Failed to establish gateway mTLS: ${err.message}`));
});
- gatewaySocket.setTimeout(120000);
+ gatewaySocket.setTimeout(timeoutMs);
gatewaySocket.on("timeout", () => {
destroyGatewayTunnel({ gatewayConn: gatewaySocket, tunnelId, trigger: "gatewayTimeout" });
reject(new Error("Gateway connection timeout"));
@@ -197,6 +200,7 @@ export const createGatewayConnection = async (
export const setupRelayServer = async ({
gatewayId,
protocol,
+ directAddress,
relayHost,
gateway,
relay,
@@ -206,9 +210,10 @@ export const setupRelayServer = async ({
}: {
gatewayId: string;
protocol: GatewayProxyProtocol;
- relayHost: string;
+ directAddress?: string;
+ relayHost?: string;
gateway: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string };
- relay: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string };
+ relay?: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string };
httpsAgent?: https.Agent;
longLived?: boolean;
/**
@@ -236,26 +241,48 @@ export const setupRelayServer = async ({
const openUpstream = async (): Promise<TUpstream> => {
const tunnelId = crypto.randomBytes(4).toString("hex");
-
- // Stage 1: Connect to relay with TLS
let relayConn: net.Socket;
+ let gatewayServerName = "localhost";
try {
- relayConn = await createRelayConnection({
- relayHost,
- clientCertificate: relay.clientCertificate,
- clientPrivateKey: relay.clientPrivateKey,
- serverCertificateChain: relay.serverCertificateChain,
- tunnelId
- });
+ 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
+ });
+ }
} catch (err) {
- tunnelLog(tunnelId, "relay connect failed", ` [err=${err instanceof Error ? err.message : String(err)}]`);
+ tunnelLog(
+ tunnelId,
+ directAddress ? "direct connect failed" : "relay connect failed",
+ ` [err=${err instanceof Error ? err.message : String(err)}]`
+ );
throw err;
}
let gatewayConn: net.Socket;
try {
// Stage 2: Establish mTLS connection to gateway through the relay
- gatewayConn = await createGatewayConnection(relayConn, gateway, protocol, tunnelId);
+ gatewayConn = await createGatewayConnection(
+ relayConn,
+ gateway,
+ protocol,
+ tunnelId,
+ gatewayServerName,
+ directAddress ? 3000 : undefined
+ );
} catch (err) {
tunnelLog(tunnelId, "gateway mTLS failed", ` [err=${err instanceof Error ? err.message : String(err)}]`);
destroyGatewayTunnel({ relayConn, tunnelId, trigger: "gatewayHandshakeFailed" });
@@ -463,13 +490,14 @@ export const withGatewayV2Proxy = async <T>(
longLived?: boolean;
} & TGatewayV2ConnectionDetails
): Promise<T> => {
- const { gatewayId, protocol, relayHost, gateway, relay, httpsAgent, longLived } = options;
+ const { gatewayId, protocol, directAddress, relayHost, gateway, relay, httpsAgent, longLived } = options;
let relayServer;
try {
relayServer = await setupRelayServer({
gatewayId,
protocol,
+ directAddress,
relayHost,
gateway,
relay,
diff --git a/frontend/src/hooks/api/gateways-v2/types.ts b/frontend/src/hooks/api/gateways-v2/types.ts
index ac56b51b02..a5f7446d31 100644
--- a/frontend/src/hooks/api/gateways-v2/types.ts
+++ b/frontend/src/hooks/api/gateways-v2/types.ts
@@ -1,11 +1,14 @@
export type TGatewayV2 = {
id: string;
identityId: string | null;
+ relayId: string | null;
name: string;
createdAt: string;
updatedAt: string;
heartbeat: string | null;
heartbeatTTL: number | null;
+ directAddress: string | null;
+ directHeartbeat: string | null;
canRevoke: boolean;
connectedResourcesCount: number;
identity: {
diff --git a/frontend/src/hooks/api/gateways-v2/utils.ts b/frontend/src/hooks/api/gateways-v2/utils.ts
index a88483a669..d1bbf215ee 100644
--- a/frontend/src/hooks/api/gateways-v2/utils.ts
+++ b/frontend/src/hooks/api/gateways-v2/utils.ts
@@ -2,13 +2,15 @@ export const HEARTBEAT_BUFFER_SECONDS = 30;
export const isGatewayHealthy = (gateway: {
heartbeat?: string | null;
+ directAddress?: string | null;
+ directHeartbeat?: string | null;
heartbeatTTL?: number | null;
}): boolean => {
- if (!gateway.heartbeat) return false;
+ const heartbeat = gateway.directAddress ? gateway.directHeartbeat : gateway.heartbeat;
+ if (!heartbeat) return false;
if (!gateway.heartbeatTTL) return false;
return (
- new Date(gateway.heartbeat).getTime() +
- (gateway.heartbeatTTL + HEARTBEAT_BUFFER_SECONDS) * 1000 >
+ new Date(heartbeat).getTime() + (gateway.heartbeatTTL + HEARTBEAT_BUFFER_SECONDS) * 1000 >
Date.now()
);
};
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/GatewayDetailsByIDPage.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/GatewayDetailsByIDPage.tsx
index 218b4470d7..d2685187e3 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/GatewayDetailsByIDPage.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/GatewayDetailsByIDPage.tsx
@@ -60,6 +60,7 @@ const Page = () => {
<GatewayDeploySection
gatewayId={gatewayId}
gatewayName={gateway.name}
+ directAddress={gateway.directAddress}
authMethod={gateway.authMethod}
/>
<GatewayConnectedResourcesSection gatewayId={gatewayId} />
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 2a0dd00779..58624d3ede 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/AwsStartCommandDialog.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/AwsStartCommandDialog.tsx
@@ -16,11 +16,18 @@ import { useGetRelays } from "@app/hooks/api/relays/queries";
type Props = {
gatewayId: string;
gatewayName: string;
+ isDirect: boolean;
+ listenAddress: string;
};
const AUTO_RELAY_OPTION = { id: "_auto", name: "Auto Select Relay" };
-export const AwsStartCommandContent = ({ gatewayId, gatewayName }: Props) => {
+export const AwsStartCommandContent = ({
+ gatewayId,
+ gatewayName,
+ isDirect,
+ listenAddress
+}: Props) => {
const { protocol, hostname, port } = window.location;
const portSuffix = port && port !== "80" ? `:${port}` : "";
const siteURL = `${protocol}//${hostname}${portSuffix}`;
@@ -31,14 +38,20 @@ export const AwsStartCommandContent = ({ gatewayId, gatewayName }: Props) => {
const resolvedRelayName = relay.id === "_auto" ? "" : relay.name;
const cliCommand = useMemo(() => {
- const relayPart = resolvedRelayName ? ` --target-relay-name=${resolvedRelayName}` : "";
- return `infisical gateway start ${gatewayName} --enroll-method=aws --gateway-id=${gatewayId}${relayPart} --domain=${siteURL}`;
- }, [gatewayName, gatewayId, resolvedRelayName, siteURL]);
+ const relayPart = resolvedRelayName ? ` --relay=${resolvedRelayName}` : "";
+ const directPart = isDirect
+ ? ` --listen-address=${listenAddress.trim() || "<gateway-address>:8443"}`
+ : "";
+ return `infisical gateway start ${gatewayName} --enroll-method=aws --gateway-id=${gatewayId}${relayPart}${directPart} --domain=${siteURL}`;
+ }, [gatewayName, gatewayId, isDirect, listenAddress, resolvedRelayName, siteURL]);
const systemdInstallCommand = useMemo(() => {
- const relayPart = resolvedRelayName ? ` --target-relay-name=${resolvedRelayName}` : "";
- return `sudo infisical gateway systemd install ${gatewayName} --enroll-method=aws --gateway-id=${gatewayId}${relayPart} --domain=${siteURL}`;
- }, [gatewayName, gatewayId, resolvedRelayName, siteURL]);
+ const relayPart = resolvedRelayName ? ` --relay=${resolvedRelayName}` : "";
+ const directPart = isDirect
+ ? ` --listen-address=${listenAddress.trim() || "<gateway-address>:8443"}`
+ : "";
+ return `sudo infisical gateway systemd install ${gatewayName} --enroll-method=aws --gateway-id=${gatewayId}${relayPart}${directPart} --domain=${siteURL}`;
+ }, [gatewayName, gatewayId, isDirect, listenAddress, resolvedRelayName, siteURL]);
const startServiceCommand = `sudo systemctl start ${gatewayName}`;
@@ -51,34 +64,36 @@ export const AwsStartCommandContent = ({ gatewayId, gatewayName }: Props) => {
<CodeBlock value={systemdInstallCommand} label="Install service" />
<CodeBlock value={startServiceCommand} label="Start service" />
</TabsContent>
- <Field>
- <Select
- value={relay.id}
- onValueChange={(id) =>
- setRelay(
- [AUTO_RELAY_OPTION, ...(relays || [])].find((item) => item.id === id) ||
- AUTO_RELAY_OPTION
- )
- }
- disabled={isRelaysLoading}
- >
- <SelectTrigger className="w-full">
- <SelectValue placeholder="Select relay" />
- </SelectTrigger>
- <SelectContent>
- {[AUTO_RELAY_OPTION, ...(relays || [])].map((item) => (
- <SelectItem key={item.id} value={item.id}>
- {item.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- {relay.id !== "_auto" && (
- <FieldDescription>
- * Auto Select chooses a healthy relay and fails over if needed.
- </FieldDescription>
- )}
- </Field>
+ {!isDirect && (
+ <Field>
+ <Select
+ value={relay.id}
+ onValueChange={(id: string) =>
+ setRelay(
+ [AUTO_RELAY_OPTION, ...(relays || [])].find((item) => item.id === id) ||
+ AUTO_RELAY_OPTION
+ )
+ }
+ disabled={isRelaysLoading}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select relay" />
+ </SelectTrigger>
+ <SelectContent>
+ {[AUTO_RELAY_OPTION, ...(relays || [])].map((item) => (
+ <SelectItem key={item.id} value={item.id}>
+ {item.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {relay.id !== "_auto" && (
+ <FieldDescription>
+ * Auto Select chooses a healthy relay and fails over if needed.
+ </FieldDescription>
+ )}
+ </Field>
+ )}
<p className="text-xs text-muted">
Requires AWS credentials matching the configured allowlist.
</p>
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 62db73de88..5d64f5d5aa 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/EnrollmentTokenDialog.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/EnrollmentTokenDialog.tsx
@@ -18,6 +18,8 @@ type Props = {
gatewayName: string;
enrollmentToken: string;
expiresAt: string;
+ isDirect: boolean;
+ listenAddress: string;
onCommandDirtyChange: (isDirty: boolean) => void;
};
@@ -40,6 +42,8 @@ export const EnrollmentTokenContent = ({
gatewayName,
enrollmentToken,
expiresAt,
+ isDirect,
+ listenAddress,
onCommandDirtyChange
}: Props) => {
const { protocol, hostname, port } = window.location;
@@ -73,14 +77,20 @@ export const EnrollmentTokenContent = ({
const isExpired = expiryLabel === "Expired";
const cliCommand = useMemo(() => {
- const relayPart = resolvedRelayName ? ` --target-relay-name=${resolvedRelayName}` : "";
- return `infisical gateway start ${gatewayName} --enroll-method=token --token=${enrollmentToken}${relayPart} --domain=${siteURL}`;
- }, [gatewayName, enrollmentToken, resolvedRelayName, siteURL]);
+ const relayPart = resolvedRelayName ? ` --relay=${resolvedRelayName}` : "";
+ const directPart = isDirect
+ ? ` --listen-address=${listenAddress.trim() || "<gateway-address>:8443"}`
+ : "";
+ return `infisical gateway start ${gatewayName} --enroll-method=token --token=${enrollmentToken}${relayPart}${directPart} --domain=${siteURL}`;
+ }, [gatewayName, enrollmentToken, isDirect, listenAddress, resolvedRelayName, siteURL]);
const systemdInstallCommand = useMemo(() => {
- const relayPart = resolvedRelayName ? ` --target-relay-name=${resolvedRelayName}` : "";
- return `sudo infisical gateway systemd install ${gatewayName} --enroll-method=token --token=${enrollmentToken}${relayPart} --domain=${siteURL}`;
- }, [gatewayName, enrollmentToken, resolvedRelayName, siteURL]);
+ const relayPart = resolvedRelayName ? ` --relay=${resolvedRelayName}` : "";
+ const directPart = isDirect
+ ? ` --listen-address=${listenAddress.trim() || "<gateway-address>:8443"}`
+ : "";
+ return `sudo infisical gateway systemd install ${gatewayName} --enroll-method=token --token=${enrollmentToken}${relayPart}${directPart} --domain=${siteURL}`;
+ }, [gatewayName, enrollmentToken, isDirect, listenAddress, resolvedRelayName, siteURL]);
const startServiceCommand = `sudo systemctl start ${gatewayName}`;
const commandLabel = (
@@ -112,34 +122,36 @@ export const EnrollmentTokenContent = ({
/>
<CodeBlock value={startServiceCommand} label="Start service" />
</TabsContent>
- <Field>
- <Select
- value={relay.id}
- onValueChange={(id) =>
- setRelay(
- [AUTO_RELAY_OPTION, ...(relays || [])].find((item) => item.id === id) ||
- AUTO_RELAY_OPTION
- )
- }
- disabled={isRelaysLoading}
- >
- <SelectTrigger className="w-full">
- <SelectValue placeholder="Select relay" />
- </SelectTrigger>
- <SelectContent>
- {[AUTO_RELAY_OPTION, ...(relays || [])].map((item) => (
- <SelectItem key={item.id} value={item.id}>
- {item.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- {relay.id !== "_auto" && (
- <FieldDescription>
- * Auto Select chooses a healthy relay and fails over if needed.
- </FieldDescription>
- )}
- </Field>
+ {!isDirect && (
+ <Field>
+ <Select
+ value={relay.id}
+ onValueChange={(id: string) =>
+ setRelay(
+ [AUTO_RELAY_OPTION, ...(relays || [])].find((item) => item.id === id) ||
+ AUTO_RELAY_OPTION
+ )
+ }
+ disabled={isRelaysLoading}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select relay" />
+ </SelectTrigger>
+ <SelectContent>
+ {[AUTO_RELAY_OPTION, ...(relays || [])].map((item) => (
+ <SelectItem key={item.id} value={item.id}>
+ {item.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {relay.id !== "_auto" && (
+ <FieldDescription>
+ * Auto Select chooses a healthy relay and fails over if needed.
+ </FieldDescription>
+ )}
+ </Field>
+ )}
</div>
);
};
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 04d46c0b13..6dbfceeb42 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/KubernetesStartCommandDialog.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/KubernetesStartCommandDialog.tsx
@@ -16,11 +16,26 @@ import { useGetRelays } from "@app/hooks/api/relays/queries";
type Props = {
gatewayId: string;
gatewayName: string;
+ isDirect: boolean;
+ listenAddress: string;
};
const AUTO_RELAY_OPTION = { id: "_auto", name: "Auto Select Relay" };
-export const KubernetesStartCommandContent = ({ gatewayId, gatewayName }: Props) => {
+const getListenPort = (address: string) => {
+ try {
+ return new URL(`tcp://${address}`).port || "8443";
+ } catch {
+ return "8443";
+ }
+};
+
+export const KubernetesStartCommandContent = ({
+ gatewayId,
+ gatewayName,
+ isDirect,
+ listenAddress
+}: Props) => {
const { protocol, hostname, port } = window.location;
const portSuffix = port && port !== "80" ? `:${port}` : "";
const siteURL = `${protocol}//${hostname}${portSuffix}`;
@@ -31,6 +46,15 @@ export const KubernetesStartCommandContent = ({ gatewayId, gatewayName }: Props)
const resolvedRelayName = relay.id === "_auto" ? "" : relay.name;
const helmCommand = useMemo(() => {
+ const advertisedAddress = listenAddress.trim() || "<gateway-address>:8443";
+ const directPart = isDirect
+ ? [
+ " \\",
+ ` --set gateway.listenAddress=${advertisedAddress}`,
+ " \\",
+ ` --set service.port=${getListenPort(advertisedAddress)}`
+ ].join("\n")
+ : "";
const relayPart = resolvedRelayName
? ` \\\n --set gateway.relayName=${resolvedRelayName}`
: "";
@@ -40,13 +64,16 @@ helm install infisical-gateway infisical/infisical-gateway \\
--set gateway.name=${gatewayName} \\
--set gateway.domain=${siteURL} \\
--set gateway.enrollment.method=kubernetes \\
- --set gateway.enrollment.kubernetes.gatewayId=${gatewayId}${relayPart}`;
- }, [gatewayName, gatewayId, resolvedRelayName, siteURL]);
+ --set gateway.enrollment.kubernetes.gatewayId=${gatewayId}${relayPart}${directPart}`;
+ }, [gatewayName, gatewayId, isDirect, listenAddress, resolvedRelayName, siteURL]);
const cliCommand = useMemo(() => {
- const relayPart = resolvedRelayName ? ` --target-relay-name=${resolvedRelayName}` : "";
- return `infisical gateway start ${gatewayName} --enroll-method=kubernetes --gateway-id=${gatewayId}${relayPart} --domain=${siteURL}`;
- }, [gatewayName, gatewayId, resolvedRelayName, siteURL]);
+ const relayPart = resolvedRelayName ? ` --relay=${resolvedRelayName}` : "";
+ const directPart = isDirect
+ ? ` --listen-address=${listenAddress.trim() || "<gateway-address>:8443"}`
+ : "";
+ return `infisical gateway start ${gatewayName} --enroll-method=kubernetes --gateway-id=${gatewayId}${relayPart}${directPart} --domain=${siteURL}`;
+ }, [gatewayName, gatewayId, isDirect, listenAddress, resolvedRelayName, siteURL]);
return (
<div className="min-w-0 space-y-4">
@@ -60,34 +87,36 @@ helm install infisical-gateway infisical/infisical-gateway \\
must be reachable from the pod, so a loopback address will not work.
</p>
</TabsContent>
- <Field>
- <Select
- value={relay.id}
- onValueChange={(id) =>
- setRelay(
- [AUTO_RELAY_OPTION, ...(relays || [])].find((item) => item.id === id) ||
- AUTO_RELAY_OPTION
- )
- }
- disabled={isRelaysLoading}
- >
- <SelectTrigger className="w-full">
- <SelectValue placeholder="Select relay" />
- </SelectTrigger>
- <SelectContent>
- {[AUTO_RELAY_OPTION, ...(relays || [])].map((item) => (
- <SelectItem key={item.id} value={item.id}>
- {item.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- {relay.id !== "_auto" && (
- <FieldDescription>
- * Auto Select chooses a healthy relay and fails over if needed.
- </FieldDescription>
- )}
- </Field>
+ {!isDirect && (
+ <Field>
+ <Select
+ value={relay.id}
+ onValueChange={(id: string) =>
+ setRelay(
+ [AUTO_RELAY_OPTION, ...(relays || [])].find((item) => item.id === id) ||
+ AUTO_RELAY_OPTION
+ )
+ }
+ disabled={isRelaysLoading}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select relay" />
+ </SelectTrigger>
+ <SelectContent>
+ {[AUTO_RELAY_OPTION, ...(relays || [])].map((item) => (
+ <SelectItem key={item.id} value={item.id}>
+ {item.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {relay.id !== "_auto" && (
+ <FieldDescription>
+ * Auto Select chooses a healthy relay and fails over if needed.
+ </FieldDescription>
+ )}
+ </Field>
+ )}
<p className="text-xs text-muted">
The gateway must run in a namespace and service account matching the configured allowlists.
</p>
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 498138cd36..f11d04ac0a 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDeploySection/GatewayDeploySection.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDeploySection/GatewayDeploySection.tsx
@@ -14,6 +14,15 @@ import {
CardHeader,
CardTitle,
DocumentationLinkBadge,
+ Field,
+ FieldDescription,
+ FieldLabel,
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
Tabs,
TabsList,
TabsTrigger
@@ -23,6 +32,7 @@ import {
OrgGatewayPermissionActions,
OrgPermissionSubjects
} from "@app/context/OrgPermissionContext/types";
+import { isInfisicalCloud } from "@app/helpers/platform";
import { useMintGatewayToken } from "@app/hooks/api/gateways-v2";
import { GatewayAuthMethodView, TGatewayEnrollmentToken } from "@app/hooks/api/gateways-v2/types";
@@ -33,11 +43,22 @@ import { KubernetesStartCommandContent } from "../GatewayAuthMethod/KubernetesSt
type Props = {
gatewayId: string;
gatewayName: string;
+ directAddress?: string | null;
authMethod: GatewayAuthMethodView;
};
-export const GatewayDeploySection = ({ gatewayId, gatewayName, authMethod }: Props) => {
+export const GatewayDeploySection = ({
+ gatewayId,
+ gatewayName,
+ directAddress,
+ authMethod
+}: Props) => {
+ const isCloud = isInfisicalCloud();
const isKubernetes = authMethod.method === "kubernetes";
+ const [connectionMode, setConnectionMode] = useState<"relay" | "direct">(
+ isCloud ? "relay" : "direct"
+ );
+ const [listenAddress, setListenAddress] = useState(directAddress ?? "");
const [deploymentMethod, setDeploymentMethod] = useState("");
const [mintedEnrollment, setMintedEnrollment] = useState<
(TGatewayEnrollmentToken & { gatewayId: string }) | null
@@ -112,12 +133,55 @@ export const GatewayDeploySection = ({ gatewayId, gatewayName, authMethod }: Pro
</Alert>
) : (
<>
+ {!isCloud && (
+ <Field>
+ <FieldLabel htmlFor="gateway-connection-mode">Connection Mode</FieldLabel>
+ <Select
+ 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>
+ </Field>
+ )}
+
+ {connectionMode === "direct" && (
+ <Field>
+ <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"
+ />
+ <FieldDescription>
+ Enter the stable address Infisical will use to reach this gateway.
+ </FieldDescription>
+ </Field>
+ )}
+
{authMethod.method === "aws" && (
- <AwsStartCommandContent gatewayId={gatewayId} gatewayName={gatewayName} />
+ <AwsStartCommandContent
+ gatewayId={gatewayId}
+ gatewayName={gatewayName}
+ isDirect={connectionMode === "direct"}
+ listenAddress={listenAddress}
+ />
)}
{isKubernetes && (
- <KubernetesStartCommandContent gatewayId={gatewayId} gatewayName={gatewayName} />
+ <KubernetesStartCommandContent
+ gatewayId={gatewayId}
+ gatewayName={gatewayName}
+ isDirect={connectionMode === "direct"}
+ listenAddress={listenAddress}
+ />
)}
{authMethod.method === "token" && !enrollment && (
@@ -139,6 +203,8 @@ export const GatewayDeploySection = ({ gatewayId, gatewayName, authMethod }: Pro
gatewayName={gatewayName}
enrollmentToken={enrollment.token}
expiresAt={enrollment.expiresAt}
+ isDirect={connectionMode === "direct"}
+ listenAddress={listenAddress}
onCommandDirtyChange={setIsCommandDirty}
/>
<Button
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 a8fb70021d..d8764e5406 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx
@@ -40,7 +40,13 @@ import {
} from "../../../components/NetworkingAuthMethodForm";
const HealthBadge = ({ gateway }: { gateway: TGatewayV2 }) => {
- if (!gateway.heartbeat && !gateway.heartbeatTTL) {
+ const heartbeat = gateway.directAddress ? gateway.directHeartbeat : gateway.heartbeat;
+ if (
+ !heartbeat &&
+ gateway.heartbeatTTL === null &&
+ gateway.directAddress === null &&
+ gateway.relayId === null
+ ) {
return <Badge variant="warning">Unregistered</Badge>;
}
if (isGatewayHealthy(gateway)) {
@@ -59,6 +65,12 @@ export const GatewayDetailsCard = ({ gateway }: { gateway: TGatewayV2WithAuthMet
const { authMethod } = gateway;
const isIdentityGateway = authMethod.method === "identity";
+ const effectiveHeartbeat = gateway.directAddress ? gateway.directHeartbeat : gateway.heartbeat;
+ const connection = gateway.directAddress
+ ? `${gateway.relayId ? "Direct + Relay" : "Direct"} (${gateway.directAddress})`
+ : gateway.relayId
+ ? "Relay"
+ : "Not configured";
return (
<Card className="w-full">
@@ -96,17 +108,21 @@ export const GatewayDetailsCard = ({ gateway }: { gateway: TGatewayV2WithAuthMet
<HealthBadge gateway={gateway} />
</DetailValue>
</Detail>
+ <Detail>
+ <DetailLabel>Connection</DetailLabel>
+ <DetailValue>{connection}</DetailValue>
+ </Detail>
<Detail>
<DetailLabel>Last Seen</DetailLabel>
<DetailValue>
- {gateway.heartbeat ? (
+ {effectiveHeartbeat ? (
<Tooltip>
<TooltipTrigger asChild>
<span className="cursor-default">
- {format(new Date(gateway.heartbeat), "PPpp")}
+ {format(new Date(effectiveHeartbeat), "PPpp")}
</span>
</TooltipTrigger>
- <TooltipContent>{new Date(gateway.heartbeat).toUTCString()}</TooltipContent>
+ <TooltipContent>{new Date(effectiveHeartbeat).toUTCString()}</TooltipContent>
</Tooltip>
) : (
<span className="text-muted">—</span>
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayPageHeader/GatewayPageHeader.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayPageHeader/GatewayPageHeader.tsx
index 998ebfeda5..0c327b2f91 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayPageHeader/GatewayPageHeader.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayPageHeader/GatewayPageHeader.tsx
@@ -74,7 +74,9 @@ export const GatewayPageHeader = ({ gateway, orgId }: { gateway: TGatewayV2; org
}
};
- const isRegistered = Boolean(gateway.heartbeat || gateway.heartbeatTTL);
+ const isRegistered = Boolean(
+ gateway.directAddress || gateway.relayId || gateway.heartbeat || gateway.heartbeatTTL !== null
+ );
const { canRevoke } = gateway;
return (
diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx
index b2bae70388..ccfee02586 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx
@@ -389,6 +389,9 @@ export const GatewayTab = withPermission(
<TableCell className="whitespace-nowrap">
<GatewayHealthStatus
heartbeat={"heartbeat" in el ? el.heartbeat : null}
+ relayId={"relayId" in el ? el.relayId : null}
+ directAddress={"directAddress" in el ? el.directAddress : null}
+ directHeartbeat={"directHeartbeat" in el ? el.directHeartbeat : null}
heartbeatTTL={"heartbeatTTL" in el ? el.heartbeatTTL : null}
/>
</TableCell>
@@ -406,12 +409,18 @@ export const GatewayTab = withPermission(
<CopyIcon />
Copy ID
</DropdownMenuItem>
- {!el.isV1 && (!!el.heartbeat || !!el.heartbeatTTL) && (
- <DropdownMenuItem onClick={() => handleTriggerHealthCheck(el.id)}>
- <HeartPulseIcon />
- Trigger Health Check
- </DropdownMenuItem>
- )}
+ {!el.isV1 &&
+ (!!el.directAddress ||
+ !!el.relayId ||
+ !!el.heartbeat ||
+ el.heartbeatTTL !== null) && (
+ <DropdownMenuItem
+ onClick={() => handleTriggerHealthCheck(el.id)}
+ >
+ <HeartPulseIcon />
+ Trigger Health Check
+ </DropdownMenuItem>
+ )}
{el.isV1 && (
<OrgPermissionCan
I={OrgGatewayPermissionActions.EditGateways}
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 c15debc146..1fb5abcb61 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayHealthStatus.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayHealthStatus.tsx
@@ -6,12 +6,19 @@ import { isGatewayHealthy } from "@app/hooks/api/gateways-v2/utils";
export const GatewayHealthStatus = ({
heartbeat,
+ relayId,
+ directAddress,
+ directHeartbeat,
heartbeatTTL
}: {
heartbeat?: string | null;
+ relayId?: string | null;
+ directAddress?: string | null;
+ directHeartbeat?: string | null;
heartbeatTTL?: number | null;
}) => {
- if (!heartbeat && !heartbeatTTL) {
+ const effectiveHeartbeat = directAddress ? directHeartbeat : heartbeat;
+ if (!effectiveHeartbeat && heartbeatTTL === null && !directAddress && !relayId) {
return (
<Badge variant="warning" iconPosition="left">
<CircleDashedIcon />
@@ -20,8 +27,8 @@ export const GatewayHealthStatus = ({
);
}
- const heartbeatDate = heartbeat ? new Date(heartbeat) : null;
- const isHealthy = isGatewayHealthy({ heartbeat, heartbeatTTL });
+ const heartbeatDate = effectiveHeartbeat ? new Date(effectiveHeartbeat) : null;
+ const isHealthy = isGatewayHealthy({ heartbeat, directAddress, directHeartbeat, heartbeatTTL });
return (
<Tooltip>
diff --git a/helm-charts/infisical-gateway/ci/default-values.yaml b/helm-charts/infisical-gateway/ci/default-values.yaml
index a496b33aa1..736f1711bb 100644
--- a/helm-charts/infisical-gateway/ci/default-values.yaml
+++ b/helm-charts/infisical-gateway/ci/default-values.yaml
@@ -4,4 +4,4 @@
gateway:
name: ci-test-gateway
extraArgs:
- - --target-relay-name=ci-test-relay
+ - --relay=ci-test-relay
diff --git a/helm-charts/infisical-gateway/templates/deployment.yaml b/helm-charts/infisical-gateway/templates/deployment.yaml
index f4e7090aaf..28891146ae 100644
--- a/helm-charts/infisical-gateway/templates/deployment.yaml
+++ b/helm-charts/infisical-gateway/templates/deployment.yaml
@@ -122,12 +122,21 @@ spec:
{{- end }}
{{- end }}
{{- if .Values.gateway.relayName }}
- - --target-relay-name={{ .Values.gateway.relayName }}
+ - --relay={{ .Values.gateway.relayName }}
+ {{- end }}
+ {{- if .Values.gateway.listenAddress }}
+ - --listen-address={{ .Values.gateway.listenAddress }}
{{- end }}
- --pam-session-recording-path={{ $sessionPath }}
{{- with .Values.extraArgs }}
{{- toYaml . | nindent 12 }}
{{- end }}
+ {{- if .Values.gateway.listenAddress }}
+ ports:
+ - name: http
+ containerPort: {{ .Values.service.port }}
+ protocol: TCP
+ {{- end }}
volumeMounts:
{{- if $usePVC }}
- name: gateway-data
diff --git a/helm-charts/infisical-gateway/values.yaml b/helm-charts/infisical-gateway/values.yaml
index 3ebe7eef78..495177bb8e 100644
--- a/helm-charts/infisical-gateway/values.yaml
+++ b/helm-charts/infisical-gateway/values.yaml
@@ -54,6 +54,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).