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

command.test.ts

354 lines13.7 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as Layer from "effect/Layer";
8import * as Result from "effect/Result";
9import * as Schema from "effect/Schema";
10import * as Sink from "effect/Sink";
11import * as Stream from "effect/Stream";
12import * as TestClock from "effect/testing/TestClock";
13import { ChildProcess, ChildProcessSpawner } from "effect/process";
14​
15import { baseSshArgs, parseSshResolveOutput, remoteStateKey, runSshCommand } from "./command.ts";
16import { SshCommandError } from "./errors.ts";
17​
18const encoder = new TextEncoder();
19const isSshCommandError = Schema.is(SshCommandError);
20​
21const makeFailedProcess = (input: { readonly stdout: string; readonly stderr?: string }) => {
22 const stdoutStream = Stream.make(encoder.encode(input.stdout));
23 const stderrStream = input.stderr ? Stream.make(encoder.encode(input.stderr)) : Stream.empty;
24 return ChildProcessSpawner.makeHandle({
25 pid: ChildProcessSpawner.ProcessId(123),
26 stdout: stdoutStream,
27 stderr: stderrStream,
28 all: Stream.empty,
29 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
30 exitStatus: Effect.succeed({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(1) }),
31 isRunning: Effect.succeed(false),
32 kill: () => Effect.void,
33 stdin: Sink.drain,
34 getInputFd: () => Sink.drain,
35 getOutputFd: () => Stream.empty,
36 unref: Effect.succeed(Effect.void),
37 });
38};
39​
40describe("ssh command", () => {
41 it.effect("parses resolved ssh config output into a target", () =>
42 Effect.sync(() => {
43 assert.deepEqual(
44 parseSshResolveOutput(
45 "devbox",
46 ["hostname devbox.example.com", "user julius", "port 2222", ""].join("\n"),
47 ),
48 {
49 alias: "devbox",
50 hostname: "devbox.example.com",
51 username: "julius",
52 port: 2222,
53 },
54 );
55 }),
56 );
57​
58 it.effect("passes an option-shaped alias to ssh as the destination", () => {
59 const spawned: Array<ReadonlyArray<string>> = [];
60 const spawner = ChildProcessSpawner.make((command) => {
61 if (ChildProcess.isStandardCommand(command)) spawned.push(command.args.map(String));
62 return Effect.succeed(makeFailedProcess({ stdout: "", stderr: "bad hostname\n" }));
63 });
64 return runSshCommand(
65 { alias: "-oProxyCommand=false", hostname: "devbox", username: null, port: null },
66 { remoteCommandArgs: ["sh", "-s"] },
67 ).pipe(
68 Effect.flip,
69 Effect.map(() => {
70 assert.deepEqual(spawned[0]?.slice(-4), ["--", "-oProxyCommand=false", "sh", "-s"]);
71 }),
72 Effect.provide(
73 Layer.merge(
74 Layer.mergeAll(NodeServices.layer, NodeCrypto.layer),
75 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
76 ),
77 ),
78 );
79 });
80​
81 it.effect("overrides an alias's RemoteCommand and RequestTTY", () =>
82 Effect.sync(() => {
83 assert.deepEqual(
84 baseSshArgs(
85 { alias: "devbox", hostname: "devbox", username: null, port: 2222 },
86 { batchMode: "yes" },
87 ),
88 [
89 "-o",
90 "BatchMode=yes",
91 "-o",
92 "ConnectTimeout=10",
93 "-o",
94 "RemoteCommand=none",
95 "-o",
96 "RequestTTY=no",
97 "-p",
98 "2222",
99 ],
100 );
101 }),
102 );
103​
104 // Remote servers store state under this key, so it must not change across releases.
105 it.effect("derives a stable remote state key", () =>
106 Effect.gen(function* () {
107 assert.equal(
108 yield* remoteStateKey({
109 alias: "devbox",
110 hostname: "devbox.example.com",
111 username: "julius",
112 port: 2222,
113 }),
114 "711bc738002d72fd",
115 );
116 assert.equal(
117 yield* remoteStateKey({
118 alias: "fixture",
119 hostname: "fixture",
120 username: null,
121 port: null,
122 }),
123 "326264c4f08c8a0c",
124 );
125 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
126 );
127​
128 it.live.each([
129 { name: "default head", keepErrorOutputTail: undefined, exitCode: 1, stderr: "" },
130 {
131 name: "opt-in tail",
132 keepErrorOutputTail: true,
133 exitCode: 1,
134 stderr: "stderr failure ".repeat(400),
135 },
136 { name: "successful output", keepErrorOutputTail: true, exitCode: 0, stderr: "" },
137 ])("preserves process output: $name", ({ keepErrorOutputTail, exitCode, stderr }) =>
138 Effect.gen(function* () {
139 const prefix = `HEAD\n${"verbose-prefix ".repeat(400)}`;
140 const secret = "synthetic-secret".repeat(400);
141 const diagnostic = "\nPANIC: emulator SDK is broken\n";
142 const stdout = `${prefix}{"credential":"${secret}"}${diagnostic}`;
143 const nativeSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
144 // Replace only the SSH endpoint with a real, deterministic process.
145 const spawner = ChildProcessSpawner.make(() =>
146 nativeSpawner.spawn(
147 ChildProcess.make(process.execPath, [
148 "-e",
149 `process.stdout.write(${JSON.stringify(stdout)}); process.stderr.write(${JSON.stringify(stderr)}); process.exitCode = ${exitCode};`,
150 ]),
151 ),
152 );
153 const command = runSshCommand(
154 { alias: "synthetic-fixture", hostname: "synthetic-fixture", username: null, port: null },
155 keepErrorOutputTail === undefined ? {} : { keepErrorOutputTail },
156 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
157 if (exitCode === 0) {
158 assert.deepEqual(yield* command, { stdout, stderr });
159 return;
160 }
161 const failure = yield* Effect.flip(command);
162 assert.instanceOf(failure, SshCommandError);
163 assert.equal(failure.exitCode, 1);
164 assert.equal(failure.stderr, stderr);
165 assert.equal(failure.message, stderr.trim() || failure.stdout?.trim());
166 const redacted = `${prefix}{"credential":"[redacted]"}${diagnostic}`;
167 assert.equal(
168 failure.stdout,
169 keepErrorOutputTail
170 ? `[truncated]\n${redacted.slice(-4_000)}`
171 : `${redacted.slice(0, 4_000)}\n[truncated]`,
172 );
173 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
174 );
175​
176 it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")(
177 "a timed-out command leaves no helper running that ignored SIGTERM",
178 () =>
179 Effect.gen(function* () {
180 const nativeSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
181 // Stands in for ssh and a ProxyCommand: ssh exits on SIGTERM, the proxy ignores it.
182 const spawner = ChildProcessSpawner.make((command) =>
183 nativeSpawner.spawn(
184 ChildProcess.make(
185 process.execPath,
186 [
187 "-e",
188 `const proxy = require("node:child_process").spawn("sh", ["-c", "trap '' TERM; exec sleep 60"], { stdio: "ignore" });
189 process.stdout.write(proxy.pid + "\\n");
190 setInterval(() => {}, 1000);`,
191 ],
192 command._tag === "StandardCommand" ? command.options : {},
193 ),
194 ),
195 );
196 const failure = yield* runSshCommand(
197 { alias: "synthetic-fixture", hostname: "synthetic-fixture", username: null, port: null },
198 { timeoutMs: 1_000, keepErrorOutputTail: true },
199 ).pipe(
200 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
201 Effect.flip,
202 );
203 assert.instanceOf(failure, SshCommandError);
204 assert.equal(failure.message, "SSH command timed out after 1000ms.");
205 const proxyPid = Number(failure.stdout?.trim());
206 assert.isTrue(Number.isSafeInteger(proxyPid) && proxyPid > 1);
207 const state = (yield* nativeSpawner.string(
208 ChildProcess.make("ps", ["-p", String(proxyPid), "-o", "stat="]),
209 )).trim();
210 if (state !== "" && !state.startsWith("Z")) process.kill(proxyPid, "SIGKILL");
211 assert.isTrue(state === "" || state.startsWith("Z"), `proxy still running (${state})`);
212 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
213 );
214​
215 it.live("enables server-alive checks for long remote commands", () =>
216 Effect.gen(function* () {
217 // Ask OpenSSH for its effective configuration without opening a connection.
218 const { stdout } = yield* runSshCommand(
219 { alias: "synthetic-fixture", hostname: "synthetic-fixture", username: null, port: null },
220 { preHostArgs: ["-F", "none", "-G"], timeoutMs: 900_000 },
221 );
222 assert.match(stdout, /^serveraliveinterval 15\r?$/mu);
223 assert.match(stdout, /^serveralivecountmax 3\r?$/mu);
224 }).pipe(Effect.provide(NodeServices.layer)),
225 );
226​
227 it.effect("redacts credentials from stdout in non-zero command failures", () => {
228 const spawner = ChildProcessSpawner.make(() =>
229 Effect.succeed(makeFailedProcess({ stdout: '{"credential":"pairing-secret"}\n' })),
230 );
231 const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
232 const layerProcess = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerSpawner);
233​
234 return Effect.gen(function* () {
235 const result = yield* Effect.result(
236 runSshCommand(
237 {
238 alias: "devbox",
239 hostname: "devbox.example.com",
240 username: "julius",
241 port: 2222,
242 },
243 { remoteCommandArgs: ["sh", "-s"] },
244 ),
245 );
246​
247 assert.isTrue(Result.isFailure(result));
248 if (Result.isFailure(result)) {
249 assert.instanceOf(result.failure, SshCommandError);
250 assert.equal(result.failure.message, '{"credential":"[redacted]"}');
251 assert.equal(result.failure.stdout, '{"credential":"[redacted]"}\n');
252 }
253 }).pipe(Effect.provide(layerProcess));
254 });
255​
256 it.effect("keeps redacted output the command emitted before timing out", () => {
257 const spawner = ChildProcessSpawner.make(() =>
258 Effect.succeed(
259 ChildProcessSpawner.makeHandle({
260 pid: ChildProcessSpawner.ProcessId(123),
261 stdout: Stream.concat(
262 Stream.make(encoder.encode('PROGRESS: extracting\n{"credential":"pairing-secret"}\n')),
263 Stream.never,
264 ),
265 stderr: Stream.concat(
266 Stream.make(encoder.encode("REMOTE: waiting for archive extraction\n")),
267 Stream.never,
268 ),
269 all: Stream.empty,
270 exitCode: Effect.never,
271 exitStatus: Effect.never,
272 isRunning: Effect.succeed(true),
273 kill: () => Effect.void,
274 stdin: Sink.drain,
275 getInputFd: () => Sink.drain,
276 getOutputFd: () => Stream.empty,
277 unref: Effect.succeed(Effect.void),
278 }),
279 ),
280 );
281 const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
282​
283 return Effect.gen(function* () {
284 const fiber = yield* runSshCommand(
285 { alias: "devbox", hostname: "devbox", username: null, port: null },
286 { remoteCommandArgs: ["sh", "-s"], timeoutMs: 1_000, keepErrorOutputTail: true },
287 ).pipe(Effect.flip, Effect.forkChild);
288 yield* TestClock.adjust("1 second");
289 const failure = yield* Fiber.join(fiber);
290​
291 assert.instanceOf(failure, SshCommandError);
292 assert.equal(failure.exitCode, null);
293 assert.equal(failure.stdout, 'PROGRESS: extracting\n{"credential":"[redacted]"}\n');
294 assert.equal(failure.stderr, "REMOTE: waiting for archive extraction\n");
295 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerSpawner)));
296 });
297​
298 const changedKeyStderr =
299 "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\r\n" +
300 "@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @\r\n" +
301 " ssh-keygen -f '/home/me/.ssh/known_hosts' -R 'devbox'\r\n" +
302 "Host key verification failed.\r\n";
303​
304 it.effect.each([
305 {
306 name: "quotes the terminal command for a POSIX shell",
307 target: { alias: "my host", username: "o'brien" },
308 platform: "linux",
309 stderr: "Host key verification failed.\r\n",
310 expected: ["`ssh 'o'\\''brien@my host'`"],
311 },
312 {
313 name: "quotes the terminal command for a Windows shell",
314 target: { alias: "my host", username: "me" },
315 platform: "win32",
316 stderr: "Host key verification failed.\r\n",
317 expected: ['`ssh "me@my host"`'],
318 },
319 {
320 name: "keeps an option-shaped alias out of the option list",
321 target: { alias: "-oProxyCommand=false", username: null },
322 platform: "linux",
323 stderr: "Host key verification failed.\r\n",
324 expected: ["`ssh -- -oProxyCommand=false`"],
325 },
326 {
327 name: "tells the user to remove a changed host key first",
328 target: { alias: "devbox", username: null },
329 platform: "linux",
330 stderr: changedKeyStderr,
331 expected: ["has changed", "`ssh-keygen -R`", "`ssh devbox`", "-R 'devbox'"],
332 },
333 ] as const)("$name", ({ target, platform, stderr, expected }) => {
334 const spawner = ChildProcessSpawner.make(() =>
335 Effect.succeed(makeFailedProcess({ stdout: "", stderr })),
336 );
337 return runSshCommand({ ...target, hostname: "devbox", port: null }).pipe(
338 Effect.flip,
339 Effect.map((error) => {
340 assert.isTrue(isSshCommandError(error));
341 for (const text of expected) assert.include(error.message, text);
342 if (isSshCommandError(error)) assert.equal(error.stderr, stderr);
343 }),
344 Effect.provideService(HostProcess.Platform, platform),
345 Effect.provide(
346 Layer.mergeAll(
347 NodeServices.layer,
348 NodeCrypto.layer,
349 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
350 ),
351 ),
352 );
353 });
354});