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

relayClient.test.ts

282 lines9.0 KB

1import { sha256 } from "@noble/hashes/sha2";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { describe, expect, it } from "@effect/vitest";
4import * as ConfigProvider from "effect/ConfigProvider";
5import * as Effect from "effect/Effect";
6import * as Encoding from "effect/Encoding";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Sink from "effect/Sink";
10import * as Stream from "effect/Stream";
11import { HttpClient, HttpClientResponse } from "effect/unstable/http";
12import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
13import { HostProcessArchitecture, HostProcessPlatform } from "./hostProcess.ts";
14​
15import {
16 RelayClientInstallError,
17 CLOUDFLARED_VERSION,
18 makeCloudflaredRelayClient,
19} from "./relayClient.ts";
20​
21// The suite runs the linux code path against the real filesystem, checking
22// POSIX exec bits that NTFS never reports; the win32 branch skips that check.
23const windowsHost = HostProcessPlatform.defaultValue() === "win32";
24​
25const hostRuntimeLayer = (env: Record<string, string> = {}) =>
26 Layer.mergeAll(
27 Layer.succeed(HostProcessPlatform, "linux"),
28 Layer.succeed(HostProcessArchitecture, "x64"),
29 ConfigProvider.layer(ConfigProvider.fromEnv({ env })),
30 );
31​
32function makeHandle(exitCode = 0) {
33 return ChildProcessSpawner.makeHandle({
34 pid: ChildProcessSpawner.ProcessId(100),
35 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
36 isRunning: Effect.succeed(false),
37 kill: () => Effect.void,
38 unref: Effect.succeed(Effect.void),
39 stdin: Sink.drain,
40 stdout: Stream.empty,
41 stderr: Stream.empty,
42 all: Stream.empty,
43 getInputFd: () => Sink.drain,
44 getOutputFd: () => Stream.empty,
45 });
47​
48const makeHttpClientLayer = (bytes: Uint8Array) =>
49 Layer.succeed(
50 HttpClient.HttpClient,
51 HttpClient.make((request) =>
52 Effect.succeed(
53 HttpClientResponse.fromWeb(request, new Response(bytes.buffer as ArrayBuffer)),
54 ),
55 ),
56 );
57​
58const makeSpawnerLayer = (commands: Array<string>) =>
59 Layer.succeed(
60 ChildProcessSpawner.ChildProcessSpawner,
61 ChildProcessSpawner.make((command) =>
62 Effect.sync(() => {
63 commands.push(ChildProcess.isStandardCommand(command) ? command.command : "piped-command");
64 return makeHandle();
65 }),
66 ),
67 );
68​
69describe("RelayClient", () => {
70 it.effect.skipIf(windowsHost)(
71 "resolves explicit overrides before managed and PATH executables",
72 () =>
73 Effect.gen(function* () {
74 const fileSystem = yield* FileSystem.FileSystem;
75 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
76 prefix: "t3-cloudflared-test-",
77 });
78 const overridePath = `${baseDir}/override-cloudflared`;
79 yield* fileSystem.writeFileString(overridePath, "override");
80 yield* fileSystem.chmod(overridePath, 0o755);
81 const manager = yield* makeCloudflaredRelayClient({
82 baseDir,
83 });
84​
85 expect(
86 yield* manager.resolve.pipe(
87 Effect.provideService(
88 ConfigProvider.ConfigProvider,
89 ConfigProvider.fromEnv({
90 env: { PATH: "", T3CODE_CLOUDFLARED_PATH: overridePath },
91 }),
92 ),
93 ),
94 ).toEqual({
95 status: "available",
96 executablePath: overridePath,
97 source: "override",
98 version: CLOUDFLARED_VERSION,
99 });
100 }).pipe(
101 Effect.scoped,
102 Effect.provide(
103 Layer.mergeAll(
104 NodeServices.layer,
105 makeHttpClientLayer(new Uint8Array()),
106 makeSpawnerLayer([]),
107 hostRuntimeLayer(),
108 ),
109 ),
110 ),
111 );
112​
113 it.effect.skipIf(windowsHost)(
114 "downloads, verifies, validates, and atomically installs the managed executable",
115 () =>
116 Effect.gen(function* () {
117 const fileSystem = yield* FileSystem.FileSystem;
118 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
119 prefix: "t3-cloudflared-test-",
120 });
121 const bytes = new TextEncoder().encode("test-cloudflared-binary");
122 const manager = yield* makeCloudflaredRelayClient({
123 baseDir,
124 releaseAsset: {
125 url: "https://example.test/cloudflared",
126 sha256: Encoding.encodeHex(sha256(bytes)),
127 archive: "binary",
128 },
129 });
130​
131 const progress: Array<string> = [];
132 const installed = yield* manager.installWithProgress((event) =>
133 Effect.sync(() => {
134 if (event.type === "progress") {
135 progress.push(event.stage);
136 }
137 }),
138 );
139 const managedPath = `${baseDir}/tools/cloudflared/${CLOUDFLARED_VERSION}/linux-x64/cloudflared`;
140 expect(installed).toEqual({
141 status: "available",
142 executablePath: managedPath,
143 source: "managed",
144 version: CLOUDFLARED_VERSION,
145 });
146 expect(new TextDecoder().decode(yield* fileSystem.readFile(managedPath))).toBe(
147 "test-cloudflared-binary",
148 );
149 expect(progress).toEqual([
150 "checking",
151 "waiting_for_lock",
152 "downloading",
153 "verifying",
154 "installing",
155 "validating",
156 "activating",
157 ]);
158 expect(yield* manager.resolve).toEqual(installed);
159 }).pipe(
160 Effect.scoped,
161 Effect.provide(
162 Layer.mergeAll(
163 NodeServices.layer,
164 makeHttpClientLayer(new TextEncoder().encode("test-cloudflared-binary")),
165 makeSpawnerLayer([]),
166 hostRuntimeLayer(),
167 ),
168 ),
169 ),
170 );
171​
172 it.effect("rejects downloads whose checksum does not match the pinned manifest", () =>
173 Effect.gen(function* () {
174 const fileSystem = yield* FileSystem.FileSystem;
175 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
176 prefix: "t3-cloudflared-test-",
177 });
178 const manager = yield* makeCloudflaredRelayClient({
179 baseDir,
180 releaseAsset: {
181 url: "https://example.test/cloudflared",
182 sha256: Encoding.encodeHex(sha256(new TextEncoder().encode("expected"))),
183 archive: "binary",
184 },
185 });
186​
187 const error = yield* manager.install.pipe(Effect.flip);
188 expect(error).toBeInstanceOf(RelayClientInstallError);
189 expect(error.reason).toBe("invalid_checksum");
190 }).pipe(
191 Effect.scoped,
192 Effect.provide(
193 Layer.mergeAll(
194 NodeServices.layer,
195 makeHttpClientLayer(new TextEncoder().encode("tampered")),
196 makeSpawnerLayer([]),
197 hostRuntimeLayer(),
198 ),
199 ),
200 ),
201 );
202​
203 it.effect.skipIf(windowsHost)("serializes concurrent installs within one runtime", () => {
204 const commands: Array<string> = [];
205 const bytes = new TextEncoder().encode("test-cloudflared-binary");
206 return Effect.gen(function* () {
207 const fileSystem = yield* FileSystem.FileSystem;
208 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
209 prefix: "t3-cloudflared-test-",
210 });
211 const manager = yield* makeCloudflaredRelayClient({
212 baseDir,
213 releaseAsset: {
214 url: "https://example.test/cloudflared",
215 sha256: Encoding.encodeHex(sha256(bytes)),
216 archive: "binary",
217 },
218 });
219​
220 const [first, second] = yield* Effect.all([manager.install, manager.install], {
221 concurrency: "unbounded",
222 });
223 expect(second).toEqual(first);
224 expect(commands).toHaveLength(1);
225 }).pipe(
226 Effect.scoped,
227 Effect.provide(
228 Layer.mergeAll(
229 NodeServices.layer,
230 makeHttpClientLayer(bytes),
231 makeSpawnerLayer(commands),
232 hostRuntimeLayer(),
233 ),
234 ),
235 );
236 });
237​
238 it.effect.skipIf(windowsHost)(
239 "observes PATH changes after the manager has been constructed",
240 () => {
241 const env = { PATH: "" };
242 return Effect.gen(function* () {
243 const fileSystem = yield* FileSystem.FileSystem;
244 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
245 prefix: "t3-cloudflared-test-",
246 });
247 const binDir = `${baseDir}/bin`;
248 const executablePath = `${binDir}/cloudflared`;
249 const manager = yield* makeCloudflaredRelayClient({
250 baseDir,
251 });
252​
253 expect(yield* manager.resolve).toEqual({
254 status: "missing",
255 version: CLOUDFLARED_VERSION,
256 });
257​
258 yield* fileSystem.makeDirectory(binDir);
259 yield* fileSystem.writeFileString(executablePath, "cloudflared");
260 yield* fileSystem.chmod(executablePath, 0o755);
261 env.PATH = binDir;
262​
263 expect(yield* manager.resolve).toEqual({
264 status: "available",
265 executablePath,
266 source: "path",
267 version: CLOUDFLARED_VERSION,
268 });
269 }).pipe(
270 Effect.scoped,
271 Effect.provide(
272 Layer.mergeAll(
273 NodeServices.layer,
274 makeHttpClientLayer(new Uint8Array()),
275 makeSpawnerLayer([]),
276 hostRuntimeLayer(env),
277 ),
278 ),
279 );
280 },
281 );
282});