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

tailscale.test.ts

401 lines14.6 KB

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