Skip to content

Commit c5bd05a

Browse files
noamsmall18claude
andcommitted
fix(ssh): closeLocalTunnels also kills tunnels that are still connecting
A tunnel's ssh process is spawned before its entry reaches the tunnel map, so a closeLocalTunnels during a connect missed it and the update still orphaned that forward. Track connecting tunnel scopes and close them too; a connect whose scope was taken fails instead of registering. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 9f45802 commit c5bd05a

2 files changed

Lines changed: 59 additions & 15 deletions

File tree

‎packages/ssh/src/tunnel.test.ts‎

Lines changed: 39 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import * as Clock from "effect/Clock";
1212
import * as Deferred from "effect/Deferred";
1313
import * as Duration from "effect/Duration";
1414
import * as Effect from "effect/Effect";
15+
import * as Exit from "effect/Exit";
1516
import * as Fiber from "effect/Fiber";
1617
import * as FileSystem from "effect/FileSystem";
1718
import * as Layer from "effect/Layer";
@@ -701,18 +702,27 @@ describe("ssh tunnel scripts", () => {
701702
}),
702703
);
703704

704-
it.effect("closes every local tunnel without stopping the remote servers", () =>
705+
it.effect("closes connected and connecting local tunnels without stopping remote servers", () =>
705706
Effect.gen(function* () {
706-
let tunnelKills = 0;
707+
const killedTunnels = new Set<string>();
708+
const connectingTunnelSpawned = yield* Deferred.make<void>();
707709
let remoteStops = 0;
710+
let nextLocalPort = 41_773;
711+
const connectingPort = 41_774;
708712
const spawner = ChildProcessSpawner.make((command) =>
709-
Effect.sync(() => {
713+
Effect.gen(function* () {
710714
const args = commandArgs(command);
711715
if (args.includes("-G")) return makeSuccessfulProcess("");
712716
if (args.includes("-N")) {
713-
return makeRunningProcess(() => {
714-
tunnelKills += 1;
715-
});
717+
const host = args.at(-1) ?? "";
718+
if (args.includes(`${connectingPort}:127.0.0.1:3773`)) {
719+
yield* Deferred.succeed(connectingTunnelSpawned, undefined);
720+
}
721+
// Like the real spawner, closing the spawn scope kills the process.
722+
return yield* Effect.acquireRelease(
723+
Effect.succeed(makeRunningProcess(() => killedTunnels.add(host))),
724+
(tunnel) => tunnel.kill().pipe(Effect.ignore),
725+
);
716726
}
717727
if (args.some((arg, index) => arg === "-s" && args[index + 1] === "--")) {
718728
return makeSuccessfulProcess('{"remotePort":3773}\n');
@@ -726,24 +736,39 @@ describe("ssh tunnel scripts", () => {
726736
NodeCrypto.layer,
727737
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
728738
Layer.succeed(HttpClient.HttpClient, testHttpClient),
729-
Layer.succeed(NetService.NetService, testNetService),
739+
Layer.succeed(
740+
NetService.NetService,
741+
NetService.NetService.of({
742+
...testNetService,
743+
reserveLoopbackPort: () => Effect.sync(() => nextLocalPort++),
744+
hasListenerOnHost: (port) => Effect.succeed(port !== connectingPort),
745+
}),
746+
),
730747
SshAuth.SshPasswordPrompt.disabledLayer,
731748
SshTunnel.SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }),
732749
);
733750
yield* Effect.gen(function* () {
734751
const manager = yield* SshTunnel.SshEnvironmentManager;
735-
for (const host of ["devbox", "other"]) {
736-
yield* manager.ensureEnvironment({
737-
alias: host,
738-
hostname: host,
752+
yield* manager.ensureEnvironment({
753+
alias: "devbox",
754+
hostname: "devbox",
755+
username: null,
756+
port: null,
757+
});
758+
const connecting = yield* Effect.forkChild(
759+
manager.ensureEnvironment({
760+
alias: "other",
761+
hostname: "other",
739762
username: null,
740763
port: null,
741-
});
742-
}
764+
}),
765+
);
766+
yield* Deferred.await(connectingTunnelSpawned);
743767

744768
yield* manager.closeLocalTunnels();
745769

746-
assert.equal(tunnelKills, 2);
770+
assert.isTrue(Exit.isFailure(yield* Fiber.await(connecting)));
771+
assert.deepEqual([...killedTunnels].sort(), ["devbox", "other"]);
747772
assert.equal(remoteStops, 0);
748773
}).pipe(Effect.provide(layer), Effect.scoped);
749774
}),

‎packages/ssh/src/tunnel.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1475,6 +1475,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
14751475
): Effect.fn.Return<SshEnvironmentManagerShape, never, Scope.Scope> {
14761476
const managerScope = yield* Scope.Scope;
14771477
const tunnels = new Map<string, SshTunnelEntry>();
1478+
const connectingTunnelScopes = new Set<Scope.Closeable>();
14781479
const targetLocks = yield* KeyedLock.make<string>();
14791480
const authSecrets = new Map<string, string>();
14801481

@@ -1662,6 +1663,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
16621663
remotePort,
16631664
});
16641665
const entryScope = yield* Scope.make("sequential");
1666+
connectingTunnelScopes.add(entryScope);
16651667
const tunnelEntry = yield* runWithSshAuth({
16661668
key: input.key,
16671669
target: input.resolvedTarget,
@@ -1679,9 +1681,19 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
16791681
}),
16801682
}).pipe(
16811683
Effect.onExit((exit) =>
1682-
Exit.isSuccess(exit) ? Effect.void : Scope.close(entryScope, Exit.void).pipe(Effect.ignore),
1684+
Exit.isSuccess(exit)
1685+
? Effect.void
1686+
: Effect.sync(() => connectingTunnelScopes.delete(entryScope)).pipe(
1687+
Effect.andThen(Scope.close(entryScope, Exit.void)),
1688+
Effect.ignore,
1689+
),
16831690
),
16841691
);
1692+
if (!connectingTunnelScopes.delete(entryScope)) {
1693+
return yield* new SshReadinessError({
1694+
message: `SSH tunnel to ${input.resolvedTarget.alias} was closed while connecting.`,
1695+
});
1696+
}
16851697
tunnels.set(input.key, tunnelEntry);
16861698
const spawnerService = yield* ChildProcessSpawner.ChildProcessSpawner;
16871699
const digestService = yield* Digest.Digest;
@@ -1905,9 +1917,16 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
19051917

19061918
const closeLocalTunnels = Effect.fn("ssh/tunnel.closeLocalTunnels")(function* () {
19071919
const entries = [...tunnels.values()];
1920+
// Closing a connecting scope kills its spawned ssh before it reaches the map.
1921+
const connectingScopes = [...connectingTunnelScopes];
19081922
// Entries no longer in the map skip the remote stop in their finalizer.
19091923
tunnels.clear();
1924+
connectingTunnelScopes.clear();
19101925
yield* Effect.forEach(entries, closeTunnelEntry, { concurrency: "unbounded", discard: true });
1926+
yield* Effect.forEach(connectingScopes, (scope) => Scope.close(scope, Exit.void), {
1927+
concurrency: "unbounded",
1928+
discard: true,
1929+
});
19111930
});
19121931

19131932
return SshEnvironmentManager.of({ ensureEnvironment, disconnectEnvironment, closeLocalTunnels });

0 commit comments

Comments
 (0)