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

tailscale.test.ts

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