Open History to see the last commit
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 { 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 isRunning: Effect.succeed(false),
31 kill: () => Effect.void,
32 stdin: Sink.drain,
33 getInputFd: () => Sink.drain,
34 getOutputFd: () => Stream.empty,
35 unref: Effect.succeed(Effect.void),
36 });
37};
38
39describe("ssh command", () => {
40 it.effect("parses resolved ssh config output into a target", () =>
41 Effect.sync(() => {
42 assert.deepEqual(
43 parseSshResolveOutput(
44 "devbox",
45 ["hostname devbox.example.com", "user julius", "port 2222", ""].join("\n"),
46 ),
47 {
48 alias: "devbox",
49 hostname: "devbox.example.com",
50 username: "julius",
51 port: 2222,
52 },
53 );
54 }),
55 );
56
57 it.effect("passes an option-shaped alias to ssh as the destination", () => {
58 const spawned: Array<ReadonlyArray<string>> = [];
59 const spawner = ChildProcessSpawner.make((command) => {
60 if (ChildProcess.isStandardCommand(command)) spawned.push(command.args.map(String));
61 return Effect.succeed(makeFailedProcess({ stdout: "", stderr: "bad hostname\n" }));
62 });
63 return runSshCommand(
64 { alias: "-oProxyCommand=false", hostname: "devbox", username: null, port: null },
65 { remoteCommandArgs: ["sh", "-s"] },
66 ).pipe(
67 Effect.flip,
68 Effect.map(() => {
69 assert.deepEqual(spawned[0]?.slice(-4), ["--", "-oProxyCommand=false", "sh", "-s"]);
70 }),
71 Effect.provide(
72 Layer.merge(
73 Layer.mergeAll(NodeServices.layer, NodeCrypto.layer),
74 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
75 ),
76 ),
77 );
78 });
79
80 // Remote servers store state under this key, so it must not change across releases.
81 it.effect("derives a stable remote state key", () =>
82 Effect.gen(function* () {
83 assert.equal(
84 yield* remoteStateKey({
85 alias: "devbox",
86 hostname: "devbox.example.com",
87 username: "julius",
88 port: 2222,
89 }),
90 "711bc738002d72fd",
91 );
92 assert.equal(
93 yield* remoteStateKey({
94 alias: "fixture",
95 hostname: "fixture",
96 username: null,
97 port: null,
98 }),
99 "326264c4f08c8a0c",
100 );
101 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
102 );
103
104 it.live.each([
105 { name: "default head", keepErrorOutputTail: undefined, exitCode: 1, stderr: "" },
106 {
107 name: "opt-in tail",
108 keepErrorOutputTail: true,
109 exitCode: 1,
110 stderr: "stderr failure ".repeat(400),
111 },
112 { name: "successful output", keepErrorOutputTail: true, exitCode: 0, stderr: "" },
113 ])("preserves process output: $name", ({ keepErrorOutputTail, exitCode, stderr }) =>
114 Effect.gen(function* () {
115 const prefix = `HEAD\n${"verbose-prefix ".repeat(400)}`;
116 const secret = "synthetic-secret".repeat(400);
117 const diagnostic = "\nPANIC: emulator SDK is broken\n";
118 const stdout = `${prefix}{"credential":"${secret}"}${diagnostic}`;
119 const nativeSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
120 // Replace only the SSH endpoint with a real, deterministic process.
121 const spawner = ChildProcessSpawner.make(() =>
122 nativeSpawner.spawn(
123 ChildProcess.make(process.execPath, [
124 "-e",
125 `process.stdout.write(${JSON.stringify(stdout)}); process.stderr.write(${JSON.stringify(stderr)}); process.exitCode = ${exitCode};`,
126 ]),
127 ),
128 );
129 const command = runSshCommand(
130 { alias: "synthetic-fixture", hostname: "synthetic-fixture", username: null, port: null },
131 keepErrorOutputTail === undefined ? {} : { keepErrorOutputTail },
132 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
133 if (exitCode === 0) {
134 assert.deepEqual(yield* command, { stdout, stderr });
135 return;
136 }
137 const failure = yield* Effect.flip(command);
138 assert.instanceOf(failure, SshCommandError);
139 assert.equal(failure.exitCode, 1);
140 assert.equal(failure.stderr, stderr);
141 assert.equal(failure.message, stderr.trim() || failure.stdout?.trim());
142 const redacted = `${prefix}{"credential":"[redacted]"}${diagnostic}`;
143 assert.equal(
144 failure.stdout,
145 keepErrorOutputTail
146 ? `[truncated]\n${redacted.slice(-4_000)}`
147 : `${redacted.slice(0, 4_000)}\n[truncated]`,
148 );
149 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
150 );
151
152 it.live("enables server-alive checks for long remote commands", () =>
153 Effect.gen(function* () {
154 // Ask OpenSSH for its effective configuration without opening a connection.
155 const { stdout } = yield* runSshCommand(
156 { alias: "synthetic-fixture", hostname: "synthetic-fixture", username: null, port: null },
157 { preHostArgs: ["-F", "none", "-G"], timeoutMs: 900_000 },
158 );
159 assert.match(stdout, /^serveraliveinterval 15\r?$/mu);
160 assert.match(stdout, /^serveralivecountmax 3\r?$/mu);
161 }).pipe(Effect.provide(NodeServices.layer)),
162 );
163
164 it.effect("redacts credentials from stdout in non-zero command failures", () => {
165 const spawner = ChildProcessSpawner.make(() =>
166 Effect.succeed(makeFailedProcess({ stdout: '{"credential":"pairing-secret"}\n' })),
167 );
168 const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
169 const layerProcess = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerSpawner);
170
171 return Effect.gen(function* () {
172 const result = yield* Effect.result(
173 runSshCommand(
174 {
175 alias: "devbox",
176 hostname: "devbox.example.com",
177 username: "julius",
178 port: 2222,
179 },
180 { remoteCommandArgs: ["sh", "-s"] },
181 ),
182 );
183
184 assert.isTrue(Result.isFailure(result));
185 if (Result.isFailure(result)) {
186 assert.instanceOf(result.failure, SshCommandError);
187 assert.equal(result.failure.message, '{"credential":"[redacted]"}');
188 assert.equal(result.failure.stdout, '{"credential":"[redacted]"}\n');
189 }
190 }).pipe(Effect.provide(layerProcess));
191 });
192
193 it.effect("keeps redacted output the command emitted before timing out", () => {
194 const spawner = ChildProcessSpawner.make(() =>
195 Effect.succeed(
196 ChildProcessSpawner.makeHandle({
197 pid: ChildProcessSpawner.ProcessId(123),
198 stdout: Stream.concat(
199 Stream.make(encoder.encode('PROGRESS: extracting\n{"credential":"pairing-secret"}\n')),
200 Stream.never,
201 ),
202 stderr: Stream.concat(
203 Stream.make(encoder.encode("REMOTE: waiting for archive extraction\n")),
204 Stream.never,
205 ),
206 all: Stream.empty,
207 exitCode: Effect.never,
208 isRunning: Effect.succeed(true),
209 kill: () => Effect.void,
210 stdin: Sink.drain,
211 getInputFd: () => Sink.drain,
212 getOutputFd: () => Stream.empty,
213 unref: Effect.succeed(Effect.void),
214 }),
215 ),
216 );
217 const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
218
219 return Effect.gen(function* () {
220 const fiber = yield* runSshCommand(
221 { alias: "devbox", hostname: "devbox", username: null, port: null },
222 { remoteCommandArgs: ["sh", "-s"], timeoutMs: 1_000, keepErrorOutputTail: true },
223 ).pipe(Effect.flip, Effect.forkChild);
224 yield* TestClock.adjust("1 second");
225 const failure = yield* Fiber.join(fiber);
226
227 assert.instanceOf(failure, SshCommandError);
228 assert.equal(failure.exitCode, null);
229 assert.equal(failure.stdout, 'PROGRESS: extracting\n{"credential":"[redacted]"}\n');
230 assert.equal(failure.stderr, "REMOTE: waiting for archive extraction\n");
231 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerSpawner)));
232 });
233
234 const changedKeyStderr =
235 "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\r\n" +
236 "@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @\r\n" +
237 " ssh-keygen -f '/home/me/.ssh/known_hosts' -R 'devbox'\r\n" +
238 "Host key verification failed.\r\n";
239
240 it.effect.each([
241 {
242 name: "quotes the terminal command for a POSIX shell",
243 target: { alias: "my host", username: "o'brien" },
244 platform: "linux",
245 stderr: "Host key verification failed.\r\n",
246 expected: ["`ssh 'o'\\''brien@my host'`"],
247 },
248 {
249 name: "quotes the terminal command for a Windows shell",
250 target: { alias: "my host", username: "me" },
251 platform: "win32",
252 stderr: "Host key verification failed.\r\n",
253 expected: ['`ssh "me@my host"`'],
254 },
255 {
256 name: "keeps an option-shaped alias out of the option list",
257 target: { alias: "-oProxyCommand=false", username: null },
258 platform: "linux",
259 stderr: "Host key verification failed.\r\n",
260 expected: ["`ssh -- -oProxyCommand=false`"],
261 },
262 {
263 name: "tells the user to remove a changed host key first",
264 target: { alias: "devbox", username: null },
265 platform: "linux",
266 stderr: changedKeyStderr,
267 expected: ["has changed", "`ssh-keygen -R`", "`ssh devbox`", "-R 'devbox'"],
268 },
269 ] as const)("$name", ({ target, platform, stderr, expected }) => {
270 const spawner = ChildProcessSpawner.make(() =>
271 Effect.succeed(makeFailedProcess({ stdout: "", stderr })),
272 );
273 return runSshCommand({ ...target, hostname: "devbox", port: null }).pipe(
274 Effect.flip,
275 Effect.map((error) => {
276 assert.isTrue(isSshCommandError(error));
277 for (const text of expected) assert.include(error.message, text);
278 if (isSshCommandError(error)) assert.equal(error.stderr, stderr);
279 }),
280 Effect.provideService(HostProcess.Platform, platform),
281 Effect.provide(
282 Layer.mergeAll(
283 NodeServices.layer,
284 NodeCrypto.layer,
285 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
286 ),
287 ),
288 );
289 });
290});