Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Sink from "effect/Sink";
12import * as Stream from "effect/Stream";
13import { ChildProcessSpawner } from "effect/process";
14import * as HostProcess from "@t3tools/shared/HostProcess";
15import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
16
17import { buildSshChildEnvironment, isSshAgentSigningFailure, isSshAuthFailure } from "./auth.ts";
18
19describe("ssh auth", () => {
20 it.effect("detects ssh auth failures from common permission denied messages", () =>
21 Effect.sync(() => {
22 assert.equal(
23 isSshAuthFailure(
24 new Error(
25 "julius@100.65.180.100: Permission denied (publickey,password,keyboard-interactive).",
26 ),
27 ),
28 true,
29 );
30 assert.equal(isSshAuthFailure(new Error("Permission denied (publickey).")), true);
31 assert.equal(isSshAuthFailure(new Error("Connection timed out")), false);
32 assert.equal(isSshAuthFailure(new Error("mkdir: Permission denied")), false);
33 }),
34 );
35
36 it.effect("detects agent signing failures from current and pre-8.2 OpenSSH", () =>
37 Effect.sync(() => {
38 const denied = "julius@devbox: Permission denied (publickey,password).";
39 assert.isTrue(
40 isSshAgentSigningFailure(
41 new Error(
42 `sign_and_send_pubkey: signing failed for ED25519 "/home/julius/.ssh/id_ed25519" from agent: communication with agent failed\r\n${denied}`,
43 ),
44 ),
45 );
46 assert.isTrue(
47 isSshAgentSigningFailure(
48 new Error(`sign_and_send_pubkey: signing failed: agent refused operation\n${denied}`),
49 ),
50 );
51 assert.isTrue(
52 isSshAgentSigningFailure(
53 new Error(
54 `sign_and_send_pubkey: signing failed: communication with agent failed\n${denied}`,
55 ),
56 ),
57 );
58 assert.isFalse(
59 isSshAgentSigningFailure(
60 new Error(
61 `sign_and_send_pubkey: signing failed for ED25519-SK "/home/julius/.ssh/id_ed25519_sk": device not found\n${denied}`,
62 ),
63 ),
64 );
65 assert.isFalse(isSshAgentSigningFailure(new Error(denied)));
66 }),
67 );
68
69 it.effect("creates askpass env for cached password prompts", () =>
70 Effect.gen(function* () {
71 const fs = yield* FileSystem.FileSystem;
72 const path = yield* Path.Path;
73 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ssh-askpass-test-" });
74 const env = yield* buildSshChildEnvironment({
75 authSecret: "super-secret",
76 interactiveAuth: true,
77 askpassDirectory: directory,
78 baseEnv: {},
79 });
80
81 const askpassPath = path.join(directory, "ssh-askpass.sh");
82 assert.equal(env.SSH_ASKPASS, askpassPath);
83 assert.equal(env.SSH_ASKPASS_REQUIRE, "force");
84 assert.equal(env.T3_SSH_AUTH_SECRET, "super-secret");
85 assert.equal(env.DISPLAY, "t3code");
86 assert.equal(yield* fs.exists(askpassPath), true);
87 assert.include(yield* fs.readFileString(askpassPath), 'printf "%s\\n" "$T3_SSH_AUTH_SECRET"');
88 }).pipe(
89 Effect.provide(Layer.merge(NodeServices.layer, Layer.succeed(HostProcess.Platform, "linux"))),
90 ),
91 );
92
93 it.effect("picks the Windows askpass helper that the installed ssh client can start", () =>
94 Effect.gen(function* () {
95 const fs = yield* FileSystem.FileSystem;
96 const path = yield* Path.Path;
97 const temp = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ssh-askpass-test-" });
98 const dir = path.join(temp, "askpass");
99 const cases = [
100 {
101 banner: "OpenSSH_for_Windows_9.5p2, LibreSSL 3.8.2",
102 isExecutable: false,
103 askpass: `"C:\\fake\\node.exe" "${dir}\\ssh-askpass.cjs"`,
104 nodeOptions: undefined,
105 runAsNode: "1",
106 },
107 {
108 banner: "OpenSSH_for_Windows_8.1p1, LibreSSL 2.9.2",
109 execPath: "C:\\a.exe b\\node.EXE",
110 isExecutable: false,
111 askpass: `"C:\\a.exe b\\node.EXE" "${dir}\\ssh-askpass.cjs"`,
112 nodeOptions: undefined,
113 runAsNode: "1",
114 },
115 {
116 banner: "OpenSSH_for_Windows_9.5p2, LibreSSL 3.8.2",
117 isExecutable: true,
118 askpass: `"C:\\fake\\node.exe" "${dir}\\ssh-askpass.cjs"`,
119 nodeOptions: `--require "${dir.replaceAll("\\", "/")}/ssh-askpass.cjs"`,
120 runAsNode: "1",
121 },
122 {
123 banner: "OpenSSH_10.6p1, OpenSSL 3.5.9 29 Sep 2026",
124 isExecutable: false,
125 askpass: `${dir}\\ssh-askpass.sh`,
126 nodeOptions: undefined,
127 runAsNode: undefined,
128 },
129 ];
130 for (const testCase of cases) {
131 const spawned: Array<ReadonlyArray<string>> = [];
132 const spawner = ChildProcessSpawner.make((command) =>
133 Effect.sync(() => {
134 if (command._tag === "StandardCommand") {
135 spawned.push([command.command, ...command.args].map(String));
136 }
137 return ChildProcessSpawner.makeHandle({
138 pid: ChildProcessSpawner.ProcessId(123),
139 stdout: Stream.empty,
140 stderr: Stream.make(new TextEncoder().encode(`${testCase.banner}\r\n`)),
141 all: Stream.empty,
142 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
143 exitStatus: Effect.succeed({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(0) }),
144 isRunning: Effect.succeed(false),
145 kill: () => Effect.void,
146 stdin: Sink.drain,
147 getInputFd: () => Sink.drain,
148 getOutputFd: () => Stream.empty,
149 unref: Effect.succeed(Effect.void),
150 });
151 }),
152 );
153 const env = yield* buildSshChildEnvironment({
154 authSecret: "super-secret",
155 interactiveAuth: true,
156 askpassDirectory: dir,
157 baseEnv: {},
158 }).pipe(
159 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
160 Effect.provideService(HostProcess.IsExecutable, testCase.isExecutable),
161 Effect.provideService(
162 HostProcess.ExecutablePath,
163 testCase.execPath ?? "C:\\fake\\node.exe",
164 ),
165 );
166
167 assert.deepEqual(spawned, [["ssh.exe", "-V"]]);
168 assert.equal(env.SSH_ASKPASS, testCase.askpass);
169 assert.equal(env.NODE_OPTIONS, testCase.nodeOptions);
170 assert.equal(env.ELECTRON_RUN_AS_NODE, testCase.runAsNode);
171 assert.equal(env.SSH_ASKPASS_REQUIRE, "force");
172 assert.equal(env.T3_SSH_AUTH_SECRET, "super-secret");
173 }
174
175 assert.equal(yield* fs.exists(`${dir}\\ssh-askpass.cmd`), false);
176 assert.notInclude(yield* fs.readFileString(`${dir}\\ssh-askpass.cjs`), "process.argv");
177 assert.include(
178 yield* fs.readFileString(`${dir}\\ssh-askpass.sh`),
179 'printf "%s\\n" "$T3_SSH_AUTH_SECRET"',
180 );
181 }).pipe(
182 Effect.provide(Layer.merge(NodeServices.layer, Layer.succeed(HostProcess.Platform, "win32"))),
183 ),
184 );
185
186 it.effect("reuses the default askpass directory across interactive commands", () =>
187 Effect.gen(function* () {
188 const fs = yield* FileSystem.FileSystem;
189 const path = yield* Path.Path;
190 const askpassPath = () =>
191 buildSshChildEnvironment({ interactiveAuth: true, authSecret: "pw" }).pipe(
192 Effect.map((env) => env.SSH_ASKPASS ?? ""),
193 );
194 const runtimeDirectoryOf = (askpass: string) => path.dirname(path.dirname(askpass));
195
196 const first = yield* askpassPath();
197 assert.equal(yield* askpassPath(), first);
198
199 yield* fs.remove(runtimeDirectoryOf(first), { recursive: true });
200 const recreated = yield* askpassPath();
201 assert.notEqual(recreated, first);
202 assert.equal(yield* fs.exists(recreated), true);
203
204 const cachedOwner = yield* fs.stat(runtimeDirectoryOf(recreated));
205 const otherUser = yield* askpassPath().pipe(
206 Effect.provideService(
207 HostProcess.UserId,
208 (Option.getOrUndefined(cachedOwner.uid) ?? 0) + 1,
209 ),
210 );
211 assert.notEqual(otherUser, recreated);
212
213 yield* fs.remove(runtimeDirectoryOf(recreated), { recursive: true });
214 yield* fs.remove(runtimeDirectoryOf(otherUser), { recursive: true });
215 }).pipe(
216 Effect.provide(Layer.merge(NodeServices.layer, Layer.succeed(HostProcess.Platform, "linux"))),
217 ),
218 );
219
220 it.effect.skipIf(!symlinksSupported)(
221 "does not reuse a symlink left at the default askpass directory path",
222 () =>
223 Effect.gen(function* () {
224 const fs = yield* FileSystem.FileSystem;
225 const path = yield* Path.Path;
226 const askpassPath = () =>
227 buildSshChildEnvironment({ interactiveAuth: true, authSecret: "pw" }).pipe(
228 Effect.map((env) => env.SSH_ASKPASS ?? ""),
229 );
230 const runtimeDirectoryOf = (askpass: string) => path.dirname(path.dirname(askpass));
231
232 const first = yield* askpassPath();
233 const ownedTarget = yield* fs.makeTempDirectory({ prefix: "t3code-ssh-symlink-target-" });
234 yield* fs.remove(runtimeDirectoryOf(first), { recursive: true });
235 yield* fs.symlink(ownedTarget, runtimeDirectoryOf(first));
236
237 const next = yield* askpassPath();
238 assert.notEqual(next, first);
239 assert.equal(yield* fs.exists(path.join(ownedTarget, "t3code-ssh-askpass")), false);
240
241 yield* fs.remove(runtimeDirectoryOf(first));
242 yield* fs.remove(ownedTarget, { recursive: true });
243 yield* fs.remove(runtimeDirectoryOf(next), { recursive: true });
244 }).pipe(
245 Effect.provide(
246 Layer.merge(NodeServices.layer, Layer.succeed(HostProcess.Platform, "linux")),
247 ),
248 ),
249 );
250
251 it.effect("writes the default askpass helper once when interactive commands overlap", () =>
252 Effect.gen(function* () {
253 const fs = yield* FileSystem.FileSystem;
254 const runtimeDirectories: Array<string> = [];
255 yield* Effect.addFinalizer(() =>
256 Effect.forEach(runtimeDirectories, (directory) =>
257 fs.remove(directory, { recursive: true }).pipe(Effect.ignore),
258 ),
259 );
260
261 // The first helper write of each round waits for the test, so the second command starts
262 // while the first is still setting up and must not touch the shared files until it is done.
263 let gate: { arrived: Deferred.Deferred<void>; release: Deferred.Deferred<void> } | undefined;
264 let fileCalls = 0;
265 let helperWrites = 0;
266 const counted = <A, E>(effect: Effect.Effect<A, E>) =>
267 Effect.suspend(() => {
268 fileCalls += 1;
269 return effect;
270 });
271 const trackedFs: FileSystem.FileSystem = {
272 ...fs,
273 makeTempDirectory: (options) =>
274 counted(fs.makeTempDirectory(options)).pipe(
275 Effect.tap((directory) => Effect.sync(() => runtimeDirectories.push(directory))),
276 ),
277 stat: (path) => counted(fs.stat(path)),
278 exists: (path) => counted(fs.exists(path)),
279 writeFileString: (path, data, options) =>
280 counted(
281 Effect.gen(function* () {
282 helperWrites += 1;
283 const held = gate;
284 gate = undefined;
285 if (held) {
286 yield* Deferred.succeed(held.arrived, undefined);
287 yield* Deferred.await(held.release);
288 }
289 yield* fs.writeFileString(path, data, options);
290 }),
291 ),
292 };
293 const askpassPath = buildSshChildEnvironment({
294 interactiveAuth: true,
295 authSecret: "pw",
296 }).pipe(
297 Effect.map((env) => env.SSH_ASKPASS ?? ""),
298 Effect.provideService(FileSystem.FileSystem, trackedFs),
299 );
300 const twoOverlappingCommands = Effect.gen(function* () {
301 const held = {
302 arrived: yield* Deferred.make<void>(),
303 release: yield* Deferred.make<void>(),
304 };
305 gate = held;
306 const first = yield* Effect.forkChild(askpassPath);
307 yield* Deferred.await(held.arrived);
308 const callsBefore = fileCalls;
309 const second = yield* askpassPath.pipe(Effect.forkChild({ startImmediately: true }));
310 assert.equal(fileCalls, callsBefore, "second command touched the files mid-setup");
311 yield* Deferred.succeed(held.release, undefined);
312 return [yield* Fiber.join(first), yield* Fiber.join(second)] as const;
313 });
314
315 const [first, second] = yield* twoOverlappingCommands;
316 assert.equal(second, first);
317 assert.equal(runtimeDirectories.length, 1);
318 assert.equal(helperWrites, 1);
319
320 yield* fs.remove(first);
321 assert.deepStrictEqual(yield* twoOverlappingCommands, [first, first]);
322 assert.equal(runtimeDirectories.length, 1);
323 assert.equal(helperWrites, 2);
324
325 yield* fs.remove(first);
326 const held = {
327 arrived: yield* Deferred.make<void>(),
328 release: yield* Deferred.make<void>(),
329 };
330 gate = held;
331 const cancelled = yield* Effect.forkChild(askpassPath);
332 yield* Deferred.await(held.arrived);
333 const callsBeforeCancellation = fileCalls;
334 const interruption = yield* Fiber.interrupt(cancelled).pipe(
335 Effect.forkChild({ startImmediately: true }),
336 );
337 const next = yield* askpassPath.pipe(Effect.forkChild({ startImmediately: true }));
338 const callsDuringCancellation = fileCalls;
339 yield* Deferred.succeed(held.release, undefined);
340 yield* Fiber.join(interruption);
341 assert.equal(yield* Fiber.join(next), first);
342 assert.equal(callsDuringCancellation, callsBeforeCancellation);
343 assert.equal(helperWrites, 3);
344 assert.include(yield* fs.readFileString(first), 'printf "%s\\n" "$T3_SSH_AUTH_SECRET"');
345 }).pipe(
346 Effect.provide(Layer.merge(NodeServices.layer, Layer.succeed(HostProcess.Platform, "linux"))),
347 ),
348 );
349});