Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises the Node HTTP boundary.
2import * as NodeHttp from "node:http";
3
4import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import * as NetService from "@t3tools/shared/Net";
7import * as RelayClient from "@t3tools/shared/relayClient";
8import { assert, it } from "@effect/vitest";
9import * as ConfigProvider from "effect/ConfigProvider";
10import * as Console from "effect/Console";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as TestConsole from "effect/testing/TestConsole";
16import { Command } from "effect/cli";
17
18import { makeCli } from "../binCli.ts";
19import { CLOUD_CLI_DESIRED_LINK_SECRET } from "../cloud/CliState.ts";
20import {
21 makePersistedServerRuntimeState,
22 persistServerRuntimeState,
23} from "../serverRuntimeState.ts";
24import { acquireRelayClientForLink } from "./connect.ts";
25
26const managedExecutable = {
27 status: "available",
28 executablePath: "/tmp/cloudflared",
29 source: "managed",
30 version: RelayClient.CLOUDFLARED_VERSION,
31} as const;
32
33it.effect("does not install the relay client when the user declines the managed download", () =>
34 Effect.gen(function* () {
35 let installCalls = 0;
36 const result = yield* acquireRelayClientForLink(
37 {
38 resolve: Effect.succeed({
39 status: "missing",
40 version: RelayClient.CLOUDFLARED_VERSION,
41 }),
42 install: Effect.sync(() => {
43 installCalls += 1;
44 return managedExecutable;
45 }),
46 installWithProgress: () =>
47 Effect.sync(() => {
48 installCalls += 1;
49 return managedExecutable;
50 }),
51 pruneManagedVersions: Effect.void,
52 },
53 () => Effect.succeed(false),
54 () => Effect.void,
55 );
56
57 assert.isTrue(Option.isNone(result));
58 assert.equal(installCalls, 0);
59 }),
60);
61
62it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))(
63 "t3 connect unlink and status",
64 (it) => {
65 const runConnect = (
66 recordedPid: number,
67 options?: {
68 readonly portFreed?: boolean;
69 readonly command?: "unlink" | "status";
70 readonly linkMode?: "managed" | "publish_only";
71 },
72 ) =>
73 Effect.gen(function* () {
74 const requests: Array<string> = [];
75 const warnings: Array<string> = [];
76 const server = yield* Effect.acquireRelease(
77 Effect.callback<NodeHttp.Server>((resume) => {
78 const listening = NodeHttp.createServer((request, response) => {
79 requests.push(`${request.method} ${request.url}`);
80 response.writeHead(200, { "content-type": "application/json" });
81 response.end(JSON.stringify({ ok: true, endpointRuntimeStatus: null }));
82 });
83 listening.listen(0, "127.0.0.1", () => resume(Effect.succeed(listening)));
84 }),
85 (listening) => Effect.sync(() => listening.close()),
86 );
87 const address = server.address();
88 if (address === null || typeof address === "string") {
89 return yield* Effect.die(new Error("Expected a TCP address"));
90 }
91 if (options?.portFreed) {
92 yield* Effect.callback<void>((resume) => {
93 server.close(() => resume(Effect.void));
94 });
95 }
96
97 const fs = yield* FileSystem.FileSystem;
98 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-connect-unlink-test-" });
99 const state = yield* makePersistedServerRuntimeState({
100 config: { host: "127.0.0.1", devUrl: undefined },
101 port: address.port,
102 });
103 yield* persistServerRuntimeState({
104 path: `${baseDir}/userdata/server-runtime.json`,
105 state: { ...state, pid: recordedPid },
106 });
107 if (options?.command === "status") {
108 // Status asks the server for reachability only for a managed link.
109 yield* fs.makeDirectory(`${baseDir}/userdata/secrets`, { recursive: true });
110 yield* fs.writeFileString(
111 `${baseDir}/userdata/secrets/${CLOUD_CLI_DESIRED_LINK_SECRET}.bin`,
112 options.linkMode ?? "managed",
113 );
114 }
115
116 yield* Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([
117 "connect",
118 options?.command ?? "unlink",
119 "--base-dir",
120 baseDir,
121 ]).pipe(
122 // TestConsole has no reader for Console.warn.
123 Effect.updateService(Console.Console, (console) => ({
124 ...console,
125 warn: (...args: ReadonlyArray<unknown>) => {
126 warnings.push(args.join(" "));
127 },
128 })),
129 );
130
131 return { requests, warnings, printed: (yield* TestConsole.logLines).join("\n") };
132 }).pipe(
133 Effect.scoped,
134 Effect.provide(
135 Layer.mergeAll(
136 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
137 Layer.fresh(TestConsole.layer),
138 ),
139 ),
140 );
141
142 // Above Linux's PID ceiling, as in pair.test.ts: no process can hold it.
143 const deadPid = 4_194_305;
144
145 it.effect("does not tell the user to restart a server that is gone", () =>
146 Effect.gen(function* () {
147 const { printed, warnings } = yield* runConnect(deadPid, { portFreed: true });
148
149 assert.include(printed, "T3 Connect is disabled locally.");
150 assert.notInclude(warnings.join("\n"), "Restart that server");
151 }),
152 );
153
154 it.effect("warns that a server that is gone may have left its connector running", () =>
155 Effect.gen(function* () {
156 const { warnings } = yield* runConnect(deadPid, { portFreed: true });
157
158 assert.include(warnings.join("\n"), "its cloudflared process may still be running");
159 }),
160 );
161
162 it.effect("does not send a token to whatever took over a dead server's port", () =>
163 Effect.gen(function* () {
164 const { requests } = yield* runConnect(deadPid);
165
166 assert.deepEqual(requests, []);
167 }),
168 );
169
170 it.effect("status does not send a token to whatever took over a dead server's port", () =>
171 Effect.gen(function* () {
172 const { requests } = yield* runConnect(deadPid, { command: "status" });
173
174 assert.deepEqual(requests, []);
175 }),
176 );
177
178 it.effect("status asks a running server to check reachability", () =>
179 Effect.gen(function* () {
180 const { requests } = yield* runConnect(process.pid, { command: "status" });
181
182 assert.deepEqual(requests, ["POST /api/connect/reachability"]);
183 }),
184 );
185
186 it.effect("status does not report a publish-only link as exposed", () =>
187 Effect.gen(function* () {
188 const { printed } = yield* runConnect(process.pid, {
189 command: "status",
190 linkMode: "publish_only",
191 });
192
193 assert.include(printed, "Exposure: publish-only");
194 assert.notInclude(printed, "Other devices can reach this machine");
195 }),
196 );
197
198 it.effect("asks a running server to stop its tunnel", () =>
199 Effect.gen(function* () {
200 const { requests, printed, warnings } = yield* runConnect(process.pid);
201
202 assert.deepEqual(requests, ["POST /api/connect/unlink"]);
203 assert.include(printed, "T3 Connect is disabled locally.");
204 assert.notInclude(warnings.join("\n"), "cloudflared process");
205 }),
206 );
207 },
208);