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