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.effect("redacts credentials from stdout in non-zero command failures", () => {
191 const spawner = ChildProcessSpawner.make(() =>
192 Effect.succeed(makeFailedProcess({ stdout: '{"credential":"pairing-secret"}\n' })),
193 );
194 const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
195 const layerProcess = Layer.mergeAll(NodeServices.layer, layerSpawner);
196
197 return Effect.gen(function* () {
198 const result = yield* Effect.result(
199 runSshCommand(
200 {
201 alias: "devbox",
202 hostname: "devbox.example.com",
203 username: "julius",
204 port: 2222,
205 },
206 { remoteCommandArgs: ["sh", "-s"] },
207 ),
208 );
209
210 assert.isTrue(Result.isFailure(result));
211 if (Result.isFailure(result)) {
212 assert.instanceOf(result.failure, SshCommandError);
213 assert.equal(result.failure.message, '{"credential":"[redacted]"}');
214 assert.equal(result.failure.stdout, '{"credential":"[redacted]"}\n');
215 }
216 }).pipe(Effect.provide(layerProcess));
217 });
218
219 it.effect("fails commands that never finish", () => {
220 const spawner = ChildProcessSpawner.make(() => Effect.succeed(makeNeverFinishingProcess()));
221 const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
222 const layerProcess = Layer.mergeAll(NodeServices.layer, layerSpawner, TestClock.layer());
223
224 return Effect.gen(function* () {
225 const fiber = yield* Effect.forkChild(
226 Effect.result(
227 runSshCommand(
228 {
229 alias: "devbox",
230 hostname: "devbox.example.com",
231 username: "julius",
232 port: 2222,
233 },
234 { timeoutMs: 1 },
235 ),
236 ),
237 );
238 yield* Effect.yieldNow;
239 yield* TestClock.adjust(Duration.millis(1));
240
241 const result = yield* Fiber.join(fiber);
242
243 assert.isTrue(Result.isFailure(result));
244 if (Result.isFailure(result)) {
245 assert.include(result.failure.message, "SSH command timed out after 1ms.");
246 }
247 }).pipe(Effect.provide(layerProcess));
248 });
249});