Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as Cause from "effect/Cause";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as Layer from "effect/Layer";
6import * as PlatformError from "effect/PlatformError";
7import * as Sink from "effect/Sink";
8import * as Stream from "effect/Stream";
9import * as TestClock from "effect/testing/TestClock";
10import { ChildProcessSpawner } from "effect/unstable/process";
11import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
12
13import {
14 buildTailscaleHttpsBaseUrl,
15 disableTailscaleServe,
16 ensureTailscaleServe,
17 isTailscaleIpv4Address,
18 parseTailscaleMagicDnsName,
19 parseTailscaleServeTarget,
20 parseTailscaleStatus,
21 readTailscaleServeTarget,
22 readTailscaleStatus,
23 TAILSCALE_STATUS_TIMEOUT,
24 TailscaleCommandExitError,
25 TailscaleCommandSpawnError,
26 TailscaleCommandTimeoutError,
27 TailscaleStatusParseError,
28} from "./tailscale.ts";
29
30const encoder = new TextEncoder();
31
32/**
33 * Asserts nothing reachable from `error` contains `secret`. Recurses through
34 * nested objects, arrays, and `cause` chains rather than checking only
35 * top-level strings: a leak one level down (say, a wrapped cause carrying raw
36 * stderr) is just as visible in a log, and a shallow check would pass it.
37 *
38 * Walks values instead of serializing so it holds for fields added later, and
39 * tracks visited objects so a cyclic cause chain terminates.
40 */
41function assertCarriesNoSecret(error: object, secret: string): void {
42 const seen = new WeakSet<object>();
43
44 const walk = (value: unknown, path: string): void => {
45 if (typeof value === "string") {
46 assert.notInclude(value, secret, `${path} leaked stderr`);
47 return;
48 }
49 if (typeof value !== "object" || value === null || seen.has(value)) {
50 return;
51 }
52 seen.add(value);
53
54 if (Array.isArray(value)) {
55 value.forEach((entry, index) => walk(entry, `${path}[${String(index)}]`));
56 return;
57 }
58 // `message` and `cause` are getters on Error subclasses, so they are not
59 // own enumerable properties and Object.entries alone would skip them.
60 walk((value as { message?: unknown }).message, `${path}.message`);
61 walk((value as { cause?: unknown }).cause, `${path}.cause`);
62 for (const [key, nested] of Object.entries(value)) {
63 walk(nested, `${path}.${key}`);
64 }
65 };
66
67 walk(error, "error");
68}
69const tailscaleStatusJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.100.100.100","fd7a:115c:a1e0::1","192.168.1.20"]}}`;
70const tailscaleStatusWithSingleIpJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.90.1.2"]}}`;
71
72const tailscaleServeStatusJson = JSON.stringify({
73 TCP: { "10010": { HTTPS: true } },
74 Web: {
75 "desktop.tail.ts.net:10010": {
76 Handlers: { "/": { Proxy: "http://127.0.0.1:3773" } },
77 },
78 "desktop.tail.ts.net:443": {
79 Handlers: { "/": { Proxy: "http://127.0.0.1:5173" } },
80 },
81 },
82});
83
84function mockHandle(result: { stdout?: string; stderr?: string; code?: number }) {
85 return ChildProcessSpawner.makeHandle({
86 pid: ChildProcessSpawner.ProcessId(1),
87 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
88 isRunning: Effect.succeed(false),
89 kill: () => Effect.void,
90 unref: Effect.succeed(Effect.void),
91 stdin: Sink.drain,
92 stdout: Stream.make(encoder.encode(result.stdout ?? "")),
93 stderr: Stream.make(encoder.encode(result.stderr ?? "")),
94 all: Stream.empty,
95 getInputFd: () => Sink.drain,
96 getOutputFd: () => Stream.empty,
97 });
98}
99
100function neverFinishingMockHandle() {
101 return ChildProcessSpawner.makeHandle({
102 pid: ChildProcessSpawner.ProcessId(1),
103 exitCode: Effect.never,
104 isRunning: Effect.succeed(true),
105 kill: () => Effect.void,
106 unref: Effect.succeed(Effect.void),
107 stdin: Sink.drain,
108 stdout: Stream.empty,
109 stderr: Stream.empty,
110 all: Stream.empty,
111 getInputFd: () => Sink.drain,
112 getOutputFd: () => Stream.empty,
113 });
114}
115
116// The executable name depends on the host platform (`tailscale.exe` on
117// Windows), so pin it: these tests assert the posix spelling.
118function spawnerLayer(spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) {
119 return Layer.merge(
120 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
121 Layer.succeed(HostProcessPlatform, "linux"),
122 );
123}
124
125function mockSpawnerLayer(
126 handler: (
127 command: string,
128 args: ReadonlyArray<string>,
129 ) => { stdout?: string; stderr?: string; code?: number },
130) {
131 return spawnerLayer(
132 ChildProcessSpawner.make((command) => {
133 const childProcess = command as unknown as {
134 readonly command: string;
135 readonly args: ReadonlyArray<string>;
136 };
137 return Effect.succeed(mockHandle(handler(childProcess.command, childProcess.args)));
138 }),
139 );
140}
141
142describe("tailscale", () => {
143 it.effect("detects Tailnet IPv4 addresses", () =>
144 Effect.sync(() => {
145 assert.equal(isTailscaleIpv4Address("100.64.0.1"), true);
146 assert.equal(isTailscaleIpv4Address("100.127.255.254"), true);
147 assert.equal(isTailscaleIpv4Address("100.128.0.1"), false);
148 assert.equal(isTailscaleIpv4Address("192.168.1.44"), false);
149 }),
150 );
151
152 it.effect("parses MagicDNS names from tailscale status", () =>
153 Effect.gen(function* () {
154 const dnsName = yield* parseTailscaleMagicDnsName(tailscaleStatusJson);
155 assert.equal(dnsName, "desktop.tail.ts.net");
156 assert.equal(yield* parseTailscaleMagicDnsName("{}"), null);
157 }),
158 );
159
160 it.effect("parses status facts", () =>
161 Effect.gen(function* () {
162 const status = yield* parseTailscaleStatus(tailscaleStatusJson);
163 assert.deepEqual(status, {
164 magicDnsName: "desktop.tail.ts.net",
165 tailnetIpv4Addresses: ["100.100.100.100"],
166 });
167 }),
168 );
169
170 it.effect("preserves status decoding failures without exposing cause text", () =>
171 Effect.gen(function* () {
172 const error = yield* parseTailscaleStatus("{not-json").pipe(Effect.flip);
173
174 assert.instanceOf(error, TailscaleStatusParseError);
175 assert.equal(error.message, "Failed to decode tailscale status JSON.");
176 assert.isDefined(error.cause);
177 assert.notInclude(error.message, String(error.cause));
178 }),
179 );
180
181 it.effect("builds clean HTTPS base URLs", () =>
182 Effect.sync(() => {
183 assert.equal(
184 buildTailscaleHttpsBaseUrl({ magicDnsName: "desktop.tail.ts.net" }),
185 "https://desktop.tail.ts.net/",
186 );
187 assert.equal(
188 buildTailscaleHttpsBaseUrl({ magicDnsName: "desktop.tail.ts.net", servePort: 8443 }),
189 "https://desktop.tail.ts.net:8443/",
190 );
191 }),
192 );
193
194 it.effect("reads tailscale status through the process spawner service", () => {
195 const layer = mockSpawnerLayer((command, args) => {
196 assert.equal(command, "tailscale");
197 assert.deepEqual(args, ["status", "--json"]);
198 return {
199 stdout: tailscaleStatusWithSingleIpJson,
200 };
201 });
202
203 return Effect.gen(function* () {
204 const status = yield* readTailscaleStatus.pipe(Effect.provide(layer));
205 assert.deepEqual(status, {
206 magicDnsName: "desktop.tail.ts.net",
207 tailnetIpv4Addresses: ["100.90.1.2"],
208 });
209 });
210 });
211
212 it.effect("preserves tailscale spawn failures as causes", () => {
213 const systemCause = new Error("private executable lookup detail");
214 const cause = PlatformError.systemError({
215 _tag: "NotFound",
216 module: "ChildProcess",
217 method: "spawn",
218 cause: systemCause,
219 });
220 const layer = spawnerLayer(ChildProcessSpawner.make(() => Effect.fail(cause)));
221
222 return Effect.gen(function* () {
223 const error = yield* readTailscaleStatus.pipe(Effect.flip, Effect.provide(layer));
224
225 assert.instanceOf(error, TailscaleCommandSpawnError);
226 assert.equal(error.executable, "tailscale");
227 assert.equal(error.subcommand, "status");
228 assert.equal(error.argumentCount, 2);
229 assert.strictEqual(error.cause, cause);
230 assert.equal(error.message, "Failed to spawn tailscale status.");
231 assert.notInclude(error.message, systemCause.message);
232 });
233 });
234
235 it.effect("turns spawn defects into typed spawn failures", () => {
236 // A non-directory entry on PATH makes node's spawn throw ENOTDIR
237 // synchronously. The platform spawner calls `NodeChildProcess.spawn` from
238 // inside an `Effect.callback` registration, so that throw arrives as a
239 // defect rather than a typed error - the shape reproduced here.
240 const defect = Object.assign(new Error("spawn tailscale ENOTDIR"), { code: "ENOTDIR" });
241 const layer = spawnerLayer(
242 ChildProcessSpawner.make(() =>
243 Effect.callback<never, never>(() => {
244 throw defect;
245 }),
246 ),
247 );
248
249 return Effect.gen(function* () {
250 const statusError = yield* readTailscaleStatus.pipe(Effect.flip, Effect.provide(layer));
251 assert.instanceOf(statusError, TailscaleCommandSpawnError);
252 assert.equal(statusError.subcommand, "status");
253 assert.strictEqual(statusError.cause, defect);
254
255 const serveError = yield* ensureTailscaleServe({ localPort: 13773, servePort: 8443 }).pipe(
256 Effect.flip,
257 Effect.provide(layer),
258 );
259 assert.instanceOf(serveError, TailscaleCommandSpawnError);
260 assert.equal(serveError.subcommand, "serve");
261 assert.strictEqual(serveError.cause, defect);
262
263 // What callers actually rely on: the desktop endpoint providers recover
264 // with `Effect.orElseSucceed`, which only sees the typed error channel.
265 const degraded = yield* readTailscaleStatus.pipe(
266 Effect.orElseSucceed(() => null),
267 Effect.provide(layer),
268 );
269 assert.equal(degraded, null);
270 });
271 });
272
273 it.effect("keeps nonzero exit diagnostics structured", () => {
274 const layer = mockSpawnerLayer(() => ({
275 code: 7,
276 stderr: "not logged in tskey-auth-secret-token-value",
277 }));
278
279 return Effect.gen(function* () {
280 const error = yield* readTailscaleStatus.pipe(Effect.flip, Effect.provide(layer));
281
282 assert.instanceOf(error, TailscaleCommandExitError);
283 assert.equal(error.executable, "tailscale");
284 assert.equal(error.subcommand, "status");
285 assert.equal(error.argumentCount, 2);
286 assert.equal(error.exitCode, 7);
287 assert.equal(error.stdoutLength, 0);
288 assert.equal(error.stderrLength, 43);
289 assert.notProperty(error, "command");
290 assert.notProperty(error, "stderr");
291 assert.notInclude(error.message, "tskey-auth-secret-token-value");
292 assert.equal(error.message, "tailscale status exited with code 7.");
293 assert.equal(error.stderrDiagnostic, "not-logged-in");
294 assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
295 });
296 });
297
298 it.effect("classifies unrecognized stderr without quoting it", () => {
299 const layer = mockSpawnerLayer(() => ({
300 code: 3,
301 stderr: "something novel went wrong for node fluffy-badger tskey-auth-secret-token-value",
302 }));
303
304 return Effect.gen(function* () {
305 const error = yield* readTailscaleStatus.pipe(Effect.flip, Effect.provide(layer));
306
307 assert.instanceOf(error, TailscaleCommandExitError);
308 // Unmatched stderr degrades to "unknown" rather than passing text
309 // through — that fallback is what keeps novel output from leaking.
310 assert.equal(error.stderrDiagnostic, "unknown");
311 assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
312 assertCarriesNoSecret(error, "fluffy-badger");
313 });
314 });
315
316 it.effect("times out tailscale status through TestClock", () => {
317 const layer = Layer.merge(
318 TestClock.layer(),
319 spawnerLayer(ChildProcessSpawner.make(() => Effect.succeed(neverFinishingMockHandle()))),
320 );
321
322 return Effect.gen(function* () {
323 const fiber = yield* readTailscaleStatus.pipe(Effect.flip, Effect.forkScoped);
324 yield* Effect.yieldNow;
325 yield* TestClock.adjust(TAILSCALE_STATUS_TIMEOUT);
326 const error = yield* Fiber.join(fiber);
327
328 assert.instanceOf(error, TailscaleCommandTimeoutError);
329 assert.equal(error.executable, "tailscale");
330 assert.equal(error.subcommand, "status");
331 assert.equal(error.argumentCount, 2);
332 assert.equal(error.timeoutMs, 1_500);
333 assert.isTrue(Cause.isTimeoutError(error.cause));
334 assert.equal(error.message, "tailscale status timed out after 1500ms.");
335 }).pipe(Effect.provide(layer));
336 });
337
338 it.effect("configures tailscale serve through the process spawner service", () => {
339 const layer = mockSpawnerLayer((command, args) => {
340 assert.equal(command, "tailscale");
341 assert.deepEqual(args, ["serve", "--bg", "--https=8443", "http://127.0.0.1:13773"]);
342 return {};
343 });
344
345 return ensureTailscaleServe({ localPort: 13773, servePort: 8443 }).pipe(Effect.provide(layer));
346 });
347
348 it.effect("retains tailscale serve exit diagnostics", () => {
349 const layer = mockSpawnerLayer(() => ({
350 code: 1,
351 stderr: "serve permission denied tskey-auth-secret-token-value",
352 }));
353
354 return Effect.gen(function* () {
355 const error = yield* ensureTailscaleServe({ localPort: 13773, servePort: 8443 }).pipe(
356 Effect.flip,
357 Effect.provide(layer),
358 );
359
360 assert.instanceOf(error, TailscaleCommandExitError);
361 assert.equal(error.executable, "tailscale");
362 assert.equal(error.subcommand, "serve");
363 assert.equal(error.argumentCount, 4);
364 assert.equal(error.exitCode, 1);
365 assert.equal(error.stderrLength, 53);
366 assert.notProperty(error, "command");
367 assert.notProperty(error, "stderr");
368 assert.notInclude(error.message, "tskey-auth-secret-token-value");
369 // The diagnostic classifies the failure without quoting stderr, so the
370 // key cannot reach a log through it either.
371 assert.equal(error.stderrDiagnostic, "permission-denied");
372 assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
373 });
374 });
375
376 it.effect("disables tailscale serve through the process spawner service", () => {
377 const commands: {
378 readonly command: string;
379 readonly args: ReadonlyArray<string>;
380 }[] = [];
381 const layer = mockSpawnerLayer((command, args) => {
382 commands.push({ command, args });
383 assert.equal(command, "tailscale");
384 assert.deepEqual(args, ["serve", "--https=8443", "off"]);
385 return {};
386 });
387
388 return Effect.gen(function* () {
389 yield* disableTailscaleServe({ servePort: 8443 }).pipe(Effect.provide(layer));
390 assert.deepEqual(commands, [
391 { command: "tailscale", args: ["serve", "--https=8443", "off"] },
392 ]);
393 });
394 });
395
396 it.effect("reads the serve mapping's local target", () => {
397 const layer = mockSpawnerLayer((command, args) => {
398 assert.equal(command, "tailscale");
399 assert.deepEqual(args, ["serve", "status", "--json"]);
400 return { stdout: tailscaleServeStatusJson };
401 });
402
403 return Effect.gen(function* () {
404 assert.deepEqual(
405 yield* readTailscaleServeTarget({ servePort: 10010 }).pipe(Effect.provide(layer)),
406 {
407 localHost: "127.0.0.1",
408 localPort: 3773,
409 },
410 );
411 // A serve port with no mapping must read as unclaimed, not as the
412 // mapping that happens to sit on another port.
413 assert.equal(
414 yield* readTailscaleServeTarget({ servePort: 8443 }).pipe(Effect.provide(layer)),
415 null,
416 );
417 });
418 });
419
420 it.effect("defaults the serve port to HTTPS", () =>
421 Effect.gen(function* () {
422 assert.deepEqual(yield* parseTailscaleServeTarget(tailscaleServeStatusJson), {
423 localHost: "127.0.0.1",
424 localPort: 5173,
425 });
426 assert.equal(yield* parseTailscaleServeTarget("{}", { servePort: 10010 }), null);
427 }),
428 );
429});