mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-12-02 07:11:00 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
36fbc8b85b |
No files matched your search
@@ -12,6 +12,18 @@ const fail = (code, message) => new PluginRpcError(RPC_ERRORS[code], message);
|
||||
const DEFAULT_IDLE_TTL_MS = 120_000;
|
||||
const DEFAULT_MAX_CONCURRENT_PER_RUNTIME = 16;
|
||||
const DEFAULT_MAX_CONCURRENT_TOTAL = 64;
|
||||
// Tighter than interactive SSH defaults (20s TCP / 120s auth) so background
|
||||
// plugin dials fail with a clear timeout before the ~30s plugin RPC deadline
|
||||
// (interactive prompts such as host-key/passphrase/2FA still share that RPC budget).
|
||||
const DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS = 8_000;
|
||||
const DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS = 8_000;
|
||||
const DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS = 18_000;
|
||||
// resolveSshConnectionTimeouts() ignores values below 1000ms and falls back to 20s/120s.
|
||||
const MIN_SSH_CONNECT_STAGE_TIMEOUT_MS = 1_000;
|
||||
|
||||
function positiveMs(value, fallback) {
|
||||
return Number.isFinite(value) && value > 0 ? Math.round(value) : fallback;
|
||||
}
|
||||
|
||||
let vendorDetectorPromise = null;
|
||||
function loadVendorDetector() {
|
||||
@@ -41,13 +53,25 @@ class PluginHostSshExecTransport {
|
||||
this.idleTtlMs = options.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
|
||||
this.maxConcurrentPerRuntime = options.maxConcurrentPerRuntime ?? DEFAULT_MAX_CONCURRENT_PER_RUNTIME;
|
||||
this.maxConcurrentTotal = options.maxConcurrentTotal ?? DEFAULT_MAX_CONCURRENT_TOTAL;
|
||||
this.sshTcpConnectTimeoutMs = positiveMs(
|
||||
options.sshTcpConnectTimeoutMs,
|
||||
DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS,
|
||||
);
|
||||
this.sshAuthReadyTimeoutMs = positiveMs(
|
||||
options.sshAuthReadyTimeoutMs,
|
||||
DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS,
|
||||
);
|
||||
this.sshDialEnvelopeMs = positiveMs(
|
||||
options.sshDialEnvelopeMs,
|
||||
DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS,
|
||||
);
|
||||
this.clock = options.clock ?? Date.now;
|
||||
this.isLocked = options.isLocked ?? (() => false);
|
||||
this.getSender = options.getSender ?? (() => null);
|
||||
|
||||
/** @type {Map<string, object>} `${runtimeId}\0${hostId}` -> pooled entry */
|
||||
this.connections = new Map();
|
||||
/** @type {Map<string, Promise<object>>} `${runtimeId}\0${hostId}` -> in-flight dial */
|
||||
/** @type {Map<string, object>} `${runtimeId}\0${hostId}` -> in-flight dial record */
|
||||
this.pendingDials = new Map();
|
||||
/** @type {Set<{ controller: AbortController, runtimeId: string, pluginId: string, hostId: string }>} */
|
||||
this.activeExecs = new Set();
|
||||
@@ -69,10 +93,165 @@ class PluginHostSshExecTransport {
|
||||
#isEntryHealthy(entry) {
|
||||
if (!entry || entry.closed || !entry.conn) return false;
|
||||
const sock = entry.conn._sock;
|
||||
if (sock && (sock.destroyed || sock.writableEnded)) return false;
|
||||
if (sock && (
|
||||
sock.destroyed
|
||||
|| sock.writableEnded
|
||||
|| sock.readableEnded
|
||||
|| sock.writableFinished
|
||||
|| sock.writable === false
|
||||
|| sock.readyState === "closed"
|
||||
|| sock.readyState === "readOnly"
|
||||
)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#isDeadlineAbort(signal) {
|
||||
if (!signal?.aborted) return false;
|
||||
const reason = signal.reason;
|
||||
if (!reason) return false;
|
||||
if (reason.code === RPC_ERRORS.deadlineExceeded) return true;
|
||||
const message = typeof reason === "string" ? reason : String(reason?.message ?? "");
|
||||
return /plugin (?:request|notification) deadline exceeded/i.test(message);
|
||||
}
|
||||
|
||||
#isConnectTimeoutError(err) {
|
||||
if (!err) return false;
|
||||
if (err?.code === "ETIMEDOUT" || err?.code === RPC_ERRORS.deadlineExceeded) return true;
|
||||
const message = typeof err === "string" ? err : String(err?.message ?? "");
|
||||
return /\btimed?\s*out\b|\btimeout\b/i.test(message);
|
||||
}
|
||||
|
||||
#callerAbortError(signal, fallbackMessage = "SSH connection was cancelled") {
|
||||
if (signal?.reason instanceof PluginRpcError) return signal.reason;
|
||||
if (this.#isDeadlineAbort(signal)) {
|
||||
return fail("deadlineExceeded", "Plugin request deadline exceeded");
|
||||
}
|
||||
return fail("cancelled", fallbackMessage);
|
||||
}
|
||||
|
||||
#dialAbortError(dialRecord) {
|
||||
if (dialRecord.timedOut) {
|
||||
return fail("deadlineExceeded", "SSH connection timed out");
|
||||
}
|
||||
const reason = dialRecord.controller.signal.reason;
|
||||
if (reason instanceof PluginRpcError) return reason;
|
||||
if (dialRecord.cancelledByWaiters) {
|
||||
return fail("cancelled", "SSH connection was cancelled");
|
||||
}
|
||||
return fail("unavailable", "Host SSH execution is unavailable");
|
||||
}
|
||||
|
||||
#isStopConfirmed(result) {
|
||||
return result?.success === true;
|
||||
}
|
||||
|
||||
#clearStopRetryTimer(dialRecord) {
|
||||
if (dialRecord?.stopRetryTimer) {
|
||||
clearTimeout(dialRecord.stopRetryTimer);
|
||||
dialRecord.stopRetryTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
#scheduleStopRetry(dialRecord) {
|
||||
if (
|
||||
!dialRecord
|
||||
|| !dialRecord.tunnelId
|
||||
|| !dialRecord.stopRequested
|
||||
|| dialRecord.stopConfirmed
|
||||
|| dialRecord.dialDone
|
||||
|| dialRecord.settled
|
||||
|| dialRecord.stopRetryTimer
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const maxAttempts = Math.min(200, Math.max(25, Math.ceil(this.sshDialEnvelopeMs / 100)));
|
||||
const attempt = dialRecord.stopRetryAttempts ?? 0;
|
||||
if (attempt >= maxAttempts) {
|
||||
return;
|
||||
}
|
||||
const delayMs = Math.min(100, 10 * (2 ** Math.min(attempt, 4)));
|
||||
dialRecord.stopRetryAttempts = attempt + 1;
|
||||
dialRecord.stopRetryTimer = setTimeout(() => {
|
||||
dialRecord.stopRetryTimer = null;
|
||||
if (
|
||||
!dialRecord.stopRequested
|
||||
|| dialRecord.stopConfirmed
|
||||
|| dialRecord.dialDone
|
||||
|| dialRecord.settled
|
||||
) {
|
||||
return;
|
||||
}
|
||||
void this.#stopDialTunnel(dialRecord);
|
||||
}, delayMs);
|
||||
dialRecord.stopRetryTimer.unref?.();
|
||||
}
|
||||
|
||||
async #stopDialTunnel(dialRecord, { afterDialReturn = false } = {}) {
|
||||
if (!dialRecord?.tunnelId) return false;
|
||||
dialRecord.stopRequested = true;
|
||||
this.#clearStopRetryTimer(dialRecord);
|
||||
if (dialRecord.stopConfirmed) return true;
|
||||
|
||||
if (dialRecord.stopInFlight) {
|
||||
if (!afterDialReturn) {
|
||||
return dialRecord.stopInFlight;
|
||||
}
|
||||
while (dialRecord.stopInFlight) {
|
||||
await dialRecord.stopInFlight;
|
||||
}
|
||||
if (dialRecord.stopConfirmed) return true;
|
||||
}
|
||||
|
||||
const { tunnelId, sender } = dialRecord;
|
||||
const stopPromise = (async () => {
|
||||
try {
|
||||
hostKeyVerifier.cancelRequestsForSession(tunnelId);
|
||||
} catch { /* ignore */ }
|
||||
let result = null;
|
||||
try {
|
||||
result = await this.#bridge().stopPortForward({ sender }, { tunnelId });
|
||||
} catch {
|
||||
result = null;
|
||||
}
|
||||
if (this.#isStopConfirmed(result)) {
|
||||
dialRecord.stopConfirmed = true;
|
||||
this.#clearStopRetryTimer(dialRecord);
|
||||
return true;
|
||||
}
|
||||
if (!dialRecord.dialDone && !dialRecord.settled && dialRecord.stopRequested) {
|
||||
this.#scheduleStopRetry(dialRecord);
|
||||
}
|
||||
return false;
|
||||
})();
|
||||
const tracked = stopPromise.finally(() => {
|
||||
if (dialRecord.stopInFlight === tracked) {
|
||||
dialRecord.stopInFlight = null;
|
||||
}
|
||||
});
|
||||
dialRecord.stopInFlight = tracked;
|
||||
return tracked;
|
||||
}
|
||||
|
||||
#cancelPendingDial(dialRecord, reason) {
|
||||
if (!dialRecord) return;
|
||||
dialRecord.stopRequested = true;
|
||||
if (dialRecord.envelopeTimer) {
|
||||
clearTimeout(dialRecord.envelopeTimer);
|
||||
dialRecord.envelopeTimer = null;
|
||||
}
|
||||
if (this.pendingDials.get(dialRecord.key) === dialRecord) {
|
||||
this.pendingDials.delete(dialRecord.key);
|
||||
}
|
||||
if (!dialRecord.settled && dialRecord.tunnelId) {
|
||||
void this.#stopDialTunnel(dialRecord);
|
||||
}
|
||||
if (!dialRecord.controller.signal.aborted) {
|
||||
dialRecord.controller.abort(reason);
|
||||
}
|
||||
}
|
||||
|
||||
#touchIdleTimer(entry) {
|
||||
if (entry.idleTimer) clearTimeout(entry.idleTimer);
|
||||
if (entry.closed || this.idleTtlMs <= 0) return;
|
||||
@@ -102,6 +281,9 @@ class PluginHostSshExecTransport {
|
||||
}
|
||||
|
||||
async #dialEntry({ runtimeId, pluginId, hostId, prepareConnection, signal }) {
|
||||
if (signal?.aborted) {
|
||||
throw this.#callerAbortError(signal);
|
||||
}
|
||||
const key = this.#key(runtimeId, hostId);
|
||||
const existing = this.connections.get(key);
|
||||
if (this.#isEntryHealthy(existing)) {
|
||||
@@ -111,126 +293,280 @@ class PluginHostSshExecTransport {
|
||||
void this.#closeEntry(existing);
|
||||
}
|
||||
|
||||
const raceCallerSignal = (promise) => {
|
||||
if (!signal) return promise;
|
||||
if (signal.aborted) return Promise.reject(fail("cancelled", "SSH connection was cancelled"));
|
||||
const attachWaiter = (dialRecord) => {
|
||||
if (signal?.aborted) {
|
||||
return Promise.reject(this.#callerAbortError(signal));
|
||||
}
|
||||
if (dialRecord.controller.signal.aborted && !dialRecord.settled) {
|
||||
return Promise.reject(this.#dialAbortError(dialRecord));
|
||||
}
|
||||
dialRecord.waiterCount += 1;
|
||||
let released = false;
|
||||
const releaseWaiter = (abortedByCaller) => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
dialRecord.waiterCount = Math.max(0, dialRecord.waiterCount - 1);
|
||||
// Tear down the shared dial only when the last waiter leaves while
|
||||
// still in flight so retries do not hitchhike on a wedged handshake.
|
||||
// Keep dialing when another waiter remains, and never stop a settled entry.
|
||||
if (abortedByCaller && dialRecord.waiterCount === 0 && !dialRecord.settled) {
|
||||
dialRecord.cancelledByWaiters = true;
|
||||
this.#cancelPendingDial(dialRecord, fail("cancelled", "SSH connection was cancelled"));
|
||||
}
|
||||
};
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const onAbort = () => reject(fail("cancelled", "SSH connection was cancelled"));
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
promise.then(
|
||||
(val) => { signal.removeEventListener("abort", onAbort); resolve(val); },
|
||||
(err) => { signal.removeEventListener("abort", onAbort); reject(err); },
|
||||
const dialSignal = dialRecord.controller.signal;
|
||||
const cleanup = () => {
|
||||
signal?.removeEventListener("abort", onCallerAbort);
|
||||
dialSignal.removeEventListener("abort", onDialAbort);
|
||||
};
|
||||
const onCallerAbort = () => {
|
||||
cleanup();
|
||||
releaseWaiter(true);
|
||||
reject(this.#callerAbortError(signal));
|
||||
};
|
||||
const onDialAbort = () => {
|
||||
cleanup();
|
||||
releaseWaiter(false);
|
||||
reject(this.#dialAbortError(dialRecord));
|
||||
};
|
||||
signal?.addEventListener("abort", onCallerAbort, { once: true });
|
||||
dialSignal.addEventListener("abort", onDialAbort, { once: true });
|
||||
dialRecord.promise.then(
|
||||
(val) => {
|
||||
cleanup();
|
||||
releaseWaiter(false);
|
||||
resolve(val);
|
||||
},
|
||||
(err) => {
|
||||
cleanup();
|
||||
releaseWaiter(false);
|
||||
reject(err);
|
||||
},
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const inflight = this.pendingDials.get(key);
|
||||
if (inflight) {
|
||||
return raceCallerSignal(inflight.promise);
|
||||
return attachWaiter(inflight);
|
||||
}
|
||||
|
||||
const dialStartedAt = this.clock();
|
||||
const envelopeMs = this.sshDialEnvelopeMs;
|
||||
const dialController = new AbortController();
|
||||
const dialRecord = {
|
||||
key,
|
||||
controller: dialController,
|
||||
promise: null,
|
||||
runtimeId,
|
||||
pluginId,
|
||||
hostId,
|
||||
waiterCount: 0,
|
||||
settled: false,
|
||||
cancelledByWaiters: false,
|
||||
timedOut: false,
|
||||
tunnelId: null,
|
||||
sender: null,
|
||||
stopRequested: false,
|
||||
stopConfirmed: false,
|
||||
stopInFlight: null,
|
||||
stopRetryTimer: null,
|
||||
stopRetryAttempts: 0,
|
||||
dialDone: false,
|
||||
envelopeTimer: null,
|
||||
};
|
||||
this.pendingDials.set(key, dialRecord);
|
||||
dialRecord.envelopeTimer = setTimeout(() => {
|
||||
dialRecord.envelopeTimer = null;
|
||||
if (dialRecord.settled) return;
|
||||
dialRecord.timedOut = true;
|
||||
this.#cancelPendingDial(dialRecord, fail("deadlineExceeded", "SSH connection timed out"));
|
||||
}, envelopeMs);
|
||||
dialRecord.envelopeTimer.unref?.();
|
||||
|
||||
const dialPromise = (async () => {
|
||||
if (this.closed || this.isLocked() || dialController.signal.aborted) {
|
||||
throw fail("unavailable", "Host SSH execution is unavailable");
|
||||
}
|
||||
const connectionOptions = await prepareConnection(hostId, dialController.signal);
|
||||
if (!connectionOptions || typeof connectionOptions !== "object") {
|
||||
throw fail("unavailable", "Could not prepare SSH connection for host");
|
||||
}
|
||||
if (connectionOptions.singleChannelSsh) {
|
||||
throw fail("unsupported", "This SSH server does not support multiplexed command execution");
|
||||
}
|
||||
if (this.closed || this.isLocked() || dialController.signal.aborted) {
|
||||
throw fail("unavailable", "Host SSH execution is unavailable");
|
||||
}
|
||||
try {
|
||||
if (this.closed || this.isLocked() || dialController.signal.aborted) {
|
||||
throw this.#dialAbortError(dialRecord);
|
||||
}
|
||||
let connectionOptions;
|
||||
try {
|
||||
connectionOptions = await prepareConnection(hostId, dialController.signal);
|
||||
} catch (err) {
|
||||
if (dialRecord.timedOut || dialController.signal.aborted) {
|
||||
throw this.#dialAbortError(dialRecord);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
if (this.closed || this.isLocked() || dialRecord.timedOut || dialController.signal.aborted) {
|
||||
throw this.#dialAbortError(dialRecord);
|
||||
}
|
||||
if (!connectionOptions || typeof connectionOptions !== "object") {
|
||||
throw fail("unavailable", "Could not prepare SSH connection for host");
|
||||
}
|
||||
if (connectionOptions.singleChannelSsh) {
|
||||
throw fail("unsupported", "This SSH server does not support multiplexed command execution");
|
||||
}
|
||||
|
||||
const sender = this.getSender();
|
||||
const tunnelId = `plugin-exec-${randomUUID()}`;
|
||||
const event = { sender };
|
||||
let liveConn = null;
|
||||
let rejectedUnsupported = false;
|
||||
const detectVendor = await loadVendorDetector();
|
||||
const detectVendor = await loadVendorDetector();
|
||||
if (this.closed || this.isLocked() || dialRecord.timedOut || dialController.signal.aborted) {
|
||||
throw this.#dialAbortError(dialRecord);
|
||||
}
|
||||
|
||||
const result = await this.#bridge().startPortForward(
|
||||
event,
|
||||
{
|
||||
...connectionOptions,
|
||||
const elapsedMs = Math.max(0, this.clock() - dialStartedAt);
|
||||
const remainingMs = envelopeMs - elapsedMs;
|
||||
if (remainingMs <= 0) {
|
||||
dialRecord.timedOut = true;
|
||||
throw fail("deadlineExceeded", "SSH connection timed out");
|
||||
}
|
||||
const minStageMs = Math.min(
|
||||
MIN_SSH_CONNECT_STAGE_TIMEOUT_MS,
|
||||
this.sshTcpConnectTimeoutMs,
|
||||
this.sshAuthReadyTimeoutMs,
|
||||
);
|
||||
const stageBudgetMs = Math.max(minStageMs, Math.round(remainingMs));
|
||||
const sshTcpConnectTimeoutMs = Math.min(this.sshTcpConnectTimeoutMs, stageBudgetMs);
|
||||
const sshAuthReadyTimeoutMs = Math.min(this.sshAuthReadyTimeoutMs, stageBudgetMs);
|
||||
|
||||
const sender = this.getSender();
|
||||
const bridge = this.#bridge();
|
||||
if (this.closed || this.isLocked() || dialRecord.timedOut || dialController.signal.aborted || dialRecord.stopRequested) {
|
||||
throw this.#dialAbortError(dialRecord);
|
||||
}
|
||||
const tunnelId = `plugin-exec-${randomUUID()}`;
|
||||
const event = { sender };
|
||||
dialRecord.tunnelId = tunnelId;
|
||||
dialRecord.sender = sender;
|
||||
|
||||
let liveConn = null;
|
||||
let rejectedUnsupported = false;
|
||||
let result;
|
||||
try {
|
||||
result = await bridge.startPortForward(
|
||||
event,
|
||||
{
|
||||
...connectionOptions,
|
||||
tunnelId,
|
||||
ruleId: undefined,
|
||||
type: "local",
|
||||
localPort: 0,
|
||||
bindAddress: "127.0.0.1",
|
||||
remoteHost: "127.0.0.1",
|
||||
remotePort: 1,
|
||||
reuseTransport: true,
|
||||
sshTcpConnectTimeoutMs,
|
||||
sshAuthReadyTimeoutMs,
|
||||
},
|
||||
{
|
||||
bindChannels: async ({ conn, tunnelState, chainConnections }) => {
|
||||
tunnelState.conn = conn;
|
||||
tunnelState.pendingConn = null;
|
||||
tunnelState.chainConnections = chainConnections;
|
||||
const remoteVer = typeof conn?._remoteVer === "string" ? conn._remoteVer : "";
|
||||
if (detectVendor(remoteVer) || remoteSoftwareRequiresSingleChannel(remoteVer)) {
|
||||
rejectedUnsupported = true;
|
||||
throw new Error("SINGLE_CHANNEL_UNSUPPORTED");
|
||||
}
|
||||
liveConn = conn;
|
||||
tunnelState.status = "active";
|
||||
return { success: true };
|
||||
},
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
dialRecord.dialDone = true;
|
||||
this.#clearStopRetryTimer(dialRecord);
|
||||
await this.#stopDialTunnel(dialRecord, { afterDialReturn: true });
|
||||
if (rejectedUnsupported) {
|
||||
throw fail("unsupported", "This SSH server does not support multiplexed command execution");
|
||||
}
|
||||
if (dialRecord.timedOut || dialController.signal.aborted) {
|
||||
throw this.#dialAbortError(dialRecord);
|
||||
}
|
||||
if (this.#isConnectTimeoutError(err)) {
|
||||
throw fail("deadlineExceeded", "SSH connection timed out");
|
||||
}
|
||||
if (err instanceof PluginRpcError) throw err;
|
||||
throw fail("unavailable", "Could not connect to the selected SSH server");
|
||||
}
|
||||
dialRecord.dialDone = true;
|
||||
this.#clearStopRetryTimer(dialRecord);
|
||||
|
||||
if (rejectedUnsupported) {
|
||||
await this.#stopDialTunnel(dialRecord, { afterDialReturn: true });
|
||||
throw fail("unsupported", "This SSH server does not support multiplexed command execution");
|
||||
}
|
||||
if (this.closed || this.isLocked() || dialRecord.timedOut || dialController.signal.aborted || dialRecord.stopRequested) {
|
||||
await this.#stopDialTunnel(dialRecord, { afterDialReturn: true });
|
||||
throw this.#dialAbortError(dialRecord);
|
||||
}
|
||||
if (!result?.success || !liveConn) {
|
||||
await this.#stopDialTunnel(dialRecord, { afterDialReturn: true });
|
||||
if (result?.cancelled) {
|
||||
throw fail("cancelled", "SSH connection was cancelled");
|
||||
}
|
||||
if (this.#isConnectTimeoutError(result?.error)) {
|
||||
throw fail("deadlineExceeded", "SSH connection timed out");
|
||||
}
|
||||
throw fail("unavailable", "Could not connect to the selected SSH server");
|
||||
}
|
||||
|
||||
const entry = {
|
||||
key,
|
||||
runtimeId,
|
||||
pluginId,
|
||||
hostId,
|
||||
tunnelId,
|
||||
ruleId: undefined,
|
||||
type: "local",
|
||||
localPort: 0,
|
||||
bindAddress: "127.0.0.1",
|
||||
remoteHost: "127.0.0.1",
|
||||
remotePort: 1,
|
||||
reuseTransport: true,
|
||||
},
|
||||
{
|
||||
bindChannels: async ({ conn, tunnelState, chainConnections }) => {
|
||||
tunnelState.conn = conn;
|
||||
tunnelState.pendingConn = null;
|
||||
tunnelState.chainConnections = chainConnections;
|
||||
const remoteVer = typeof conn?._remoteVer === "string" ? conn._remoteVer : "";
|
||||
if (detectVendor(remoteVer) || remoteSoftwareRequiresSingleChannel(remoteVer)) {
|
||||
rejectedUnsupported = true;
|
||||
throw new Error("SINGLE_CHANNEL_UNSUPPORTED");
|
||||
}
|
||||
liveConn = conn;
|
||||
tunnelState.status = "active";
|
||||
return { success: true };
|
||||
},
|
||||
},
|
||||
);
|
||||
sender,
|
||||
conn: liveConn,
|
||||
closed: false,
|
||||
activeCount: 0,
|
||||
idleTimer: null,
|
||||
};
|
||||
const onConnDead = () => {
|
||||
void this.#closeEntry(entry);
|
||||
};
|
||||
liveConn.once?.("close", onConnDead);
|
||||
liveConn.once?.("end", onConnDead);
|
||||
liveConn.once?.("error", onConnDead);
|
||||
|
||||
if (rejectedUnsupported) {
|
||||
hostKeyVerifier.cancelRequestsForSession(tunnelId);
|
||||
await this.#bridge().stopPortForward(event, { tunnelId }).catch(() => {});
|
||||
throw fail("unsupported", "This SSH server does not support multiplexed command execution");
|
||||
if (this.closed || this.isLocked() || dialRecord.timedOut || dialController.signal.aborted || dialRecord.stopRequested) {
|
||||
await this.#closeEntry(entry);
|
||||
throw this.#dialAbortError(dialRecord);
|
||||
}
|
||||
|
||||
// Publish and mark settled synchronously before resolving so a waiter
|
||||
// abort in the settlement microtask cannot tear down the pooled entry.
|
||||
dialRecord.settled = true;
|
||||
if (dialRecord.envelopeTimer) {
|
||||
clearTimeout(dialRecord.envelopeTimer);
|
||||
dialRecord.envelopeTimer = null;
|
||||
}
|
||||
if (this.pendingDials.get(key) === dialRecord) {
|
||||
this.pendingDials.delete(key);
|
||||
}
|
||||
this.connections.set(key, entry);
|
||||
this.#touchIdleTimer(entry);
|
||||
return entry;
|
||||
} finally {
|
||||
dialRecord.settled = true;
|
||||
dialRecord.dialDone = true;
|
||||
this.#clearStopRetryTimer(dialRecord);
|
||||
if (dialRecord.envelopeTimer) {
|
||||
clearTimeout(dialRecord.envelopeTimer);
|
||||
dialRecord.envelopeTimer = null;
|
||||
}
|
||||
if (this.pendingDials.get(key) === dialRecord) {
|
||||
this.pendingDials.delete(key);
|
||||
}
|
||||
}
|
||||
if (!result?.success || !liveConn) {
|
||||
hostKeyVerifier.cancelRequestsForSession(tunnelId);
|
||||
await this.#bridge().stopPortForward(event, { tunnelId }).catch(() => {});
|
||||
throw fail("unavailable", "Could not connect to the selected SSH server");
|
||||
}
|
||||
|
||||
const entry = {
|
||||
key,
|
||||
runtimeId,
|
||||
pluginId,
|
||||
hostId,
|
||||
tunnelId,
|
||||
sender,
|
||||
conn: liveConn,
|
||||
closed: false,
|
||||
activeCount: 0,
|
||||
idleTimer: null,
|
||||
};
|
||||
const onConnDead = () => {
|
||||
void this.#closeEntry(entry);
|
||||
};
|
||||
liveConn.once?.("close", onConnDead);
|
||||
liveConn.once?.("end", onConnDead);
|
||||
liveConn.once?.("error", onConnDead);
|
||||
|
||||
if (this.closed || this.isLocked() || dialController.signal.aborted) {
|
||||
await this.#closeEntry(entry);
|
||||
throw fail("unavailable", "Host SSH execution is unavailable");
|
||||
}
|
||||
|
||||
this.connections.set(key, entry);
|
||||
this.#touchIdleTimer(entry);
|
||||
return entry;
|
||||
})();
|
||||
|
||||
const dialRecord = { controller: dialController, promise: dialPromise, runtimeId, pluginId, hostId };
|
||||
this.pendingDials.set(key, dialRecord);
|
||||
const cleanupPending = () => {
|
||||
if (this.pendingDials.get(key) === dialRecord) {
|
||||
this.pendingDials.delete(key);
|
||||
}
|
||||
};
|
||||
dialPromise.then(cleanupPending, cleanupPending);
|
||||
return raceCallerSignal(dialPromise);
|
||||
dialRecord.promise = dialPromise;
|
||||
dialPromise.catch(() => {});
|
||||
return attachWaiter(dialRecord);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -249,15 +585,19 @@ class PluginHostSshExecTransport {
|
||||
const controller = new AbortController();
|
||||
const lease = { controller, runtimeId, pluginId, hostId };
|
||||
this.activeExecs.add(lease);
|
||||
const onCallerAbort = () => controller.abort(signal?.reason ?? fail("cancelled", "SSH operation was cancelled"));
|
||||
if (signal?.aborted) {
|
||||
this.activeExecs.delete(lease);
|
||||
throw fail("cancelled", "SSH operation was cancelled");
|
||||
}
|
||||
signal?.addEventListener("abort", onCallerAbort, { once: true });
|
||||
|
||||
let entry = null;
|
||||
let acquired = false;
|
||||
const onCallerAbort = () => {
|
||||
controller.abort(signal?.reason ?? fail("cancelled", "SSH operation was cancelled"));
|
||||
if (entry && acquired && this.#isDeadlineAbort(controller.signal)) {
|
||||
void this.#closeEntry(entry);
|
||||
}
|
||||
};
|
||||
if (signal?.aborted) {
|
||||
this.activeExecs.delete(lease);
|
||||
throw this.#callerAbortError(signal, "SSH operation was cancelled");
|
||||
}
|
||||
signal?.addEventListener("abort", onCallerAbort, { once: true });
|
||||
try {
|
||||
await assertActive?.();
|
||||
controller.signal.throwIfAborted();
|
||||
@@ -330,7 +670,7 @@ class PluginHostSshExecTransport {
|
||||
const onCallerAbort = () => controller.abort(signal?.reason ?? fail("cancelled", "SSH command was cancelled"));
|
||||
if (signal?.aborted) {
|
||||
this.activeExecs.delete(lease);
|
||||
throw fail("cancelled", "SSH command was cancelled");
|
||||
throw this.#callerAbortError(signal, "SSH command was cancelled");
|
||||
}
|
||||
signal?.addEventListener("abort", onCallerAbort, { once: true });
|
||||
|
||||
@@ -371,10 +711,19 @@ class PluginHostSshExecTransport {
|
||||
runTimeoutMs: timeoutMs,
|
||||
maxOutputBytes,
|
||||
signal: controller.signal,
|
||||
// Leave transport teardown to this plugin transport so a healthy
|
||||
// user cancel preserves the pool while open-timeout/deadline evicts.
|
||||
invalidateTransportOnAbort: false,
|
||||
});
|
||||
} catch (err) {
|
||||
if (!this.#isEntryHealthy(entry) || err?.code === "ECONNRESET" || err?.code === "EPIPE") {
|
||||
const isDeadlineAbort = this.#isDeadlineAbort(controller.signal);
|
||||
if (
|
||||
!this.#isEntryHealthy(entry)
|
||||
|| err?.code === "ECONNRESET"
|
||||
|| err?.code === "EPIPE"
|
||||
|| err?.code === "SSH_EXEC_OPEN_TIMEOUT"
|
||||
|| isDeadlineAbort
|
||||
) {
|
||||
void this.#closeEntry(entry);
|
||||
}
|
||||
if (err instanceof PluginRpcError) throw err;
|
||||
@@ -382,7 +731,7 @@ class PluginHostSshExecTransport {
|
||||
throw fail("resourceExhausted", "SSH command output exceeded the configured byte limit");
|
||||
}
|
||||
if (controller.signal.aborted) {
|
||||
throw fail("cancelled", "SSH command was cancelled");
|
||||
throw this.#callerAbortError(controller.signal, "SSH command was cancelled");
|
||||
}
|
||||
if (/timed out/i.test(String(err?.message ?? ""))) {
|
||||
throw fail("deadlineExceeded", "SSH command timed out");
|
||||
@@ -422,7 +771,7 @@ class PluginHostSshExecTransport {
|
||||
releaseHost(pluginId, hostId) {
|
||||
for (const dial of [...this.pendingDials.values()]) {
|
||||
if (dial.pluginId === pluginId && dial.hostId === hostId) {
|
||||
dial.controller.abort(fail("permissionDenied", "Host binding was revoked"));
|
||||
this.#cancelPendingDial(dial, fail("permissionDenied", "Host binding was revoked"));
|
||||
}
|
||||
}
|
||||
for (const lease of [...this.activeExecs]) {
|
||||
@@ -440,7 +789,7 @@ class PluginHostSshExecTransport {
|
||||
releaseRuntime(runtimeId) {
|
||||
for (const dial of [...this.pendingDials.values()]) {
|
||||
if (dial.runtimeId === runtimeId) {
|
||||
dial.controller.abort(fail("cancelled", "Plugin runtime stopped"));
|
||||
this.#cancelPendingDial(dial, fail("cancelled", "Plugin runtime stopped"));
|
||||
}
|
||||
}
|
||||
for (const lease of [...this.activeExecs]) {
|
||||
@@ -458,7 +807,7 @@ class PluginHostSshExecTransport {
|
||||
releasePlugin(pluginId) {
|
||||
for (const dial of [...this.pendingDials.values()]) {
|
||||
if (dial.pluginId === pluginId) {
|
||||
dial.controller.abort(fail("permissionDenied", "Plugin SSH execution permission revoked or disabled"));
|
||||
this.#cancelPendingDial(dial, fail("permissionDenied", "Plugin SSH execution permission revoked or disabled"));
|
||||
}
|
||||
}
|
||||
for (const lease of [...this.activeExecs]) {
|
||||
@@ -475,7 +824,7 @@ class PluginHostSshExecTransport {
|
||||
|
||||
closeAll(reason = "Host SSH execution unavailable") {
|
||||
for (const dial of [...this.pendingDials.values()]) {
|
||||
dial.controller.abort(fail("unavailable", reason));
|
||||
this.#cancelPendingDial(dial, fail("unavailable", reason));
|
||||
}
|
||||
for (const lease of [...this.activeExecs]) {
|
||||
lease.controller.abort(fail("unavailable", reason));
|
||||
@@ -498,4 +847,7 @@ module.exports = {
|
||||
DEFAULT_IDLE_TTL_MS,
|
||||
DEFAULT_MAX_CONCURRENT_PER_RUNTIME,
|
||||
DEFAULT_MAX_CONCURRENT_TOTAL,
|
||||
DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS,
|
||||
DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS,
|
||||
DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS,
|
||||
};
|
||||
@@ -0,0 +1,710 @@
|
||||
"use strict";
|
||||
|
||||
const assert = require("node:assert/strict");
|
||||
const EventEmitter = require("node:events");
|
||||
const test = require("node:test");
|
||||
|
||||
const {
|
||||
PluginHostSshExecTransport,
|
||||
DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS,
|
||||
DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS,
|
||||
DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS,
|
||||
} = require("./hostSshExecTransport.cjs");
|
||||
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
|
||||
|
||||
function createFakeConn(sockOverrides = {}) {
|
||||
const conn = new EventEmitter();
|
||||
conn._remoteVer = "SSH-2.0-OpenSSH_9.6";
|
||||
if (sockOverrides !== null) {
|
||||
conn._sock = {
|
||||
destroyed: false,
|
||||
writableEnded: false,
|
||||
readableEnded: false,
|
||||
writableFinished: false,
|
||||
writable: true,
|
||||
readyState: "open",
|
||||
...sockOverrides,
|
||||
};
|
||||
}
|
||||
return conn;
|
||||
}
|
||||
|
||||
function defaultPrepareConnection(hostId) {
|
||||
return Promise.resolve({
|
||||
hostId,
|
||||
hostname: "10.0.0.10",
|
||||
port: 22,
|
||||
username: "ubuntu",
|
||||
});
|
||||
}
|
||||
|
||||
function createBaseExecArgs(overrides = {}) {
|
||||
return {
|
||||
runtimeId: "rt-1",
|
||||
pluginId: "com.example.monitor",
|
||||
hostId: "host-1",
|
||||
command: "uptime",
|
||||
timeoutMs: 10_000,
|
||||
maxOutputBytes: 64 * 1024,
|
||||
prepareConnection: defaultPrepareConnection,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
test("last-waiter abort during in-flight dial stops tunnel, clears pendingDials, and allows fresh retry", async () => {
|
||||
const sender = { id: 1 };
|
||||
let dialCount = 0;
|
||||
const stoppedTunnels = [];
|
||||
const inflightStops = new Map();
|
||||
|
||||
const portForwardingBridge = {
|
||||
startPortForward(_event, opts, hooks) {
|
||||
dialCount += 1;
|
||||
const attempt = dialCount;
|
||||
if (attempt === 1) {
|
||||
// First dial hangs until stopPortForward tears it down.
|
||||
return new Promise((resolve) => {
|
||||
inflightStops.set(opts.tunnelId, () => {
|
||||
resolve({ tunnelId: opts.tunnelId, success: false, cancelled: true });
|
||||
});
|
||||
});
|
||||
}
|
||||
const conn = createFakeConn();
|
||||
return hooks.bindChannels({
|
||||
conn,
|
||||
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
|
||||
chainConnections: [],
|
||||
}).then(() => ({ success: true }));
|
||||
},
|
||||
async stopPortForward(event, { tunnelId }) {
|
||||
stoppedTunnels.push({ sender: event?.sender, tunnelId });
|
||||
const cancel = inflightStops.get(tunnelId);
|
||||
if (cancel) {
|
||||
inflightStops.delete(tunnelId);
|
||||
cancel();
|
||||
}
|
||||
return { success: true };
|
||||
},
|
||||
};
|
||||
|
||||
const transport = new PluginHostSshExecTransport({
|
||||
portForwardingBridge,
|
||||
execCommand: async (_conn, command) => ({ stdout: `ok:${command}`, stderr: "", code: 0 }),
|
||||
measurePing: async () => 5,
|
||||
getSender: () => sender,
|
||||
});
|
||||
|
||||
const abort1 = new AbortController();
|
||||
const p1 = transport.exec(createBaseExecArgs({ command: "first", signal: abort1.signal }));
|
||||
|
||||
// Wait until startPortForward has been entered for attempt 1.
|
||||
while (dialCount < 1) await new Promise((r) => setTimeout(r, 5));
|
||||
assert.equal(transport.pendingDials.size, 1);
|
||||
|
||||
abort1.abort(new PluginRpcError(RPC_ERRORS.deadlineExceeded, "Plugin request deadline exceeded"));
|
||||
await assert.rejects(p1, (err) => err.code === RPC_ERRORS.deadlineExceeded);
|
||||
|
||||
assert.equal(stoppedTunnels.length, 1, "last waiter abort must call stopPortForward");
|
||||
assert.equal(stoppedTunnels[0].sender, sender);
|
||||
assert.equal(transport.pendingDials.size, 0, "pendingDials must be cleared immediately");
|
||||
assert.equal(inflightStops.size, 0, "hung startPortForward must be torn down");
|
||||
|
||||
// A subsequent retry must dial fresh and succeed instead of hitchhiking.
|
||||
const res2 = await transport.exec(createBaseExecArgs({ command: "retry" }));
|
||||
assert.equal(res2.stdout, "ok:retry");
|
||||
assert.equal(dialCount, 2, "retry must start a new startPortForward dial");
|
||||
|
||||
// Completing normally must NOT stop the live pooled tunnel.
|
||||
assert.equal(stoppedTunnels.length, 1);
|
||||
assert.equal(transport.connections.size, 1);
|
||||
|
||||
transport.shutdown();
|
||||
});
|
||||
|
||||
test("non-last waiter cancel keeps shared dial alive for remaining waiter, while cancelling all stops tunnel", async () => {
|
||||
let dialCount = 0;
|
||||
let stopCount = 0;
|
||||
let finishDial = null;
|
||||
let dialEntered = false;
|
||||
|
||||
const portForwardingBridge = {
|
||||
startPortForward(_event, opts, hooks) {
|
||||
dialCount += 1;
|
||||
dialEntered = true;
|
||||
return new Promise((resolve) => {
|
||||
finishDial = async (cancelled = false) => {
|
||||
if (cancelled) {
|
||||
resolve({ tunnelId: opts.tunnelId, success: false, cancelled: true });
|
||||
return;
|
||||
}
|
||||
const conn = createFakeConn();
|
||||
await hooks.bindChannels({
|
||||
conn,
|
||||
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
|
||||
chainConnections: [],
|
||||
});
|
||||
resolve({ success: true });
|
||||
};
|
||||
});
|
||||
},
|
||||
async stopPortForward() {
|
||||
stopCount += 1;
|
||||
finishDial?.(true);
|
||||
return { success: true };
|
||||
},
|
||||
};
|
||||
|
||||
const transport = new PluginHostSshExecTransport({
|
||||
portForwardingBridge,
|
||||
execCommand: async (_conn, command) => ({ stdout: `ok:${command}`, stderr: "", code: 0 }),
|
||||
measurePing: async () => 7,
|
||||
getSender: () => ({ id: 1 }),
|
||||
});
|
||||
|
||||
const abortA = new AbortController();
|
||||
const pA = transport.exec(createBaseExecArgs({ command: "a", signal: abortA.signal }));
|
||||
const pB = transport.exec(createBaseExecArgs({ command: "b" }));
|
||||
|
||||
while (!dialEntered) await new Promise((r) => setTimeout(r, 5));
|
||||
assert.equal(dialCount, 1);
|
||||
|
||||
abortA.abort();
|
||||
await assert.rejects(pA, (err) => err.code === RPC_ERRORS.cancelled);
|
||||
assert.equal(stopCount, 0, "aborting one of two waiters must not stop shared tunnel");
|
||||
assert.equal(transport.pendingDials.size, 1);
|
||||
|
||||
await finishDial(false);
|
||||
const resB = await pB;
|
||||
assert.equal(resB.stdout, "ok:b");
|
||||
assert.equal(dialCount, 1);
|
||||
assert.equal(stopCount, 0);
|
||||
|
||||
// Now verify that cancelling ALL waiters (A then B) on a fresh host tears down the dial.
|
||||
dialEntered = false;
|
||||
const abortC = new AbortController();
|
||||
const abortD = new AbortController();
|
||||
const pC = transport.exec(createBaseExecArgs({ hostId: "host-2", command: "c", signal: abortC.signal }));
|
||||
const pD = transport.exec(createBaseExecArgs({ hostId: "host-2", command: "d", signal: abortD.signal }));
|
||||
|
||||
while (!dialEntered) await new Promise((r) => setTimeout(r, 5));
|
||||
assert.equal(dialCount, 2);
|
||||
|
||||
abortC.abort();
|
||||
await assert.rejects(pC, (err) => err.code === RPC_ERRORS.cancelled);
|
||||
assert.equal(stopCount, 0);
|
||||
|
||||
abortD.abort();
|
||||
await assert.rejects(pD, (err) => err.code === RPC_ERRORS.cancelled);
|
||||
assert.equal(stopCount, 1, "cancelling the final remaining waiter must stop the tunnel");
|
||||
assert.equal(transport.pendingDials.size, 0);
|
||||
|
||||
transport.shutdown();
|
||||
});
|
||||
|
||||
test("releaseRuntime and releasePlugin stop in-flight dial tunnels", async () => {
|
||||
const stopped = [];
|
||||
let entered = 0;
|
||||
|
||||
const portForwardingBridge = {
|
||||
startPortForward(_event, opts) {
|
||||
entered += 1;
|
||||
return new Promise(() => {
|
||||
// intentionally never resolves on its own
|
||||
void opts;
|
||||
});
|
||||
},
|
||||
async stopPortForward(_event, { tunnelId }) {
|
||||
stopped.push(tunnelId);
|
||||
return { success: true };
|
||||
},
|
||||
};
|
||||
|
||||
const transport = new PluginHostSshExecTransport({
|
||||
portForwardingBridge,
|
||||
execCommand: async () => ({ stdout: "", stderr: "", code: 0 }),
|
||||
measurePing: async () => 5,
|
||||
getSender: () => ({ id: 1 }),
|
||||
});
|
||||
|
||||
const p1 = transport.exec(createBaseExecArgs({ runtimeId: "rt-1", hostId: "host-1" }));
|
||||
while (entered < 1) await new Promise((r) => setTimeout(r, 5));
|
||||
transport.releaseRuntime("rt-1");
|
||||
await assert.rejects(p1, (err) => err.code === RPC_ERRORS.cancelled);
|
||||
assert.equal(stopped.length, 1);
|
||||
assert.equal(transport.pendingDials.size, 0);
|
||||
|
||||
const p2 = transport.exec(createBaseExecArgs({ runtimeId: "rt-2", pluginId: "p-2", hostId: "host-2" }));
|
||||
while (entered < 2) await new Promise((r) => setTimeout(r, 5));
|
||||
transport.releasePlugin("p-2");
|
||||
await assert.rejects(p2, (err) => err.code === RPC_ERRORS.permissionDenied);
|
||||
assert.equal(stopped.length, 2);
|
||||
assert.equal(transport.pendingDials.size, 0);
|
||||
|
||||
transport.shutdown();
|
||||
});
|
||||
|
||||
test("passes tightened SSH dial timeouts and maps connect timeout / envelope expiry to deadlineExceeded", async () => {
|
||||
assert.equal(DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS, 8_000);
|
||||
assert.equal(DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS, 8_000);
|
||||
assert.ok(DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS >= 15_000 && DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS <= 20_000);
|
||||
|
||||
const seenOpts = [];
|
||||
let now = 1_000;
|
||||
let bridgeBehavior = "timeout-error";
|
||||
let stopCount = 0;
|
||||
const hungStops = new Map();
|
||||
|
||||
const portForwardingBridge = {
|
||||
async startPortForward(_event, opts) {
|
||||
seenOpts.push(opts);
|
||||
if (bridgeBehavior === "timeout-error") {
|
||||
throw new Error("Connection timeout to 10.0.0.10");
|
||||
}
|
||||
// Simulate an open hung socket handle that is torn down by stopPortForward.
|
||||
return new Promise((resolve) => {
|
||||
const socketHandle = setTimeout(() => {}, 10_000);
|
||||
hungStops.set(opts.tunnelId, () => {
|
||||
clearTimeout(socketHandle);
|
||||
resolve({ tunnelId: opts.tunnelId, success: false, cancelled: true });
|
||||
});
|
||||
});
|
||||
},
|
||||
async stopPortForward(_event, { tunnelId }) {
|
||||
stopCount += 1;
|
||||
const cancel = hungStops.get(tunnelId);
|
||||
if (cancel) {
|
||||
hungStops.delete(tunnelId);
|
||||
cancel();
|
||||
}
|
||||
return { success: true };
|
||||
},
|
||||
};
|
||||
|
||||
const transport = new PluginHostSshExecTransport({
|
||||
portForwardingBridge,
|
||||
execCommand: async () => ({ stdout: "ok", stderr: "", code: 0 }),
|
||||
measurePing: async () => 5,
|
||||
clock: () => now,
|
||||
getSender: () => ({ id: 1 }),
|
||||
});
|
||||
|
||||
// 1) Default connect budgets passed to startPortForward + timeout error mapping.
|
||||
await assert.rejects(
|
||||
transport.exec(createBaseExecArgs()),
|
||||
(err) => err instanceof PluginRpcError
|
||||
&& err.code === RPC_ERRORS.deadlineExceeded
|
||||
&& err.message === "SSH connection timed out",
|
||||
);
|
||||
assert.equal(seenOpts.length, 1);
|
||||
assert.equal(seenOpts[0].sshTcpConnectTimeoutMs, DEFAULT_PLUGIN_SSH_TCP_CONNECT_TIMEOUT_MS);
|
||||
assert.equal(seenOpts[0].sshAuthReadyTimeoutMs, DEFAULT_PLUGIN_SSH_AUTH_READY_TIMEOUT_MS);
|
||||
assert.ok(seenOpts[0].sshTcpConnectTimeoutMs < 30_000);
|
||||
assert.ok(seenOpts[0].sshAuthReadyTimeoutMs < 30_000);
|
||||
|
||||
// 2) Slow prepareConnection shrinks remaining stage budgets (clamped >= 1000ms).
|
||||
await assert.rejects(
|
||||
transport.exec(createBaseExecArgs({
|
||||
prepareConnection: async (hostId) => {
|
||||
now += DEFAULT_PLUGIN_SSH_DIAL_ENVELOPE_MS - 3_500;
|
||||
return defaultPrepareConnection(hostId);
|
||||
},
|
||||
})),
|
||||
(err) => err.code === RPC_ERRORS.deadlineExceeded && err.message === "SSH connection timed out",
|
||||
);
|
||||
assert.equal(seenOpts.length, 2);
|
||||
assert.equal(seenOpts[1].sshTcpConnectTimeoutMs, 3_500);
|
||||
assert.equal(seenOpts[1].sshAuthReadyTimeoutMs, 3_500);
|
||||
|
||||
transport.shutdown();
|
||||
|
||||
// 3) Connect envelope actively aborts a hung dial before 30s and tears down the tunnel.
|
||||
bridgeBehavior = "hang";
|
||||
stopCount = 0;
|
||||
const envelopeTransport = new PluginHostSshExecTransport({
|
||||
portForwardingBridge,
|
||||
execCommand: async () => ({ stdout: "ok", stderr: "", code: 0 }),
|
||||
measurePing: async () => 5,
|
||||
sshDialEnvelopeMs: 40,
|
||||
getSender: () => ({ id: 1 }),
|
||||
});
|
||||
|
||||
const startedAt = Date.now();
|
||||
await assert.rejects(
|
||||
envelopeTransport.exec(createBaseExecArgs()),
|
||||
(err) => err instanceof PluginRpcError
|
||||
&& err.code === RPC_ERRORS.deadlineExceeded
|
||||
&& err.message === "SSH connection timed out",
|
||||
);
|
||||
const elapsed = Date.now() - startedAt;
|
||||
assert.ok(elapsed < 2_000, `envelope abort should be fast, took ${elapsed}ms`);
|
||||
assert.equal(stopCount, 1, "envelope abort must stop the in-flight tunnel");
|
||||
assert.equal(envelopeTransport.pendingDials.size, 0);
|
||||
|
||||
envelopeTransport.shutdown();
|
||||
});
|
||||
|
||||
test("health check reuses healthy sockets and re-dials half-open or closed sockets", async () => {
|
||||
let dialCount = 0;
|
||||
let stopCount = 0;
|
||||
let currentConn = null;
|
||||
|
||||
const portForwardingBridge = {
|
||||
async startPortForward(_event, opts, hooks) {
|
||||
dialCount += 1;
|
||||
currentConn = createFakeConn();
|
||||
await hooks.bindChannels({
|
||||
conn: currentConn,
|
||||
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
|
||||
chainConnections: [],
|
||||
});
|
||||
return { success: true };
|
||||
},
|
||||
async stopPortForward() {
|
||||
stopCount += 1;
|
||||
return { success: true };
|
||||
},
|
||||
};
|
||||
|
||||
const transport = new PluginHostSshExecTransport({
|
||||
portForwardingBridge,
|
||||
execCommand: async () => ({ stdout: "ok", stderr: "", code: 0 }),
|
||||
measurePing: async () => 3,
|
||||
getSender: () => ({ id: 1 }),
|
||||
});
|
||||
|
||||
// Healthy socket is reused across consecutive execs.
|
||||
await transport.exec(createBaseExecArgs());
|
||||
await transport.exec(createBaseExecArgs());
|
||||
assert.equal(dialCount, 1);
|
||||
assert.equal(stopCount, 0);
|
||||
|
||||
const unhealthyMutations = [
|
||||
["writableEnded", (sock) => { sock.writableEnded = true; }],
|
||||
["readableEnded", (sock) => { sock.readableEnded = true; }],
|
||||
["destroyed", (sock) => { sock.destroyed = true; }],
|
||||
["writableFinished", (sock) => { sock.writableFinished = true; }],
|
||||
["writable=false", (sock) => { sock.writable = false; }],
|
||||
["readyState=closed", (sock) => { sock.readyState = "closed"; }],
|
||||
["readyState=readOnly", (sock) => { sock.readyState = "readOnly"; }],
|
||||
];
|
||||
|
||||
let expectedDials = 1;
|
||||
let expectedStops = 0;
|
||||
for (const [label, mutate] of unhealthyMutations) {
|
||||
mutate(currentConn._sock);
|
||||
await transport.exec(createBaseExecArgs());
|
||||
expectedDials += 1;
|
||||
expectedStops += 1;
|
||||
assert.equal(dialCount, expectedDials, `expected redial when socket has ${label}`);
|
||||
assert.equal(stopCount, expectedStops, `expected eviction when socket has ${label}`);
|
||||
}
|
||||
|
||||
// Omitting _sock completely remains healthy (backward-compatible with minimal fakes).
|
||||
delete currentConn._sock;
|
||||
await transport.exec(createBaseExecArgs());
|
||||
assert.equal(dialCount, expectedDials, "missing _sock must still reuse pooled entry");
|
||||
|
||||
transport.shutdown();
|
||||
});
|
||||
|
||||
test("evicts pooled entry on SSH_EXEC_OPEN_TIMEOUT and RPC deadline abort, but keeps it on user cancel", async () => {
|
||||
let dialCount = 0;
|
||||
let stopCount = 0;
|
||||
let execHandler = async () => ({ stdout: "ok", stderr: "", code: 0 });
|
||||
|
||||
const portForwardingBridge = {
|
||||
async startPortForward(_event, opts, hooks) {
|
||||
dialCount += 1;
|
||||
const conn = createFakeConn();
|
||||
await hooks.bindChannels({
|
||||
conn,
|
||||
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
|
||||
chainConnections: [],
|
||||
});
|
||||
return { success: true };
|
||||
},
|
||||
async stopPortForward() {
|
||||
stopCount += 1;
|
||||
return { success: true };
|
||||
},
|
||||
};
|
||||
|
||||
const transport = new PluginHostSshExecTransport({
|
||||
portForwardingBridge,
|
||||
execCommand: (conn, cmd, opts) => execHandler(conn, cmd, opts),
|
||||
measurePing: async () => 4,
|
||||
getSender: () => ({ id: 1 }),
|
||||
});
|
||||
|
||||
// Prime the pool.
|
||||
await transport.exec(createBaseExecArgs());
|
||||
assert.equal(dialCount, 1);
|
||||
assert.equal(stopCount, 0);
|
||||
|
||||
// 1) User cancel (RPC_ERRORS.cancelled) of a healthy running exec must NOT evict.
|
||||
execHandler = (_conn, _cmd, opts) => new Promise((_resolve, reject) => {
|
||||
opts.signal.addEventListener("abort", () => reject(opts.signal.reason || new Error("aborted")), { once: true });
|
||||
});
|
||||
const userAbort = new AbortController();
|
||||
const userCancelPromise = transport.exec(createBaseExecArgs({ signal: userAbort.signal }));
|
||||
setTimeout(() => userAbort.abort(new PluginRpcError(RPC_ERRORS.cancelled, "User cancelled")), 10);
|
||||
await assert.rejects(userCancelPromise, (err) => err.code === RPC_ERRORS.cancelled);
|
||||
assert.equal(stopCount, 0, "user cancel of healthy exec must not evict pooled entry");
|
||||
|
||||
execHandler = async () => ({ stdout: "reused", stderr: "", code: 0 });
|
||||
const reused = await transport.exec(createBaseExecArgs());
|
||||
assert.equal(reused.stdout, "reused");
|
||||
assert.equal(dialCount, 1, "pooled connection must be reused after healthy user cancel");
|
||||
|
||||
// 2) SSH_EXEC_OPEN_TIMEOUT must evict so next exec dials fresh.
|
||||
execHandler = async () => {
|
||||
const err = new Error("SSH exec channel open timed out after 10000 ms");
|
||||
err.code = "SSH_EXEC_OPEN_TIMEOUT";
|
||||
throw err;
|
||||
};
|
||||
await assert.rejects(
|
||||
transport.exec(createBaseExecArgs()),
|
||||
(err) => err.code === RPC_ERRORS.deadlineExceeded,
|
||||
);
|
||||
assert.equal(stopCount, 1, "SSH_EXEC_OPEN_TIMEOUT must evict pooled entry");
|
||||
|
||||
execHandler = async () => ({ stdout: "fresh-after-open-timeout", stderr: "", code: 0 });
|
||||
const afterOpenTimeout = await transport.exec(createBaseExecArgs());
|
||||
assert.equal(afterOpenTimeout.stdout, "fresh-after-open-timeout");
|
||||
assert.equal(dialCount, 2, "next exec after SSH_EXEC_OPEN_TIMEOUT must re-dial");
|
||||
|
||||
// 3) RPC deadline abort after connection acquisition must evict so next exec dials fresh.
|
||||
execHandler = (_conn, _cmd, opts) => new Promise((_resolve, reject) => {
|
||||
opts.signal.addEventListener("abort", () => reject(opts.signal.reason || new Error("aborted")), { once: true });
|
||||
});
|
||||
const deadlineAbort = new AbortController();
|
||||
const deadlinePromise = transport.exec(createBaseExecArgs({ signal: deadlineAbort.signal }));
|
||||
setTimeout(() => {
|
||||
deadlineAbort.abort(new PluginRpcError(RPC_ERRORS.deadlineExceeded, "Plugin request deadline exceeded"));
|
||||
}, 10);
|
||||
await assert.rejects(deadlinePromise, (err) => err.code === RPC_ERRORS.deadlineExceeded);
|
||||
assert.equal(stopCount, 2, "RPC deadline abort must evict pooled entry");
|
||||
|
||||
execHandler = async () => ({ stdout: "fresh-after-deadline", stderr: "", code: 0 });
|
||||
const afterDeadline = await transport.exec(createBaseExecArgs());
|
||||
assert.equal(afterDeadline.stdout, "fresh-after-deadline");
|
||||
assert.equal(dialCount, 3, "next exec after RPC deadline abort must re-dial");
|
||||
|
||||
transport.shutdown();
|
||||
});
|
||||
|
||||
test("premature stop before startPortForward registers retries after registration, cancels hung dial, and allows fresh retry", async () => {
|
||||
const sender = { id: 7 };
|
||||
let dialCount = 0;
|
||||
let firstTunnelId = null;
|
||||
const stopCalls = [];
|
||||
const registeredTunnels = new Map();
|
||||
|
||||
let resolveDialAtGate;
|
||||
const dialAtGate = new Promise((resolve) => { resolveDialAtGate = resolve; });
|
||||
let releaseRegistrationGate;
|
||||
const registrationGate = new Promise((resolve) => { releaseRegistrationGate = resolve; });
|
||||
let resolveFirstDialCancelled;
|
||||
const firstDialCancelled = new Promise((resolve) => { resolveFirstDialCancelled = resolve; });
|
||||
|
||||
const portForwardingBridge = {
|
||||
async startPortForward(_event, opts, hooks) {
|
||||
dialCount += 1;
|
||||
if (dialCount === 1) {
|
||||
firstTunnelId = opts.tunnelId;
|
||||
resolveDialAtGate();
|
||||
// Simulate preemption/delay before portForwardingTunnels.set(tunnelId, ...).
|
||||
await registrationGate;
|
||||
// Now register the tunnel and hang until stopPortForward cancels it.
|
||||
return new Promise((resolve) => {
|
||||
registeredTunnels.set(opts.tunnelId, () => {
|
||||
resolveFirstDialCancelled();
|
||||
resolve({ tunnelId: opts.tunnelId, success: false, cancelled: true });
|
||||
});
|
||||
});
|
||||
}
|
||||
const conn = createFakeConn();
|
||||
registeredTunnels.set(opts.tunnelId, () => {});
|
||||
await hooks.bindChannels({
|
||||
conn,
|
||||
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
|
||||
chainConnections: [],
|
||||
});
|
||||
return { success: true };
|
||||
},
|
||||
async stopPortForward(event, { tunnelId }) {
|
||||
const cancel = registeredTunnels.get(tunnelId);
|
||||
stopCalls.push({ sender: event?.sender, tunnelId, found: Boolean(cancel) });
|
||||
if (!cancel) {
|
||||
return { tunnelId, success: false, error: "Tunnel not found" };
|
||||
}
|
||||
registeredTunnels.delete(tunnelId);
|
||||
cancel();
|
||||
return { tunnelId, success: true };
|
||||
},
|
||||
};
|
||||
|
||||
const transport = new PluginHostSshExecTransport({
|
||||
portForwardingBridge,
|
||||
execCommand: async (_conn, command) => ({ stdout: `ok:${command}`, stderr: "", code: 0 }),
|
||||
measurePing: async () => 5,
|
||||
getSender: () => sender,
|
||||
});
|
||||
|
||||
const abort1 = new AbortController();
|
||||
const p1 = transport.exec(createBaseExecArgs({ command: "first", signal: abort1.signal }));
|
||||
|
||||
await dialAtGate;
|
||||
assert.ok(firstTunnelId, "tunnelId must be assigned before gate");
|
||||
assert.equal(registeredTunnels.size, 0, "tunnel must not be registered yet");
|
||||
assert.equal(transport.pendingDials.size, 1);
|
||||
|
||||
// Last waiter aborts BEFORE startPortForward registers the tunnel.
|
||||
abort1.abort(new PluginRpcError(RPC_ERRORS.deadlineExceeded, "Plugin request deadline exceeded"));
|
||||
await assert.rejects(p1, (err) => err.code === RPC_ERRORS.deadlineExceeded);
|
||||
assert.equal(transport.pendingDials.size, 0, "pendingDials must be cleared immediately");
|
||||
assert.ok(stopCalls.length >= 1, "initial stop attempt must have fired");
|
||||
assert.equal(stopCalls[0].tunnelId, firstTunnelId);
|
||||
assert.equal(stopCalls[0].sender, sender);
|
||||
assert.equal(stopCalls[0].found, false, "initial stop before registration must report Tunnel not found");
|
||||
|
||||
// Allow startPortForward to register and begin the hung handshake.
|
||||
releaseRegistrationGate();
|
||||
|
||||
// Wait for the retry stop to cancel the newly registered hung dial.
|
||||
await Promise.race([
|
||||
firstDialCancelled,
|
||||
new Promise((_, reject) => setTimeout(() => reject(new Error("Hung dial was not cancelled after registration")), 2_000)),
|
||||
]);
|
||||
|
||||
// Give settlement microtasks / any stale timer a moment to confirm no double-close.
|
||||
await new Promise((r) => setTimeout(r, 40));
|
||||
|
||||
const confirmedStopsForFirst = stopCalls.filter((c) => c.tunnelId === firstTunnelId && c.found);
|
||||
assert.equal(confirmedStopsForFirst.length, 1, "stopPortForward must succeed once after registration without double-closing");
|
||||
assert.equal(registeredTunnels.size, 0, "no zombie tunnel may remain registered");
|
||||
assert.equal(transport.pendingDials.size, 0);
|
||||
|
||||
// A later retry must start a fresh dial and succeed without being stopped.
|
||||
const res2 = await transport.exec(createBaseExecArgs({ command: "retry" }));
|
||||
assert.equal(res2.stdout, "ok:retry");
|
||||
assert.equal(dialCount, 2, "retry must start a fresh dial");
|
||||
assert.equal(transport.connections.size, 1);
|
||||
assert.equal(registeredTunnels.size, 1, "live retry tunnel must remain active");
|
||||
|
||||
transport.shutdown();
|
||||
});
|
||||
|
||||
test("post-return abort stops tunnel after early Tunnel not found on both success and throw", async () => {
|
||||
const stopCalls = [];
|
||||
const registeredTunnels = new Map();
|
||||
let dialCount = 0;
|
||||
|
||||
let resolveGateReached;
|
||||
let gateReached;
|
||||
let releaseGate;
|
||||
let gate;
|
||||
let resolveRegistered;
|
||||
let registered;
|
||||
let mode = "succeed";
|
||||
|
||||
const resetGate = () => {
|
||||
gateReached = new Promise((resolve) => { resolveGateReached = resolve; });
|
||||
gate = new Promise((resolve) => { releaseGate = resolve; });
|
||||
registered = new Promise((resolve) => { resolveRegistered = resolve; });
|
||||
};
|
||||
|
||||
const portForwardingBridge = {
|
||||
async startPortForward(_event, opts, hooks) {
|
||||
dialCount += 1;
|
||||
if (mode === "succeed" || mode === "throw") {
|
||||
resolveGateReached(opts.tunnelId);
|
||||
await gate;
|
||||
registeredTunnels.set(opts.tunnelId, () => {});
|
||||
resolveRegistered();
|
||||
if (mode === "throw") {
|
||||
throw new Error("late dial failure");
|
||||
}
|
||||
const conn = createFakeConn();
|
||||
await hooks.bindChannels({
|
||||
conn,
|
||||
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
|
||||
chainConnections: [],
|
||||
});
|
||||
return { success: true };
|
||||
}
|
||||
const conn = createFakeConn();
|
||||
registeredTunnels.set(opts.tunnelId, () => {});
|
||||
await hooks.bindChannels({
|
||||
conn,
|
||||
tunnelState: { status: "connecting", tunnelId: opts.tunnelId },
|
||||
chainConnections: [],
|
||||
});
|
||||
return { success: true };
|
||||
},
|
||||
async stopPortForward(_event, { tunnelId }) {
|
||||
const found = registeredTunnels.has(tunnelId);
|
||||
stopCalls.push({ tunnelId, found });
|
||||
if (!found) {
|
||||
return { tunnelId, success: false, error: "Tunnel not found" };
|
||||
}
|
||||
registeredTunnels.delete(tunnelId);
|
||||
return { tunnelId, success: true };
|
||||
},
|
||||
};
|
||||
|
||||
const transport = new PluginHostSshExecTransport({
|
||||
portForwardingBridge,
|
||||
execCommand: async (_conn, command) => ({ stdout: `ok:${command}`, stderr: "", code: 0 }),
|
||||
measurePing: async () => 3,
|
||||
getSender: () => ({ id: 2 }),
|
||||
});
|
||||
|
||||
// 1) startPortForward resolves { success: true } immediately after an early Tunnel not found.
|
||||
resetGate();
|
||||
mode = "succeed";
|
||||
const abort1 = new AbortController();
|
||||
const p1 = transport.exec(createBaseExecArgs({ hostId: "host-a", signal: abort1.signal }));
|
||||
const tunnelId1 = await gateReached;
|
||||
abort1.abort(new PluginRpcError(RPC_ERRORS.cancelled, "cancelled"));
|
||||
await assert.rejects(p1, (err) => err.code === RPC_ERRORS.cancelled);
|
||||
assert.equal(stopCalls.filter((c) => c.tunnelId === tunnelId1 && !c.found).length, 1);
|
||||
releaseGate();
|
||||
await registered;
|
||||
|
||||
for (let i = 0; i < 50 && registeredTunnels.has(tunnelId1); i += 1) {
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
}
|
||||
assert.equal(registeredTunnels.has(tunnelId1), false, "post-return abort must stop tunnel that succeeded after early not-found");
|
||||
assert.equal(stopCalls.filter((c) => c.tunnelId === tunnelId1 && c.found).length, 1);
|
||||
assert.equal(transport.connections.size, 0);
|
||||
assert.equal(transport.pendingDials.size, 0);
|
||||
|
||||
// 2) startPortForward throws after an early Tunnel not found.
|
||||
resetGate();
|
||||
mode = "throw";
|
||||
const abort2 = new AbortController();
|
||||
const p2 = transport.exec(createBaseExecArgs({ hostId: "host-b", signal: abort2.signal }));
|
||||
const tunnelId2 = await gateReached;
|
||||
abort2.abort(new PluginRpcError(RPC_ERRORS.cancelled, "cancelled"));
|
||||
await assert.rejects(p2, (err) => err.code === RPC_ERRORS.cancelled);
|
||||
assert.equal(stopCalls.filter((c) => c.tunnelId === tunnelId2 && !c.found).length, 1);
|
||||
releaseGate();
|
||||
await registered;
|
||||
|
||||
for (let i = 0; i < 50 && registeredTunnels.has(tunnelId2); i += 1) {
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
}
|
||||
assert.equal(registeredTunnels.has(tunnelId2), false, "post-throw abort must stop tunnel after early not-found");
|
||||
assert.equal(stopCalls.filter((c) => c.tunnelId === tunnelId2 && c.found).length, 1);
|
||||
assert.equal(transport.pendingDials.size, 0);
|
||||
|
||||
// 3) Later retry succeeds fresh.
|
||||
mode = "normal";
|
||||
const res = await transport.exec(createBaseExecArgs({ hostId: "host-a", command: "after-cleanup" }));
|
||||
assert.equal(res.stdout, "ok:after-cleanup");
|
||||
assert.equal(dialCount, 3);
|
||||
assert.equal(transport.connections.size, 1);
|
||||
|
||||
transport.shutdown();
|
||||
});
|
||||
Reference in new issue
Block a user