Delay SSH tunnel disposal until pending setup settles

- Fix auth-failure matching for permission denied variants
- Allow remote port picker to run without a state file path
- Dispose only after pending tunnel creation resolves
This commit is contained in:
Julius Marminge committed 2026-04-27 18:37:13 -07:00
1 parent 02e194c000
commit db6a2a6dc1
3 files changed
+71 -5

No files matched your search

+65 -1
View File
@@ -5,9 +5,10 @@ import * as Path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { __test, discoverDesktopSshHosts } from "./sshEnvironment.ts";
import { __test, DesktopSshEnvironmentManager, discoverDesktopSshHosts } from "./sshEnvironment.ts";
const tempDirectories: string[] = [];
type TunnelEntry = Parameters<typeof __test.stopTunnel>[0];
afterEach(() => {
for (const directory of tempDirectories.splice(0)) {
@@ -255,10 +256,17 @@ describe("sshEnvironment", () => {
),
),
).toBe(true);
expect(__test.isSshAuthFailure(new Error("Permission denied (publickey)."))).toBe(true);
expect(__test.isSshAuthFailure(new Error("Connection timed out"))).toBe(false);
expect(__test.isSshAuthFailure(new Error("mkdir: Permission denied"))).toBe(false);
});
it("allows the remote port picker to run without a state file path", () => {
expect(__test.readSshScriptTemplate("remote-pick-port.cjs")).toContain(
'const filePath = process.argv[2] ?? "";',
);
});
it("settles tunnel shutdown if the child exits before the exit listener attaches", async () => {
vi.useFakeTimers();
@@ -307,4 +315,60 @@ describe("sshEnvironment", () => {
vi.useRealTimers();
}
});
it("waits for pending tunnel creation before disposing completed tunnels", async () => {
class ControlledChildProcess extends EventEmitter {
exitCode: number | null = null;
signalCode: NodeJS.Signals | null = null;
readonly killSignals: Array<NodeJS.Signals | undefined> = [];
kill(signal?: NodeJS.Signals | number): boolean {
this.killSignals.push(typeof signal === "string" ? signal : undefined);
this.signalCode = "SIGTERM";
this.emit("exit", null, this.signalCode);
return true;
}
}
let resolvePending!: (entry: TunnelEntry) => void;
const child = new ControlledChildProcess();
const entry: TunnelEntry = {
key: "devbox",
target: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
remotePort: 3773,
localPort: 3774,
httpBaseUrl: "http://127.0.0.1:3774/",
wsBaseUrl: "ws://127.0.0.1:3774/",
process: child as never,
};
const manager = new DesktopSshEnvironmentManager();
const internals = manager as unknown as {
pendingTunnelEntries: Map<string, Promise<TunnelEntry>>;
tunnels: Map<string, TunnelEntry>;
};
const pending = new Promise<TunnelEntry>((resolve) => {
resolvePending = resolve;
}).then((completedEntry) => {
internals.tunnels.set(completedEntry.key, completedEntry);
return completedEntry;
});
internals.pendingTunnelEntries.set(entry.key, pending);
const disposePromise = manager.dispose();
await Promise.resolve();
expect(child.killSignals).toEqual([]);
resolvePending(entry);
await disposePromise;
expect(child.killSignals).toEqual(["SIGTERM"]);
expect(internals.tunnels.size).toBe(0);
expect(internals.pendingTunnelEntries.size).toBe(0);
});
});
+5 -3
View File
@@ -472,7 +472,7 @@ function isSshAuthFailure(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error);
const normalized = message.toLowerCase();
return (
/permission denied \((?:publickey|password|keyboard-interactive|hostbased|gssapi-with-mic)[^)]+\)/u.test(
/permission denied \((?:publickey|password|keyboard-interactive|hostbased|gssapi-with-mic)[^)]*\)/u.test(
normalized,
) ||
/authentication failed/u.test(normalized) ||
@@ -1019,13 +1019,12 @@ export class DesktopSshEnvironmentManager {
.then(() => resolve())
.catch((error: unknown) => reject(error));
});
this.tunnels.set(key, tunnelEntry);
try {
await tunnelReady;
this.tunnels.set(key, tunnelEntry);
return tunnelEntry;
} catch (error) {
await stopTunnel(tunnelEntry).catch(() => undefined);
this.deleteTunnelIfCurrent(tunnelEntry);
throw error;
}
});
@@ -1039,6 +1038,8 @@ export class DesktopSshEnvironmentManager {
}
async dispose(): Promise<void> {
const pending = [...this.pendingTunnelEntries.values()];
await Promise.allSettled(pending);
const entries = [...this.tunnels.values()];
this.tunnels.clear();
this.pendingTunnelEntries.clear();
@@ -1372,6 +1373,7 @@ export const __test = {
normalizeKnownHostsHostname,
parseKnownHostsHostnames,
parseSshResolveOutput,
readSshScriptTemplate,
resolveSshConfigIncludePattern,
stopTunnel,
};
@@ -1,6 +1,6 @@
const fs = require("node:fs");
const net = require("node:net");
const filePath = process.argv[2];
const filePath = process.argv[2] ?? "";
const defaultPort = Number.parseInt(process.argv[3] ?? "", 10);
const scanWindow = Number.parseInt(process.argv[4] ?? "", 10);
const raw = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf8").trim() : "";