Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as Layer from "effect/Layer";
7import * as Result from "effect/Result";
8import * as Sink from "effect/Sink";
9import * as Stream from "effect/Stream";
10import * as TestClock from "effect/testing/TestClock";
11import { ChildProcess, ChildProcessSpawner } from "effect/process";
12
13import {
14 baseSshArgs,
15 getLastNonEmptyOutputLine,
16 parseSshResolveOutput,
17 remoteStateKey,
18 runSshCommand,
19} from "./command.ts";
20import { SshCommandError } from "./errors.ts";
21
22const encoder = new TextEncoder();
23
24const makeFailedProcess = (input: { readonly stdout: string; readonly stderr?: string }) => {
25 const stdoutStream = Stream.make(encoder.encode(input.stdout));
26 const stderrStream = input.stderr ? Stream.make(encoder.encode(input.stderr)) : Stream.empty;
27 return ChildProcessSpawner.makeHandle({
28 pid: ChildProcessSpawner.ProcessId(123),
29 stdout: stdoutStream,
30 stderr: stderrStream,
31 all: Stream.empty,
32 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
33 isRunning: Effect.succeed(false),
34 kill: () => Effect.void,
35 stdin: Sink.drain,
36 getInputFd: () => Sink.drain,
37 getOutputFd: () => Stream.empty,
38 unref: Effect.succeed(Effect.void),
39 });
40};
41
42const makeNeverFinishingProcess = () => {
43 let finish: ((exitCode: ChildProcessSpawner.ExitCode) => void) | null = null;
44 return ChildProcessSpawner.makeHandle({
45 pid: ChildProcessSpawner.ProcessId(123),
46 stdout: Stream.empty,
47 stderr: Stream.empty,
48 all: Stream.empty,
49 exitCode: Effect.callback<ChildProcessSpawner.ExitCode>((resume) => {
50 finish = (exitCode) => resume(Effect.succeed(exitCode));
51 return Effect.sync(() => {
52 finish = null;
53 });
54 }),
55 isRunning: Effect.succeed(true),
56 kill: () =>
57 Effect.sync(() => {
58 finish?.(ChildProcessSpawner.ExitCode(143));
59 }),
60 stdin: Sink.drain,
61 getInputFd: () => Sink.drain,
62 getOutputFd: () => Stream.empty,
63 unref: Effect.succeed(Effect.void),
64 });
65};
66
67describe("ssh command", () => {
68 it.effect("parses resolved ssh config output into a target", () =>
69 Effect.sync(() => {
70 assert.deepEqual(
71 parseSshResolveOutput(
72 "devbox",
73 ["hostname devbox.example.com", "user julius", "port 2222", ""].join("\n"),
74 ),
75 {
76 alias: "devbox",
77 hostname: "devbox.example.com",
78 username: "julius",
79 port: 2222,
80 },
81 );
82 }),
83 );
84
85 it.effect("builds interactive ssh args without forcing batch mode", () =>
86 Effect.sync(() => {
87 assert.deepEqual(
88 baseSshArgs(
89 {
90 alias: "devbox",
91 hostname: "devbox.example.com",
92 username: "julius",
93 port: 2222,
94 },
95 { batchMode: "no" },
96 ),
97 ["-o", "BatchMode=no", "-o", "ConnectTimeout=10", "-p", "2222"],
98 );
99 }),
100 );
101
102 it.effect("passes an option-shaped alias to ssh as the destination", () => {
103 const spawned: Array<ReadonlyArray<string>> = [];
104 const spawner = ChildProcessSpawner.make((command) => {
105 if (ChildProcess.isStandardCommand(command)) spawned.push(command.args);
106 return Effect.succeed(makeFailedProcess({ stdout: "", stderr: "bad hostname\n" }));
107 });
108 return runSshCommand(
109 { alias: "-oProxyCommand=false", hostname: "devbox", username: null, port: null },
110 { remoteCommandArgs: ["sh", "-s"] },
111 ).pipe(
112 Effect.flip,
113 Effect.map(() => {
114 assert.deepEqual(spawned[0]?.slice(-4), ["--", "-oProxyCommand=false", "sh", "-s"]);
115 }),
116 Effect.provide(
117 Layer.merge(
118 NodeServices.layer,
119 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
120 ),
121 ),
122 );
123 });
124
125 // Remote servers store state under this key, so it must not change across releases.
126 it.effect("derives a stable remote state key", () =>
127 Effect.gen(function* () {
128 assert.equal(
129 yield* remoteStateKey({
130 alias: "devbox",
131 hostname: "devbox.example.com",
132 username: "julius",
133 port: 2222,
134 }),
135 "711bc738002d72fd",
136 );
137 assert.equal(
138 yield* remoteStateKey({
139 alias: "fixture",
140 hostname: "fixture",
141 username: null,
142 port: null,
143 }),
144 "326264c4f08c8a0c",
145 );
146 }).pipe(Effect.provide(NodeServices.layer)),
147 );
148
149 it.effect("reads the last non-empty ssh output line", () =>
150 Effect.sync(() => {
151 assert.equal(
152 getLastNonEmptyOutputLine(
153 ["Welcome to the host", "", '{"credential":"pairing-token"}', ""].join("\n"),
154 ),
155 '{"credential":"pairing-token"}',
156 );
157 }),
158 );
159
160 it.effect("includes stdout in non-zero command failures when stderr is empty", () => {
161 const spawner = ChildProcessSpawner.make(() =>
162 Effect.succeed(makeFailedProcess({ stdout: "Pairing token creation failed\n" })),
163 );
164 const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
165 const layerProcess = Layer.mergeAll(NodeServices.layer, layerSpawner);
166
167 return Effect.gen(function* () {
168 const result = yield* Effect.result(
169 runSshCommand(
170 {
171 alias: "devbox",
172 hostname: "devbox.example.com",
173 username: "julius",
174 port: 2222,
175 },
176 { remoteCommandArgs: ["sh", "-s"] },
177 ),
178 );
179
180 assert.isTrue(Result.isFailure(result));
181 if (Result.isFailure(result)) {
182 assert.instanceOf(result.failure, SshCommandError);
183 assert.equal(result.failure.message, "Pairing token creation failed");
184 assert.equal(result.failure.stdout, "Pairing token creation failed\n");
185 assert.equal(result.failure.stderr, "");
186 }
187 }).pipe(Effect.provide(layerProcess));
188 });
189
190 it.live.each([
191 { name: "default head", keepErrorOutputTail: undefined, exitCode: 1, stderr: "" },
192 {
193 name: "opt-in tail",
194 keepErrorOutputTail: true,
195 exitCode: 1,
196 stderr: "stderr failure ".repeat(400),
197 },
198 { name: "successful output", keepErrorOutputTail: true, exitCode: 0, stderr: "" },
199 ])("preserves process output: $name", ({ keepErrorOutputTail, exitCode, stderr }) =>
200 Effect.gen(function* () {
201 const prefix = `HEAD\n${"verbose-prefix ".repeat(400)}`;
202 const secret = "synthetic-secret".repeat(400);
203 const diagnostic = "\nPANIC: emulator SDK is broken\n";
204 const stdout = `${prefix}{"credential":"${secret}"}${diagnostic}`;
205 const nativeSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
206 // Replace only the SSH endpoint with a real, deterministic process.
207 const spawner = ChildProcessSpawner.make(() =>
208 nativeSpawner.spawn(
209 ChildProcess.make(process.execPath, [
210 "-e",
211 `process.stdout.write(${JSON.stringify(stdout)}); process.stderr.write(${JSON.stringify(stderr)}); process.exitCode = ${exitCode};`,
212 ]),
213 ),
214 );
215 const command = runSshCommand(
216 { alias: "synthetic-fixture", hostname: "synthetic-fixture", username: null, port: null },
217 keepErrorOutputTail === undefined ? {} : { keepErrorOutputTail },
218 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
219 if (exitCode === 0) {
220 assert.deepEqual(yield* command, { stdout, stderr });
221 return;
222 }
223 const failure = yield* Effect.flip(command);
224 assert.instanceOf(failure, SshCommandError);
225 assert.equal(failure.exitCode, 1);
226 assert.equal(failure.stderr, stderr);
227 assert.equal(failure.message, stderr.trim() || failure.stdout?.trim());
228 const redacted = `${prefix}{"credential":"[redacted]"}${diagnostic}`;
229 assert.equal(
230 failure.stdout,
231 keepErrorOutputTail
232 ? `[truncated]\n${redacted.slice(-4_000)}`
233 : `${redacted.slice(0, 4_000)}\n[truncated]`,
234 );
235 }).pipe(Effect.provide(NodeServices.layer)),
236 );
237
238 it.effect("redacts credentials from stdout in non-zero command failures", () => {
239 const spawner = ChildProcessSpawner.make(() =>
240 Effect.succeed(makeFailedProcess({ stdout: '{"credential":"pairing-secret"}\n' })),
241 );
242 const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
243 const layerProcess = Layer.mergeAll(NodeServices.layer, layerSpawner);
244
245 return Effect.gen(function* () {
246 const result = yield* Effect.result(
247 runSshCommand(
248 {
249 alias: "devbox",
250 hostname: "devbox.example.com",
251 username: "julius",
252 port: 2222,
253 },
254 { remoteCommandArgs: ["sh", "-s"] },
255 ),
256 );
257
258 assert.isTrue(Result.isFailure(result));
259 if (Result.isFailure(result)) {
260 assert.instanceOf(result.failure, SshCommandError);
261 assert.equal(result.failure.message, '{"credential":"[redacted]"}');
262 assert.equal(result.failure.stdout, '{"credential":"[redacted]"}\n');
263 }
264 }).pipe(Effect.provide(layerProcess));
265 });
266
267 it.effect("fails commands that never finish", () => {
268 const spawner = ChildProcessSpawner.make(() => Effect.succeed(makeNeverFinishingProcess()));
269 const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
270 const layerProcess = Layer.mergeAll(NodeServices.layer, layerSpawner, TestClock.layer());
271
272 return Effect.gen(function* () {
273 const fiber = yield* Effect.forkChild(
274 Effect.result(
275 runSshCommand(
276 {
277 alias: "devbox",
278 hostname: "devbox.example.com",
279 username: "julius",
280 port: 2222,
281 },
282 { timeoutMs: 1 },
283 ),
284 ),
285 );
286 yield* Effect.yieldNow;
287 yield* TestClock.adjust(Duration.millis(1));
288
289 const result = yield* Fiber.join(fiber);
290
291 assert.isTrue(Result.isFailure(result));
292 if (Result.isFailure(result)) {
293 assert.include(result.failure.message, "SSH command timed out after 1ms.");
294 }
295 }).pipe(Effect.provide(layerProcess));
296 });
297});