Skip to content

Commit 1b78b65

Browse files
only21milclaudemaria-rcks
authored
fix(ssh): reuse one askpass helper directory instead of a new temp dir per command (#22123)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent 120dbb0 commit 1b78b65

2 files changed

Lines changed: 211 additions & 11 deletions

File tree

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

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
import * as NodeServices from "@effect/platform-node/NodeServices";
22
import { assert, describe, it } from "@effect/vitest";
33

4+
import * as Deferred from "effect/Deferred";
45
import * as Effect from "effect/Effect";
6+
import * as Fiber from "effect/Fiber";
57
import * as FileSystem from "effect/FileSystem";
68
import * as Layer from "effect/Layer";
9+
import * as Option from "effect/Option";
710
import * as Path from "effect/Path";
811
import * as HostProcess from "@t3tools/shared/HostProcess";
12+
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
913

1014
import { buildSshChildEnvironment, isSshAuthFailure } from "./auth.ts";
1115

@@ -50,4 +54,169 @@ describe("ssh auth", () => {
5054
Effect.scoped,
5155
),
5256
);
57+
58+
it.effect("reuses the default askpass directory across interactive commands", () =>
59+
Effect.gen(function* () {
60+
const fs = yield* FileSystem.FileSystem;
61+
const path = yield* Path.Path;
62+
const askpassPath = () =>
63+
buildSshChildEnvironment({ interactiveAuth: true, authSecret: "pw" }).pipe(
64+
Effect.map((env) => env.SSH_ASKPASS ?? ""),
65+
);
66+
const runtimeDirectoryOf = (askpass: string) => path.dirname(path.dirname(askpass));
67+
68+
const first = yield* askpassPath();
69+
assert.equal(yield* askpassPath(), first);
70+
71+
yield* fs.remove(runtimeDirectoryOf(first), { recursive: true });
72+
const recreated = yield* askpassPath();
73+
assert.notEqual(recreated, first);
74+
assert.equal(yield* fs.exists(recreated), true);
75+
76+
const cachedOwner = yield* fs.stat(runtimeDirectoryOf(recreated));
77+
const otherUser = yield* askpassPath().pipe(
78+
Effect.provideService(
79+
HostProcess.UserId,
80+
(Option.getOrUndefined(cachedOwner.uid) ?? 0) + 1,
81+
),
82+
);
83+
assert.notEqual(otherUser, recreated);
84+
85+
yield* fs.remove(runtimeDirectoryOf(recreated), { recursive: true });
86+
yield* fs.remove(runtimeDirectoryOf(otherUser), { recursive: true });
87+
}).pipe(
88+
Effect.provide(Layer.merge(NodeServices.layer, Layer.succeed(HostProcess.Platform, "linux"))),
89+
),
90+
);
91+
92+
it.effect.skipIf(!symlinksSupported)(
93+
"does not reuse a symlink left at the default askpass directory path",
94+
() =>
95+
Effect.gen(function* () {
96+
const fs = yield* FileSystem.FileSystem;
97+
const path = yield* Path.Path;
98+
const askpassPath = () =>
99+
buildSshChildEnvironment({ interactiveAuth: true, authSecret: "pw" }).pipe(
100+
Effect.map((env) => env.SSH_ASKPASS ?? ""),
101+
);
102+
const runtimeDirectoryOf = (askpass: string) => path.dirname(path.dirname(askpass));
103+
104+
const first = yield* askpassPath();
105+
const ownedTarget = yield* fs.makeTempDirectory({ prefix: "t3code-ssh-symlink-target-" });
106+
yield* fs.remove(runtimeDirectoryOf(first), { recursive: true });
107+
yield* fs.symlink(ownedTarget, runtimeDirectoryOf(first));
108+
109+
const next = yield* askpassPath();
110+
assert.notEqual(next, first);
111+
assert.equal(yield* fs.exists(path.join(ownedTarget, "t3code-ssh-askpass")), false);
112+
113+
yield* fs.remove(runtimeDirectoryOf(first));
114+
yield* fs.remove(ownedTarget, { recursive: true });
115+
yield* fs.remove(runtimeDirectoryOf(next), { recursive: true });
116+
}).pipe(
117+
Effect.provide(
118+
Layer.merge(NodeServices.layer, Layer.succeed(HostProcess.Platform, "linux")),
119+
),
120+
),
121+
);
122+
123+
it.effect("writes the default askpass helper once when interactive commands overlap", () =>
124+
Effect.gen(function* () {
125+
const fs = yield* FileSystem.FileSystem;
126+
const runtimeDirectories: Array<string> = [];
127+
yield* Effect.addFinalizer(() =>
128+
Effect.forEach(runtimeDirectories, (directory) =>
129+
fs.remove(directory, { recursive: true }).pipe(Effect.ignore),
130+
),
131+
);
132+
133+
// The first helper write of each round waits for the test, so the second command starts
134+
// while the first is still setting up and must not touch the shared files until it is done.
135+
let gate: { arrived: Deferred.Deferred<void>; release: Deferred.Deferred<void> } | undefined;
136+
let fileCalls = 0;
137+
let helperWrites = 0;
138+
const counted = <A, E>(effect: Effect.Effect<A, E>) =>
139+
Effect.suspend(() => {
140+
fileCalls += 1;
141+
return effect;
142+
});
143+
const trackedFs: FileSystem.FileSystem = {
144+
...fs,
145+
makeTempDirectory: (options) =>
146+
counted(fs.makeTempDirectory(options)).pipe(
147+
Effect.tap((directory) => Effect.sync(() => runtimeDirectories.push(directory))),
148+
),
149+
stat: (path) => counted(fs.stat(path)),
150+
exists: (path) => counted(fs.exists(path)),
151+
writeFileString: (path, data, options) =>
152+
counted(
153+
Effect.gen(function* () {
154+
helperWrites += 1;
155+
const held = gate;
156+
gate = undefined;
157+
if (held) {
158+
yield* Deferred.succeed(held.arrived, undefined);
159+
yield* Deferred.await(held.release);
160+
}
161+
yield* fs.writeFileString(path, data, options);
162+
}),
163+
),
164+
};
165+
const askpassPath = buildSshChildEnvironment({
166+
interactiveAuth: true,
167+
authSecret: "pw",
168+
}).pipe(
169+
Effect.map((env) => env.SSH_ASKPASS ?? ""),
170+
Effect.provideService(FileSystem.FileSystem, trackedFs),
171+
);
172+
const twoOverlappingCommands = Effect.gen(function* () {
173+
const held = {
174+
arrived: yield* Deferred.make<void>(),
175+
release: yield* Deferred.make<void>(),
176+
};
177+
gate = held;
178+
const first = yield* Effect.forkChild(askpassPath);
179+
yield* Deferred.await(held.arrived);
180+
const callsBefore = fileCalls;
181+
const second = yield* askpassPath.pipe(Effect.forkChild({ startImmediately: true }));
182+
assert.equal(fileCalls, callsBefore, "second command touched the files mid-setup");
183+
yield* Deferred.succeed(held.release, undefined);
184+
return [yield* Fiber.join(first), yield* Fiber.join(second)] as const;
185+
});
186+
187+
const [first, second] = yield* twoOverlappingCommands;
188+
assert.equal(second, first);
189+
assert.equal(runtimeDirectories.length, 1);
190+
assert.equal(helperWrites, 1);
191+
192+
yield* fs.remove(first);
193+
assert.deepStrictEqual(yield* twoOverlappingCommands, [first, first]);
194+
assert.equal(runtimeDirectories.length, 1);
195+
assert.equal(helperWrites, 2);
196+
197+
yield* fs.remove(first);
198+
const held = {
199+
arrived: yield* Deferred.make<void>(),
200+
release: yield* Deferred.make<void>(),
201+
};
202+
gate = held;
203+
const cancelled = yield* Effect.forkChild(askpassPath);
204+
yield* Deferred.await(held.arrived);
205+
const callsBeforeCancellation = fileCalls;
206+
const interruption = yield* Fiber.interrupt(cancelled).pipe(
207+
Effect.forkChild({ startImmediately: true }),
208+
);
209+
const next = yield* askpassPath.pipe(Effect.forkChild({ startImmediately: true }));
210+
const callsDuringCancellation = fileCalls;
211+
yield* Deferred.succeed(held.release, undefined);
212+
yield* Fiber.join(interruption);
213+
assert.equal(yield* Fiber.join(next), first);
214+
assert.equal(callsDuringCancellation, callsBeforeCancellation);
215+
assert.equal(helperWrites, 3);
216+
assert.include(yield* fs.readFileString(first), 'printf "%s\\n" "$T3_SSH_AUTH_SECRET"');
217+
}).pipe(
218+
Effect.provide(Layer.merge(NodeServices.layer, Layer.succeed(HostProcess.Platform, "linux"))),
219+
Effect.scoped,
220+
),
221+
);
53222
});

‎packages/ssh/src/auth.ts‎

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import * as Layer from "effect/Layer";
77
import * as Option from "effect/Option";
88
import * as Path from "effect/Path";
99
import * as PlatformError from "effect/PlatformError";
10+
import * as Semaphore from "effect/Semaphore";
1011

1112
import { SshPasswordPromptError } from "./errors.ts";
1213

@@ -101,15 +102,6 @@ if ($null -ne $env:T3_SSH_AUTH_SECRET) {\r
101102
exit 1\r
102103
`;
103104

104-
const getDefaultSshAskpassDirectory = Effect.fn("ssh/auth.getDefaultSshAskpassDirectory")(
105-
function* () {
106-
const fs = yield* FileSystem.FileSystem;
107-
const path = yield* Path.Path;
108-
const parentDirectory = yield* fs.makeTempDirectory({ prefix: "t3code-ssh-runtime-" });
109-
return path.join(parentDirectory, SSH_ASKPASS_DIR_NAME);
110-
},
111-
);
112-
113105
const buildSshAskpassHelperDescriptor = Effect.fn("ssh/auth.buildSshAskpassHelperDescriptor")(
114106
function* (input: {
115107
readonly directory: string;
@@ -172,6 +164,43 @@ const ensureSshAskpassHelpers = Effect.fn("ssh/auth.ensureSshAskpassHelpers")(fu
172164
return descriptor.launcherPath;
173165
});
174166

167+
// Keep setup serialized through cancellation so writes finish before another command uses the helper.
168+
let defaultSshAskpassRuntimeDirectory: string | undefined;
169+
const defaultSshAskpassLock = Semaphore.makeUnsafe(1);
170+
171+
const ensureDefaultSshAskpassHelpers = Effect.fn("ssh/auth.ensureDefaultSshAskpassHelpers")(
172+
function* () {
173+
const fs = yield* FileSystem.FileSystem;
174+
const path = yield* Path.Path;
175+
const userId = yield* HostProcess.UserId;
176+
let runtimeDirectory = defaultSshAskpassRuntimeDirectory;
177+
if (runtimeDirectory !== undefined) {
178+
const cached = runtimeDirectory;
179+
const reusable = yield* Effect.all([fs.realPath(cached), fs.stat(cached)]).pipe(
180+
Effect.map(
181+
([resolved, info]) =>
182+
resolved === cached &&
183+
info.type === "Directory" &&
184+
(userId === undefined || Option.getOrUndefined(info.uid) === userId),
185+
),
186+
Effect.orElseSucceed(() => false),
187+
);
188+
if (!reusable) {
189+
runtimeDirectory = undefined;
190+
}
191+
}
192+
runtimeDirectory ??= yield* fs.realPath(
193+
yield* fs.makeTempDirectory({ prefix: "t3code-ssh-runtime-" }),
194+
);
195+
const launcherPath = yield* ensureSshAskpassHelpers({
196+
directory: path.join(runtimeDirectory, SSH_ASKPASS_DIR_NAME),
197+
});
198+
defaultSshAskpassRuntimeDirectory = runtimeDirectory;
199+
return launcherPath;
200+
},
201+
(effect) => defaultSshAskpassLock.withPermit(Effect.uninterruptible(effect)),
202+
);
203+
175204
export const buildSshChildEnvironment = Effect.fn("ssh/auth.buildSshChildEnvironment")(function* (
176205
input: SshChildEnvironmentOptions = {},
177206
): Effect.fn.Return<
@@ -192,8 +221,10 @@ export const buildSshChildEnvironment = Effect.fn("ssh/auth.buildSshChildEnviron
192221
Effect.orElseSucceed(() => Option.none<string>()),
193222
Effect.map(Option.getOrUndefined),
194223
);
195-
const directory = input.askpassDirectory ?? (yield* getDefaultSshAskpassDirectory());
196-
const sshAskpass = yield* ensureSshAskpassHelpers({ directory });
224+
const sshAskpass =
225+
input.askpassDirectory === undefined
226+
? yield* ensureDefaultSshAskpassHelpers()
227+
: yield* ensureSshAskpassHelpers({ directory: input.askpassDirectory });
197228

198229
return {
199230
...baseEnv,

0 commit comments

Comments
 (0)