Skip to content

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

feat(pam-web-access): fail over to another pool member on session start

bernie-g351c4c0b5030
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 6eb001472a..23050dfa2b 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
@@ -60,10 +60,10 @@ type TPamWebAccessServiceFactoryDep = {
tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser">;
pamSessionDAL: Pick<
TPamSessionDALFactory,
- "create" | "endSessionById" | "activateSession" | "countActiveWebSessions" | "endExpiredWebSessions"
+ "create" | "endSessionById" | "activateSession" | "countActiveWebSessions" | "endExpiredWebSessions" | "updateById"
>;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
- gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId" | "runWithPoolFailover">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
userDAL: Pick<TUserDALFactory, "findById">;
mfaSessionService: Pick<
@@ -507,22 +507,62 @@ export const pamWebAccessServiceFactory = ({
selectedHost: targetHost
});
- const certs = await gatewayV2Service.getPAMConnectionDetails({
- gatewayId: effectiveGatewayId,
- sessionId: session.id,
- accountType: handlerEntry.gatewayAccountType,
- host: targetHost,
- port: gatewayTarget.port,
- duration: sessionDurationMs,
- actorMetadata: {
- id: userId,
- type: ActorType.USER,
- name: user?.email ?? ""
+ const createdSession = session;
+ const isRdp = account.accountType === PamAccountType.Windows || account.accountType === PamAccountType.WindowsAd;
+
+ // Certs are minted per gateway, so each attempt has to re-mint. `eager` opens the tunnel
+ // during setup, so an unreachable gateway fails here where another member can still be tried.
+ const attempt = await gatewayPoolService.runWithPoolFailover(
+ {
+ gatewayId: account.gatewayId ?? account.templateGatewayId,
+ poolId: account.gatewayPoolId ?? account.templateGatewayPoolId
+ },
+ async (gatewayId) => {
+ const attemptCerts = await gatewayV2Service.getPAMConnectionDetails({
+ gatewayId,
+ sessionId: createdSession.id,
+ accountType: handlerEntry.gatewayAccountType,
+ host: targetHost,
+ port: gatewayTarget.port,
+ duration: sessionDurationMs,
+ actorMetadata: {
+ id: userId,
+ type: ActorType.USER,
+ name: user?.email ?? ""
+ }
+ });
+
+ if (!attemptCerts) {
+ throw new BadRequestError({ message: "Failed to obtain gateway connection details" });
+ }
+
+ return {
+ certs: attemptCerts,
+ server: await setupRelayServer({
+ protocol: isRdp ? GatewayProxyProtocol.PamRdpBrowser : GatewayProxyProtocol.Pam,
+ ...attemptCerts,
+ longLived: true,
+ eager: true
+ })
+ };
}
- });
+ );
+
+ const { certs } = attempt.result;
+ relayServer = attempt.result.server;
+
+ // The tunnel is open from here rather than from whenever the session handler first dials, so
+ // a socket that closed during setup has to be caught: its "close" fired before the listener
+ // further down was attached, and nothing else would release the channel until session expiry.
+ if (socket.readyState !== socket.OPEN) {
+ await cleanup();
+ return;
+ }
- if (!certs) {
- throw new BadRequestError({ message: "Failed to obtain gateway connection details" });
+ // The row was written against the first pick. Cancellation and credential fetch look the
+ // session up by gateway, so it has to name the one that actually answered.
+ if (attempt.gatewayId !== effectiveGatewayId) {
+ await pamSessionDAL.updateById(createdSession.id, { gatewayId: attempt.gatewayId });
}
relayCerts = {
@@ -531,14 +571,6 @@ export const pamWebAccessServiceFactory = ({
gateway: certs.gateway
};
- const isRdp = account.accountType === PamAccountType.Windows || account.accountType === PamAccountType.WindowsAd;
-
- relayServer = await setupRelayServer({
- protocol: isRdp ? GatewayProxyProtocol.PamRdpBrowser : GatewayProxyProtocol.Pam,
- ...certs,
- longLived: true
- });
-
const isNearSessionExpiry = () => Date.now() >= expiresAt.getTime() - 30_000;
const boundSendMessage = (msg: TWebSocketServerMessage) => sendMessage(socket, msg);
diff --git a/backend/src/lib/gateway-v2/gateway-v2.test.ts b/backend/src/lib/gateway-v2/gateway-v2.test.ts
new file mode 100644
index 0000000000..09550040ec
--- /dev/null
+++ b/backend/src/lib/gateway-v2/gateway-v2.test.ts
@@ -0,0 +1,303 @@
+import net from "node:net";
+import tls from "node:tls";
+
+import forge from "node-forge";
+
+import { GatewayProxyProtocol } from "@app/lib/gateway/types";
+
+import { setupRelayServer } from "./gateway-v2";
+
+const tracker = vi.hoisted(() => ({
+ channelOpened: vi.fn(),
+ channelClosed: vi.fn(),
+ markSuspect: vi.fn()
+}));
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }
+}));
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ isDevelopmentMode: true })
+}));
+
+vi.mock("./gateway-load-tracker", () => ({
+ getGatewayLoadTracker: () => tracker
+}));
+
+// Real relays are addressed by hostname and always reach the gateway on 8443, so the production
+// implementation resolves the host and never sees a port. The fake relay needs an ephemeral one.
+vi.mock("@app/ee/services/dynamic-secret/dynamic-secret-fns", () => ({
+ verifyHostInputValidity: ({ host }: { host: string }) => Promise.resolve([host.split(":")[0]])
+}));
+
+const GATEWAY_ID = "11111111-1111-1111-1111-111111111111";
+
+const freePort = async () =>
+ new Promise<number>((resolve, reject) => {
+ const probe = net.createServer();
+ probe.on("error", reject);
+ probe.listen(0, "127.0.0.1", () => {
+ const address = probe.address();
+ if (!address || typeof address === "string") {
+ probe.close();
+ reject(new Error("no port"));
+ return;
+ }
+ const { port } = address;
+ probe.close(() => resolve(port));
+ });
+ });
+
+// One keypair reused by every certificate: the test only needs a chain that validates, and forge's
+// RSA generation is slow enough that three of them dominates the runtime of the whole file.
+const keys = forge.pki.rsa.generateKeyPair(2048);
+
+type TAltName = { type: number; value?: string; ip?: string };
+
+const issue = ({ subject, isCa, altNames }: { subject: string; isCa?: boolean; altNames?: TAltName[] }) => {
+ const cert = forge.pki.createCertificate();
+ cert.publicKey = keys.publicKey;
+ cert.serialNumber = "01";
+ cert.validity.notBefore = new Date(Date.now() - 60_000);
+ cert.validity.notAfter = new Date(Date.now() + 3_600_000);
+ const attrs = [{ name: "commonName", value: subject }];
+ cert.setSubject(attrs);
+ cert.setIssuer([{ name: "commonName", value: "test-ca" }]);
+ const extensions: Record<string, unknown>[] = [{ name: "basicConstraints", cA: Boolean(isCa) }];
+ if (altNames) extensions.push({ name: "subjectAltName", altNames });
+ cert.setExtensions(extensions);
+ cert.sign(keys.privateKey, forge.md.sha256.create());
+ return forge.pki.certificateToPem(cert);
+};
+
+const keyPem = forge.pki.privateKeyToPem(keys.privateKey);
+const caPem = issue({ subject: "test-ca", isCa: true });
+
+type TFakeRelay = {
+ relayHost: string;
+ tunnelsOpened: () => number;
+ tunnelsClosed: () => number;
+ close: () => Promise<void>;
+};
+
+/**
+ * Stands in for the relay plus the gateway behind it: an outer TLS listener whose accepted socket
+ * carries a second, inner TLS server. That nesting is the part under test, because a tunnel is only
+ * "open" from the gateway's point of view once the inner handshake completes.
+ */
+const startFakeRelay = async (): Promise<TFakeRelay> => {
+ const port = await freePort();
+ const relayHost = `127.0.0.1:${port}`;
+ const serverCert = issue({
+ subject: "relay",
+ altNames: [
+ { type: 2, value: relayHost },
+ { type: 2, value: "127.0.0.1" },
+ { type: 7, ip: "127.0.0.1" }
+ ]
+ });
+
+ let opened = 0;
+ let closed = 0;
+ const live = new Set<tls.TLSSocket>();
+
+ const server = tls.createServer(
+ { key: keyPem, cert: serverCert, ca: caPem, requestCert: true, rejectUnauthorized: false },
+ (outer) => {
+ live.add(outer);
+ outer.on("close", () => live.delete(outer));
+ const inner = new tls.TLSSocket(outer, {
+ isServer: true,
+ key: keyPem,
+ cert: serverCert,
+ ca: caPem,
+ requestCert: true,
+ rejectUnauthorized: false,
+ ALPNProtocols: ["infisical-tcp-proxy"]
+ });
+ inner.on("secure", () => {
+ opened += 1;
+ });
+ // Echo, so a claimed tunnel can be shown to still carry traffic.
+ inner.on("data", (chunk: Buffer) => inner.write(chunk));
+ inner.on("error", () => {});
+ inner.on("close", () => {
+ closed += 1;
+ });
+ outer.on("error", () => {});
+ }
+ );
+
+ await new Promise<void>((resolve, reject) => {
+ server.on("error", reject);
+ server.listen(port, "127.0.0.1", resolve);
+ });
+
+ return {
+ relayHost,
+ tunnelsOpened: () => opened,
+ tunnelsClosed: () => closed,
+ close: () =>
+ new Promise<void>((resolve) => {
+ for (const socket of live) socket.destroy();
+ live.clear();
+ server.close(() => resolve());
+ })
+ };
+};
+
+const clientCertPem = issue({ subject: "client" });
+
+const argsFor = (relayHost: string) => ({
+ gatewayId: GATEWAY_ID,
+ protocol: GatewayProxyProtocol.Tcp,
+ relayHost,
+ gateway: { clientCertificate: clientCertPem, clientPrivateKey: keyPem, serverCertificateChain: caPem },
+ relay: { clientCertificate: clientCertPem, clientPrivateKey: keyPem, serverCertificateChain: caPem }
+});
+
+const connectAndEcho = (port: number) =>
+ new Promise<string>((resolve, reject) => {
+ const socket: net.Socket = net.connect({ host: "127.0.0.1", port }, () => socket.write("ping"));
+ socket.on("data", (chunk) => {
+ resolve(chunk.toString());
+ socket.end();
+ });
+ socket.on("error", reject);
+ socket.setTimeout(5000, () => {
+ socket.destroy();
+ reject(new Error("echo timed out"));
+ });
+ });
+
+const waitFor = async (predicate: () => boolean) => {
+ for (let i = 0; i < 100; i += 1) {
+ if (predicate()) return;
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((resolve) => {
+ setTimeout(resolve, 20);
+ });
+ }
+ throw new Error("condition never became true");
+};
+
+// Teardown is driven by socket "close" events, so a test that ends the moment its assertion passes
+// can leak a release into the next test's counters.
+const drainChannels = (count: number) => waitFor(() => tracker.channelClosed.mock.calls.length === count);
+
+describe("setupRelayServer", () => {
+ beforeEach(() => {
+ tracker.channelOpened.mockClear();
+ tracker.channelClosed.mockClear();
+ tracker.markSuspect.mockClear();
+ });
+
+ describe("against an unreachable gateway", () => {
+ // Nothing is listening here, so any dial fails.
+ const args = {
+ gatewayId: GATEWAY_ID,
+ protocol: GatewayProxyProtocol.Tcp,
+ relayHost: "127.0.0.1:1",
+ gateway: { clientCertificate: "c", clientPrivateKey: "k", serverCertificateChain: "chain" },
+ relay: { clientCertificate: "c", clientPrivateKey: "k", serverCertificateChain: "chain" }
+ };
+
+ test("resolves when not eager, because the dial is deferred to the first client", async () => {
+ const server = await setupRelayServer(args);
+ expect(server.port).toBeGreaterThan(0);
+ expect(server.hasEstablishedChannel()).toBe(false);
+ await server.cleanup();
+ });
+
+ test("rejects when eager, which is what gives pool failover something to catch", async () => {
+ await expect(setupRelayServer({ ...args, eager: true })).rejects.toThrow();
+ });
+
+ test("reports the failure as a transport error, so it is safe to retry elsewhere", async () => {
+ await expect(setupRelayServer({ ...args, eager: true })).rejects.toMatchObject({
+ name: "BadRequest",
+ gatewayId: GATEWAY_ID
+ });
+ });
+
+ test("counts no channel for a tunnel that never opened", async () => {
+ await expect(setupRelayServer({ ...args, eager: true })).rejects.toThrow();
+ expect(tracker.channelOpened).not.toHaveBeenCalled();
+ expect(tracker.markSuspect).toHaveBeenCalledWith(GATEWAY_ID);
+ });
+ });
+
+ describe("against a reachable gateway", () => {
+ let relay: TFakeRelay;
+
+ beforeEach(async () => {
+ relay = await startFakeRelay();
+ });
+
+ afterEach(async () => {
+ await relay.close();
+ });
+
+ test("does not touch the gateway until a client connects when not eager", async () => {
+ const server = await setupRelayServer(argsFor(relay.relayHost));
+ expect(relay.tunnelsOpened()).toBe(0);
+ expect(server.hasEstablishedChannel()).toBe(false);
+ await server.cleanup();
+ });
+
+ test("opens the tunnel during setup when eager", async () => {
+ const server = await setupRelayServer({ ...argsFor(relay.relayHost), eager: true, longLived: true });
+ await waitFor(() => relay.tunnelsOpened() === 1);
+ expect(server.hasEstablishedChannel()).toBe(true);
+ expect(tracker.channelOpened).toHaveBeenCalledTimes(1);
+
+ await server.cleanup();
+ await drainChannels(1);
+ });
+
+ test("hands the tunnel it already opened to the first client instead of dialing again", async () => {
+ const server = await setupRelayServer({ ...argsFor(relay.relayHost), eager: true, longLived: true });
+ await waitFor(() => relay.tunnelsOpened() === 1);
+
+ // The reused tunnel has to still carry traffic; a probe-and-drop would fail here.
+ await expect(connectAndEcho(server.port)).resolves.toBe("ping");
+ expect(relay.tunnelsOpened()).toBe(1);
+ expect(tracker.channelOpened).toHaveBeenCalledTimes(1);
+
+ await server.cleanup();
+ await drainChannels(1);
+ });
+
+ test("dials a fresh tunnel for the second client", async () => {
+ const server = await setupRelayServer({ ...argsFor(relay.relayHost), eager: true, longLived: true });
+
+ await expect(connectAndEcho(server.port)).resolves.toBe("ping");
+ await expect(connectAndEcho(server.port)).resolves.toBe("ping");
+
+ await waitFor(() => relay.tunnelsOpened() === 2);
+ expect(tracker.channelOpened).toHaveBeenCalledTimes(2);
+
+ await server.cleanup();
+ await drainChannels(2);
+ });
+
+ test("releases the tunnel and its channel count when no client ever claims it", async () => {
+ const server = await setupRelayServer({ ...argsFor(relay.relayHost), eager: true, longLived: true });
+ await waitFor(() => relay.tunnelsOpened() === 1);
+
+ await server.cleanup();
+
+ await waitFor(() => relay.tunnelsClosed() === 1);
+ await drainChannels(1);
+ });
+
+ test("releases the channel count once when a claimed tunnel closes", async () => {
+ const server = await setupRelayServer({ ...argsFor(relay.relayHost), eager: true, longLived: true });
+ await expect(connectAndEcho(server.port)).resolves.toBe("ping");
+ await server.cleanup();
+
+ await drainChannels(1);
+ });
+ });
+});
diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.ts
index ade0dce1eb..f05e4a02a0 100644
--- a/backend/src/lib/gateway-v2/gateway-v2.ts
+++ b/backend/src/lib/gateway-v2/gateway-v2.ts
@@ -157,7 +157,8 @@ export const setupRelayServer = async ({
gateway,
relay,
httpsAgent,
- longLived
+ longLived,
+ eager
}: {
gatewayId: string;
protocol: GatewayProxyProtocol;
@@ -166,11 +167,111 @@ export const setupRelayServer = async ({
relay: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string };
httpsAgent?: https.Agent;
longLived?: boolean;
+ /**
+ * Opens the tunnel during setup and hands it to the first client instead of dialing lazily.
+ * Callers that give the port to a long-lived session need this: otherwise setup succeeds against
+ * a dead gateway and the failure only surfaces once a user is attached, far too late to pick
+ * another pool member. The connection is kept and reused rather than probed and dropped, so the
+ * gateway sees one channel that becomes the session, not a session that opens and immediately dies.
+ */
+ eager?: boolean;
}): Promise<IGatewayRelayServer> => {
const relayErrorMsg: string[] = [];
let establishedChannel = false;
const loadTracker = getGatewayLoadTracker();
+ type TUpstream = {
+ relayConn: net.Socket;
+ gatewayConn: net.Socket;
+ releaseChannel: () => void;
+ };
+
+ const openUpstream = async (): Promise<TUpstream> => {
+ // Stage 1: Connect to relay with TLS
+ const relayConn = await createRelayConnection({
+ relayHost,
+ clientCertificate: relay.clientCertificate,
+ clientPrivateKey: relay.clientPrivateKey,
+ serverCertificateChain: relay.serverCertificateChain
+ });
+
+ let gatewayConn: net.Socket;
+ try {
+ // Stage 2: Establish mTLS connection to gateway through the relay
+ gatewayConn = await createGatewayConnection(relayConn, gateway, protocol);
+ } catch (err) {
+ relayConn.destroy();
+ throw err;
+ }
+
+ // Marked as soon as both handshakes complete: the gateway dials the target the moment it
+ // accepts the channel, so the target may already have been reached even if we abandon this
+ // connection now. Treating the attempt as replayable after that point is what this prevents.
+ establishedChannel = true;
+ 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.
+ relayConn.setTimeout(0);
+ gatewayConn.setTimeout(0);
+
+ // Enable TCP keep-alive probes every 30s to detect dead connections
+ // without terminating idle-but-alive ones.
+ relayConn.setKeepAlive(true, 30000);
+ gatewayConn.setKeepAlive(true, 30000);
+ }
+
+ // Send protocol-specific configuration for HTTP requests
+ if (protocol === GatewayProxyProtocol.Http) {
+ if (httpsAgent) {
+ const agentOptions = httpsAgent.options;
+ if (agentOptions && agentOptions.ca) {
+ const caCert = Array.isArray(agentOptions.ca) ? agentOptions.ca.join("\n") : agentOptions.ca;
+ const caB64 = Buffer.from(caCert as string).toString("base64");
+ const rejectUnauthorized = agentOptions.rejectUnauthorized !== false;
+
+ const configCommand = `CONFIG ca=${caB64} verify=${rejectUnauthorized}\n`;
+ gatewayConn.write(Buffer.from(configCommand));
+ } else {
+ // Send empty config to signal end of configuration
+ gatewayConn.write(Buffer.from("CONFIG\n"));
+ }
+ } else {
+ // Send empty config to signal end of configuration
+ gatewayConn.write(Buffer.from("CONFIG\n"));
+ }
+ }
+
+ // Counted per channel rather than per caller operation: one operation can open many channels
+ // (a pooled SQL client, an HTTP client without keepalive, a discovery sweep), and it is the
+ // channel that costs the gateway a goroutine.
+ loadTracker?.channelOpened(gatewayId);
+ let released = false;
+
+ return {
+ relayConn,
+ gatewayConn,
+ releaseChannel: () => {
+ if (released) return;
+ released = true;
+ loadTracker?.channelClosed(gatewayId);
+ }
+ };
+ };
+
+ // Holds the tunnel opened during eager setup until a client claims it.
+ let pendingUpstream: TUpstream | null = null;
+
+ const discardPendingUpstream = () => {
+ if (!pendingUpstream) return;
+ const { relayConn, gatewayConn, releaseChannel } = pendingUpstream;
+ pendingUpstream = null;
+ releaseChannel();
+ relayConn.destroy();
+ gatewayConn.destroy();
+ };
+
return new Promise((resolve, reject) => {
const server = net.createServer();
@@ -180,73 +281,20 @@ export const setupRelayServer = async ({
clientConn.setKeepAlive(true, 30000);
clientConn.setNoDelay(true);
- // Stage 1: Connect to relay with TLS
- const relayConn = await createRelayConnection({
- relayHost,
- clientCertificate: relay.clientCertificate,
- clientPrivateKey: relay.clientPrivateKey,
- serverCertificateChain: relay.serverCertificateChain
- });
+ const claimed = pendingUpstream;
+ pendingUpstream = null;
+ const { relayConn, gatewayConn, releaseChannel } = claimed ?? (await openUpstream());
- // Stage 2: Establish mTLS connection to gateway through the relay
- const gatewayConn = await createGatewayConnection(relayConn, gateway, protocol);
-
- // The caller may have given up while the two handshakes were in flight. Its "close" event
- // has already fired by now, so attaching the teardown listeners below would never run and
- // the channel would stay counted for the life of the pod.
+ // The caller may have given up while the handshakes were in flight. Its "close" event has
+ // already fired by now, so attaching the teardown listeners below would never run and the
+ // channel would stay counted for the life of the pod.
if (clientConn.destroyed) {
+ releaseChannel();
relayConn.destroy();
gatewayConn.destroy();
return;
}
- establishedChannel = true;
- 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.
- relayConn.setTimeout(0);
- gatewayConn.setTimeout(0);
-
- // Enable TCP keep-alive probes every 30s to detect dead connections
- // without terminating idle-but-alive ones.
- relayConn.setKeepAlive(true, 30000);
- gatewayConn.setKeepAlive(true, 30000);
- }
-
- // Send protocol-specific configuration for HTTP requests
- if (protocol === GatewayProxyProtocol.Http) {
- if (httpsAgent) {
- const agentOptions = httpsAgent.options;
- if (agentOptions && agentOptions.ca) {
- const caCert = Array.isArray(agentOptions.ca) ? agentOptions.ca.join("\n") : agentOptions.ca;
- const caB64 = Buffer.from(caCert as string).toString("base64");
- const rejectUnauthorized = agentOptions.rejectUnauthorized !== false;
-
- const configCommand = `CONFIG ca=${caB64} verify=${rejectUnauthorized}\n`;
- gatewayConn.write(Buffer.from(configCommand));
- } else {
- // Send empty config to signal end of configuration
- gatewayConn.write(Buffer.from("CONFIG\n"));
- }
- } else {
- // Send empty config to signal end of configuration
- gatewayConn.write(Buffer.from("CONFIG\n"));
- }
- }
-
- // Counted here rather than around the caller's operation: one operation can open many
- // channels (a pooled SQL client, an HTTP client without keepalive, a discovery sweep), and
- // it is the channel that costs the gateway a goroutine.
- loadTracker?.channelOpened(gatewayId);
- let released = false;
- const releaseChannel = () => {
- if (released) return;
- released = true;
- loadTracker?.channelClosed(gatewayId);
- };
-
const destroyAll = () => {
releaseChannel();
clientConn.destroy();
@@ -286,10 +334,11 @@ export const setupRelayServer = async ({
return;
}
- resolve({
+ const relayServer: IGatewayRelayServer = {
server,
port: address.port,
cleanup: async () => {
+ discardPendingUpstream();
try {
server.close();
} catch (err) {
@@ -298,7 +347,41 @@ export const setupRelayServer = async ({
},
getRelayError: () => relayErrorMsg.join(","),
hasEstablishedChannel: () => establishedChannel
- });
+ };
+
+ if (!eager) {
+ resolve(relayServer);
+ return;
+ }
+
+ void (async () => {
+ try {
+ const upstream = await openUpstream();
+ pendingUpstream = upstream;
+
+ // If the gateway or relay drops the tunnel before anyone claims it, fall back to dialing
+ // on demand rather than handing the session a socket that is already dead.
+ const dropIfUnclaimed = () => {
+ if (pendingUpstream === upstream) discardPendingUpstream();
+ };
+ upstream.relayConn.once("close", dropIfUnclaimed);
+ upstream.gatewayConn.once("close", dropIfUnclaimed);
+ upstream.relayConn.once("error", dropIfUnclaimed);
+ upstream.gatewayConn.once("error", dropIfUnclaimed);
+
+ resolve(relayServer);
+ } catch (err) {
+ await relayServer.cleanup();
+ markAttemptTransportFailure();
+ await getGatewayLoadTracker()?.markSuspect(gatewayId);
+ reject(
+ new GatewayTransportError({
+ message: err instanceof Error ? err.message : String(err),
+ gatewayId
+ })
+ );
+ }
+ })();
});
});
};