Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

auth.test.ts

348 lines13.8 KB

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 isRunning: Effect.succeed(false),
144 kill: () => Effect.void,
145 stdin: Sink.drain,
146 getInputFd: () => Sink.drain,
147 getOutputFd: () => Stream.empty,
148 unref: Effect.succeed(Effect.void),
149 });
150 }),
151 );
152 const env = yield* buildSshChildEnvironment({
153 authSecret: "super-secret",
154 interactiveAuth: true,
155 askpassDirectory: dir,
156 baseEnv: {},
157 }).pipe(
158 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
159 Effect.provideService(HostProcess.IsExecutable, testCase.isExecutable),
160 Effect.provideService(
161 HostProcess.ExecutablePath,
162 testCase.execPath ?? "C:\\fake\\node.exe",
163 ),
164 );
165​
166 assert.deepEqual(spawned, [["ssh.exe", "-V"]]);
167 assert.equal(env.SSH_ASKPASS, testCase.askpass);
168 assert.equal(env.NODE_OPTIONS, testCase.nodeOptions);
169 assert.equal(env.ELECTRON_RUN_AS_NODE, testCase.runAsNode);
170 assert.equal(env.SSH_ASKPASS_REQUIRE, "force");
171 assert.equal(env.T3_SSH_AUTH_SECRET, "super-secret");
172 }
173​
174 assert.equal(yield* fs.exists(`${dir}\\ssh-askpass.cmd`), false);
175 assert.notInclude(yield* fs.readFileString(`${dir}\\ssh-askpass.cjs`), "process.argv");
176 assert.include(
177 yield* fs.readFileString(`${dir}\\ssh-askpass.sh`),
178 'printf "%s\\n" "$T3_SSH_AUTH_SECRET"',
179 );
180 }).pipe(
181 Effect.provide(Layer.merge(NodeServices.layer, Layer.succeed(HostProcess.Platform, "win32"))),
182 ),
183 );
184​
185 it.effect("reuses the default askpass directory across interactive commands", () =>
186 Effect.gen(function* () {
187 const fs = yield* FileSystem.FileSystem;
188 const path = yield* Path.Path;
189 const askpassPath = () =>
190 buildSshChildEnvironment({ interactiveAuth: true, authSecret: "pw" }).pipe(
191 Effect.map((env) => env.SSH_ASKPASS ?? ""),
192 );
193 const runtimeDirectoryOf = (askpass: string) => path.dirname(path.dirname(askpass));
194​
195 const first = yield* askpassPath();
196 assert.equal(yield* askpassPath(), first);
197​
198 yield* fs.remove(runtimeDirectoryOf(first), { recursive: true });
199 const recreated = yield* askpassPath();
200 assert.notEqual(recreated, first);
201 assert.equal(yield* fs.exists(recreated), true);
202​
203 const cachedOwner = yield* fs.stat(runtimeDirectoryOf(recreated));
204 const otherUser = yield* askpassPath().pipe(
205 Effect.provideService(
206 HostProcess.UserId,
207 (Option.getOrUndefined(cachedOwner.uid) ?? 0) + 1,
208 ),
209 );
210 assert.notEqual(otherUser, recreated);
211​
212 yield* fs.remove(runtimeDirectoryOf(recreated), { recursive: true });
213 yield* fs.remove(runtimeDirectoryOf(otherUser), { recursive: true });
214 }).pipe(
215 Effect.provide(Layer.merge(NodeServices.layer, Layer.succeed(HostProcess.Platform, "linux"))),
216 ),
217 );
218​
219 it.effect.skipIf(!symlinksSupported)(
220 "does not reuse a symlink left at the default askpass directory path",
221 () =>
222 Effect.gen(function* () {
223 const fs = yield* FileSystem.FileSystem;
224 const path = yield* Path.Path;
225 const askpassPath = () =>
226 buildSshChildEnvironment({ interactiveAuth: true, authSecret: "pw" }).pipe(
227 Effect.map((env) => env.SSH_ASKPASS ?? ""),
228 );
229 const runtimeDirectoryOf = (askpass: string) => path.dirname(path.dirname(askpass));
230​
231 const first = yield* askpassPath();
232 const ownedTarget = yield* fs.makeTempDirectory({ prefix: "t3code-ssh-symlink-target-" });
233 yield* fs.remove(runtimeDirectoryOf(first), { recursive: true });
234 yield* fs.symlink(ownedTarget, runtimeDirectoryOf(first));
235​
236 const next = yield* askpassPath();
237 assert.notEqual(next, first);
238 assert.equal(yield* fs.exists(path.join(ownedTarget, "t3code-ssh-askpass")), false);
239​
240 yield* fs.remove(runtimeDirectoryOf(first));
241 yield* fs.remove(ownedTarget, { recursive: true });
242 yield* fs.remove(runtimeDirectoryOf(next), { recursive: true });
243 }).pipe(
244 Effect.provide(
245 Layer.merge(NodeServices.layer, Layer.succeed(HostProcess.Platform, "linux")),
246 ),
247 ),
248 );
249​
250 it.effect("writes the default askpass helper once when interactive commands overlap", () =>
251 Effect.gen(function* () {
252 const fs = yield* FileSystem.FileSystem;
253 const runtimeDirectories: Array<string> = [];
254 yield* Effect.addFinalizer(() =>
255 Effect.forEach(runtimeDirectories, (directory) =>
256 fs.remove(directory, { recursive: true }).pipe(Effect.ignore),
257 ),
258 );
259​
260 // The first helper write of each round waits for the test, so the second command starts
261 // while the first is still setting up and must not touch the shared files until it is done.
262 let gate: { arrived: Deferred.Deferred<void>; release: Deferred.Deferred<void> } | undefined;
263 let fileCalls = 0;
264 let helperWrites = 0;
265 const counted = <A, E>(effect: Effect.Effect<A, E>) =>
266 Effect.suspend(() => {
267 fileCalls += 1;
268 return effect;
269 });
270 const trackedFs: FileSystem.FileSystem = {
271 ...fs,
272 makeTempDirectory: (options) =>
273 counted(fs.makeTempDirectory(options)).pipe(
274 Effect.tap((directory) => Effect.sync(() => runtimeDirectories.push(directory))),
275 ),
276 stat: (path) => counted(fs.stat(path)),
277 exists: (path) => counted(fs.exists(path)),
278 writeFileString: (path, data, options) =>
279 counted(
280 Effect.gen(function* () {
281 helperWrites += 1;
282 const held = gate;
283 gate = undefined;
284 if (held) {
285 yield* Deferred.succeed(held.arrived, undefined);
286 yield* Deferred.await(held.release);
287 }
288 yield* fs.writeFileString(path, data, options);
289 }),
290 ),
291 };
292 const askpassPath = buildSshChildEnvironment({
293 interactiveAuth: true,
294 authSecret: "pw",
295 }).pipe(
296 Effect.map((env) => env.SSH_ASKPASS ?? ""),
297 Effect.provideService(FileSystem.FileSystem, trackedFs),
298 );
299 const twoOverlappingCommands = Effect.gen(function* () {
300 const held = {
301 arrived: yield* Deferred.make<void>(),
302 release: yield* Deferred.make<void>(),
303 };
304 gate = held;
305 const first = yield* Effect.forkChild(askpassPath);
306 yield* Deferred.await(held.arrived);
307 const callsBefore = fileCalls;
308 const second = yield* askpassPath.pipe(Effect.forkChild({ startImmediately: true }));
309 assert.equal(fileCalls, callsBefore, "second command touched the files mid-setup");
310 yield* Deferred.succeed(held.release, undefined);
311 return [yield* Fiber.join(first), yield* Fiber.join(second)] as const;
312 });
313​
314 const [first, second] = yield* twoOverlappingCommands;
315 assert.equal(second, first);
316 assert.equal(runtimeDirectories.length, 1);
317 assert.equal(helperWrites, 1);
318​
319 yield* fs.remove(first);
320 assert.deepStrictEqual(yield* twoOverlappingCommands, [first, first]);
321 assert.equal(runtimeDirectories.length, 1);
322 assert.equal(helperWrites, 2);
323​
324 yield* fs.remove(first);
325 const held = {
326 arrived: yield* Deferred.make<void>(),
327 release: yield* Deferred.make<void>(),
328 };
329 gate = held;
330 const cancelled = yield* Effect.forkChild(askpassPath);
331 yield* Deferred.await(held.arrived);
332 const callsBeforeCancellation = fileCalls;
333 const interruption = yield* Fiber.interrupt(cancelled).pipe(
334 Effect.forkChild({ startImmediately: true }),
335 );
336 const next = yield* askpassPath.pipe(Effect.forkChild({ startImmediately: true }));
337 const callsDuringCancellation = fileCalls;
338 yield* Deferred.succeed(held.release, undefined);
339 yield* Fiber.join(interruption);
340 assert.equal(yield* Fiber.join(next), first);
341 assert.equal(callsDuringCancellation, callsBeforeCancellation);
342 assert.equal(helperWrites, 3);
343 assert.include(yield* fs.readFileString(first), 'printf "%s\\n" "$T3_SSH_AUTH_SECRET"');
344 }).pipe(
345 Effect.provide(Layer.merge(NodeServices.layer, Layer.succeed(HostProcess.Platform, "linux"))),
346 ),
347 );
348});