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

command.test.ts

174 lines6.3 KB

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