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 Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Result from "effect/Result";
7import * as Sink from "effect/Sink";
8import * as Stream from "effect/Stream";
9import { ChildProcess, ChildProcessSpawner } from "effect/process";
10
11import { parseSshResolveOutput, remoteStateKey, runSshCommand } from "./command.ts";
12import { SshCommandError } from "./errors.ts";
13
14const encoder = new TextEncoder();
15
16const makeFailedProcess = (input: { readonly stdout: string; readonly stderr?: string }) => {
17 const stdoutStream = Stream.make(encoder.encode(input.stdout));
18 const stderrStream = input.stderr ? Stream.make(encoder.encode(input.stderr)) : Stream.empty;
19 return ChildProcessSpawner.makeHandle({
20 pid: ChildProcessSpawner.ProcessId(123),
21 stdout: stdoutStream,
22 stderr: stderrStream,
23 all: Stream.empty,
24 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
25 isRunning: Effect.succeed(false),
26 kill: () => Effect.void,
27 stdin: Sink.drain,
28 getInputFd: () => Sink.drain,
29 getOutputFd: () => Stream.empty,
30 unref: Effect.succeed(Effect.void),
31 });
32};
33
34describe("ssh command", () => {
35 it.effect("parses resolved ssh config output into a target", () =>
36 Effect.sync(() => {
37 assert.deepEqual(
38 parseSshResolveOutput(
39 "devbox",
40 ["hostname devbox.example.com", "user julius", "port 2222", ""].join("\n"),
41 ),
42 {
43 alias: "devbox",
44 hostname: "devbox.example.com",
45 username: "julius",
46 port: 2222,
47 },
48 );
49 }),
50 );
51
52 it.effect("passes an option-shaped alias to ssh as the destination", () => {
53 const spawned: Array<ReadonlyArray<string>> = [];
54 const spawner = ChildProcessSpawner.make((command) => {
55 if (ChildProcess.isStandardCommand(command)) spawned.push(command.args.map(String));
56 return Effect.succeed(makeFailedProcess({ stdout: "", stderr: "bad hostname\n" }));
57 });
58 return runSshCommand(
59 { alias: "-oProxyCommand=false", hostname: "devbox", username: null, port: null },
60 { remoteCommandArgs: ["sh", "-s"] },
61 ).pipe(
62 Effect.flip,
63 Effect.map(() => {
64 assert.deepEqual(spawned[0]?.slice(-4), ["--", "-oProxyCommand=false", "sh", "-s"]);
65 }),
66 Effect.provide(
67 Layer.merge(
68 Layer.mergeAll(NodeServices.layer, NodeCrypto.layer),
69 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
70 ),
71 ),
72 );
73 });
74
75 // Remote servers store state under this key, so it must not change across releases.
76 it.effect("derives a stable remote state key", () =>
77 Effect.gen(function* () {
78 assert.equal(
79 yield* remoteStateKey({
80 alias: "devbox",
81 hostname: "devbox.example.com",
82 username: "julius",
83 port: 2222,
84 }),
85 "711bc738002d72fd",
86 );
87 assert.equal(
88 yield* remoteStateKey({
89 alias: "fixture",
90 hostname: "fixture",
91 username: null,
92 port: null,
93 }),
94 "326264c4f08c8a0c",
95 );
96 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
97 );
98
99 it.live.each([
100 { name: "default head", keepErrorOutputTail: undefined, exitCode: 1, stderr: "" },
101 {
102 name: "opt-in tail",
103 keepErrorOutputTail: true,
104 exitCode: 1,
105 stderr: "stderr failure ".repeat(400),
106 },
107 { name: "successful output", keepErrorOutputTail: true, exitCode: 0, stderr: "" },
108 ])("preserves process output: $name", ({ keepErrorOutputTail, exitCode, stderr }) =>
109 Effect.gen(function* () {
110 const prefix = `HEAD\n${"verbose-prefix ".repeat(400)}`;
111 const secret = "synthetic-secret".repeat(400);
112 const diagnostic = "\nPANIC: emulator SDK is broken\n";
113 const stdout = `${prefix}{"credential":"${secret}"}${diagnostic}`;
114 const nativeSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
115 // Replace only the SSH endpoint with a real, deterministic process.
116 const spawner = ChildProcessSpawner.make(() =>
117 nativeSpawner.spawn(
118 ChildProcess.make(process.execPath, [
119 "-e",
120 `process.stdout.write(${JSON.stringify(stdout)}); process.stderr.write(${JSON.stringify(stderr)}); process.exitCode = ${exitCode};`,
121 ]),
122 ),
123 );
124 const command = runSshCommand(
125 { alias: "synthetic-fixture", hostname: "synthetic-fixture", username: null, port: null },
126 keepErrorOutputTail === undefined ? {} : { keepErrorOutputTail },
127 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
128 if (exitCode === 0) {
129 assert.deepEqual(yield* command, { stdout, stderr });
130 return;
131 }
132 const failure = yield* Effect.flip(command);
133 assert.instanceOf(failure, SshCommandError);
134 assert.equal(failure.exitCode, 1);
135 assert.equal(failure.stderr, stderr);
136 assert.equal(failure.message, stderr.trim() || failure.stdout?.trim());
137 const redacted = `${prefix}{"credential":"[redacted]"}${diagnostic}`;
138 assert.equal(
139 failure.stdout,
140 keepErrorOutputTail
141 ? `[truncated]\n${redacted.slice(-4_000)}`
142 : `${redacted.slice(0, 4_000)}\n[truncated]`,
143 );
144 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
145 );
146
147 it.live("enables server-alive checks for long remote commands", () =>
148 Effect.gen(function* () {
149 // Ask OpenSSH for its effective configuration without opening a connection.
150 const { stdout } = yield* runSshCommand(
151 { alias: "synthetic-fixture", hostname: "synthetic-fixture", username: null, port: null },
152 { preHostArgs: ["-F", "none", "-G"], timeoutMs: 900_000 },
153 );
154 assert.match(stdout, /^serveraliveinterval 15\r?$/mu);
155 assert.match(stdout, /^serveralivecountmax 3\r?$/mu);
156 }).pipe(Effect.provide(NodeServices.layer)),
157 );
158
159 it.effect("redacts credentials from stdout in non-zero command failures", () => {
160 const spawner = ChildProcessSpawner.make(() =>
161 Effect.succeed(makeFailedProcess({ stdout: '{"credential":"pairing-secret"}\n' })),
162 );
163 const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
164 const layerProcess = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerSpawner);
165
166 return Effect.gen(function* () {
167 const result = yield* Effect.result(
168 runSshCommand(
169 {
170 alias: "devbox",
171 hostname: "devbox.example.com",
172 username: "julius",
173 port: 2222,
174 },
175 { remoteCommandArgs: ["sh", "-s"] },
176 ),
177 );
178
179 assert.isTrue(Result.isFailure(result));
180 if (Result.isFailure(result)) {
181 assert.instanceOf(result.failure, SshCommandError);
182 assert.equal(result.failure.message, '{"credential":"[redacted]"}');
183 assert.equal(result.failure.stdout, '{"credential":"[redacted]"}\n');
184 }
185 }).pipe(Effect.provide(layerProcess));
186 });
187});