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

command.test.ts

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