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

tailscale.test.ts

411 lines15.4 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as Deferred from "effect/Deferred";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Fiber from "effect/Fiber";
7import * as Layer from "effect/Layer";
8import * as Sink from "effect/Sink";
9import * as Stream from "effect/Stream";
10import { HttpClient, HttpClientResponse } from "effect/http";
11import * as TestClock from "effect/testing/TestClock";
12import { ChildProcessSpawner } from "effect/process";
13import * as HostProcess from "@t3tools/shared/HostProcess";
14​
15import {
16 ensureTailscaleServe,
17 parseTailscaleExitNode,
18 parseTailscaleServeRoutesTo,
19 parseTailscaleSshEnabled,
20 parseTailscaleStatus,
21 probeTailscaleHttpsEndpoint,
22 readTailscaleSshEnabled,
23 readTailscaleStatus,
24 TailscaleCommandExitError,
25 TailscaleCommandSpawnError,
26 TailscaleStatusParseError,
27} from "./tailscale.ts";
28​
29const encoder = new TextEncoder();
30​
31function assertCarriesNoSecret(error: object, secret: string): void {
32 const seen = new WeakSet<object>();
33​
34 const walk = (value: unknown, path: string): void => {
35 if (typeof value === "string") {
36 assert.notInclude(value, secret, `${path} leaked stderr`);
37 return;
38 }
39 if (typeof value !== "object" || value === null || seen.has(value)) {
40 return;
41 }
42 seen.add(value);
43​
44 if (Array.isArray(value)) {
45 value.forEach((entry, index) => walk(entry, `${path}[${String(index)}]`));
46 return;
47 }
48 // `message` and `cause` are getters on Error subclasses, so they are not
49 // own enumerable properties and Object.entries alone would skip them.
50 walk((value as { message?: unknown }).message, `${path}.message`);
51 walk((value as { cause?: unknown }).cause, `${path}.cause`);
52 for (const [key, nested] of Object.entries(value)) {
53 walk(nested, `${path}.${key}`);
54 }
55 };
56​
57 walk(error, "error");
59const tailscaleStatusJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.100.100.100","fd7a:115c:a1e0::1","192.168.1.20"]}}`;
60​
61function mockHandle(result: { stdout?: string; stderr?: string; code?: number }) {
62 return ChildProcessSpawner.makeHandle({
63 pid: ChildProcessSpawner.ProcessId(1),
64 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
65 isRunning: Effect.succeed(false),
66 kill: () => Effect.void,
67 unref: Effect.succeed(Effect.void),
68 stdin: Sink.drain,
69 stdout: Stream.make(encoder.encode(result.stdout ?? "")),
70 stderr: Stream.make(encoder.encode(result.stderr ?? "")),
71 all: Stream.empty,
72 getInputFd: () => Sink.drain,
73 getOutputFd: () => Stream.empty,
74 });
76​
77// The executable name depends on the host platform (`tailscale.exe` on
78// Windows), so pin it: these tests assert the posix spelling.
79function layerSpawner(spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) {
80 return Layer.merge(
81 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
82 Layer.succeed(HostProcess.Platform, "linux"),
83 );
85​
86function layerMockSpawner(
87 handler: (
88 command: string,
89 args: ReadonlyArray<string>,
90 ) => { stdout?: string; stderr?: string; code?: number },
91) {
92 return layerSpawner(
93 ChildProcessSpawner.make((command) => {
94 const childProcess = command as unknown as {
95 readonly command: string;
96 readonly args: ReadonlyArray<string>;
97 };
98 return Effect.succeed(mockHandle(handler(childProcess.command, childProcess.args)));
99 }),
100 );
102​
103describe("tailscale", () => {
104 it.effect("does not treat a non-T3 response on the HTTPS probe path as reachable", () =>
105 Effect.gen(function* () {
106 for (const [body, status] of [
107 ["<!doctype html><title>Other application</title>", 200],
108 [null, 204],
109 ] as const) {
110 const reachable = yield* probeTailscaleHttpsEndpoint({
111 baseUrl: "https://desktop.example.ts.net",
112 }).pipe(
113 Effect.provideService(
114 HttpClient.HttpClient,
115 HttpClient.make((request) =>
116 Effect.succeed(HttpClientResponse.fromWeb(request, new Response(body, { status }))),
117 ),
118 ),
119 );
120 assert.isFalse(reachable, `HTTP ${status} without a T3 descriptor`);
121 }
122 }),
123 );
124​
125 it("finds the Serve routes that forward to the bound address, and only those", () => {
126 const status = JSON.stringify({
127 TCP: {
128 "443": { HTTPS: true },
129 "7000": { TCPForward: "127.0.0.1:3773" },
130 "7001": { TCPForward: "127.0.0.2:3773" },
131 "80": { TCPForward: "unix:/run/app.sock" },
132 },
133 Web: {
134 "box.tailnet.ts.net:443": {
135 Handlers: {
136 "/t3": { Proxy: "http://127.0.0.1:3773" },
137 "/dashboard": { Proxy: "http://127.0.0.1:9000" },
138 },
139 },
140 "box.tailnet.ts.net:8443": { Handlers: { "/": { Proxy: "http://127.0.0.1:5173" } } },
141 "box.tailnet.ts.net:10000": {
142 Handlers: {
143 // Another service on another loopback address, and one on the other family.
144 "/a": { Proxy: "http://127.0.0.2:3773" },
145 "/b": { Proxy: "http://[::1]:3773" },
146 "/c": { Proxy: "http://192.168.1.5:3773" },
147 "/d": { Proxy: "http://0.0.0.0:3773" },
148 "/e": { Proxy: "http://[::ffff:127.0.0.1]:3773" },
149 "/f": { Proxy: "http://localhost:3773" },
150 // Shorthand Tailscale expands when it proxies.
151 "/g": { Proxy: "3773" },
152 "/h": { Proxy: "localhost:3773" },
153 "/i": { Proxy: "http://[::]:3773" },
154 // A name can resolve to any address, the bound one included.
155 "/j": { Proxy: "http://ip6-localhost:3773" },
156 // Go resolves these as names; a WHATWG URL rejects the first and rewrites the second.
157 "/k": { Proxy: "http://box.1:3773" },
158 "/l": { Proxy: "http://127.1:3773" },
159 "/m": { Proxy: "unix:/run/app.sock" },
160 // Credentials before the host, and IPv6 written out in full, still dial here.
161 "/n": { Proxy: "http://user:pass@127.0.0.1:3773" },
162 "/o": { Proxy: "http://[0:0:0:0:0:ffff:7f00:1]:3773" },
163 "/p": { Proxy: "http://127.0.0.1:03773" },
164 },
165 },
166 },
167 Services: {
168 "svc:t3": {
169 Web: {
170 "t3.tailnet.ts.net:443": { Handlers: { "/": { Proxy: "http://127.0.0.1:3773" } } },
171 },
172 },
173 },
174 Foreground: {
175 session1: { TCP: { "9000": { TCPForward: "localhost:3773" } } },
176 },
177 });
178 assert.deepEqual(parseTailscaleServeRoutesTo(status, { host: "127.0.0.1", port: 3773 }), [
179 { servePort: 7000 },
180 { servePort: 443, mount: "/t3", host: "box.tailnet.ts.net" },
181 // `localhost` and `[::]` can dial either loopback, so they might be another service's.
182 ...(
183 [
184 ["/d", undefined],
185 ["/e", undefined],
186 ["/f", "localhost"],
187 ["/g", undefined],
188 ["/h", "localhost"],
189 ["/i", "[::]"],
190 ["/j", "ip6-localhost"],
191 ["/k", "box.1"],
192 ["/l", "127.1"],
193 ["/n", undefined],
194 ["/o", undefined],
195 ["/p", undefined],
196 ] as const
197 ).map(([mount, ambiguous]) => ({
198 servePort: 10000,
199 mount,
200 host: "box.tailnet.ts.net",
201 ...(ambiguous === undefined ? {} : { ambiguous }),
202 })),
203 { servePort: 443, mount: "/", host: "t3.tailnet.ts.net", owner: "svc:t3" },
204 { servePort: 9000, ambiguous: "localhost", owner: "foreground" },
205 ]);
206 assert.deepEqual(
207 parseTailscaleServeRoutesTo(
208 JSON.stringify({
209 Web: { "box:443": { Handlers: { "/": { Proxy: "http://127.0.0.1" } } } },
210 }),
211 { host: "127.0.0.1", port: 80 },
212 ),
213 [{ servePort: 443, mount: "/", host: "box" }],
214 );
215 assert.deepEqual(parseTailscaleServeRoutesTo("{}", { host: "127.0.0.1", port: 3773 }), []);
216 assert.deepEqual(parseTailscaleServeRoutesTo("null", { host: "127.0.0.1", port: 3773 }), []);
217 assert.isUndefined(parseTailscaleServeRoutesTo("not json", { host: "127.0.0.1", port: 3773 }));
218 });
219​
220 it.effect("parses status facts", () =>
221 Effect.gen(function* () {
222 const status = yield* parseTailscaleStatus(tailscaleStatusJson);
223 assert.deepEqual(status, {
224 magicDnsName: "desktop.tail.ts.net",
225 tailnetIpv4Addresses: ["100.100.100.100"],
226 httpsServeEnabled: null,
227 });
228 }),
229 );
230​
231 it.effect("names the exit node in use", () =>
232 Effect.gen(function* () {
233 const inUse = yield* parseTailscaleExitNode(
234 JSON.stringify({
235 ExitNodeStatus: { ID: "nX", Online: true, TailscaleIPs: ["100.101.102.103/32"] },
236 Peer: {
237 "nodekey:a": { HostName: "laptop", DNSName: "laptop.tail.ts.net.", ExitNode: false },
238 "nodekey:b": {
239 HostName: "raspberrypi",
240 DNSName: "home-pi.tail.ts.net.",
241 ExitNode: true,
242 },
243 },
244 }),
245 );
246 assert.deepEqual(inUse, { name: "home-pi", online: true });
247​
248 const unnamed = yield* parseTailscaleExitNode(`{"ExitNodeStatus":{"Online":false}}`);
249 assert.deepEqual(unnamed, { name: null, online: false });
250​
251 assert.equal(yield* parseTailscaleExitNode(tailscaleStatusJson), null);
252 }),
253 );
254​
255 it.effect("reads the HTTPS serve capability from the status capability map", () =>
256 Effect.gen(function* () {
257 const enabled = yield* parseTailscaleStatus(
258 `{"Self":{"CapMap":{"https":null,"funnel":null}}}`,
259 );
260 assert.equal(enabled.httpsServeEnabled, true);
261​
262 const disabled = yield* parseTailscaleStatus(`{"Self":{"CapMap":{"funnel":null}}}`);
263 assert.equal(disabled.httpsServeEnabled, false);
264 }),
265 );
266​
267 it.effect("reads Tailscale SSH enablement from local prefs", () => {
268 const prefsJson =
269 '{\n\t"ControlURL": "https://controlplane.tailscale.com",\n\t"RunSSH": true,\n\t"WantRunning": true\n}\n';
270 const layer = layerMockSpawner((command, args) => {
271 assert.equal(command, "tailscale");
272 assert.deepEqual(args, ["debug", "prefs"]);
273 return { stdout: prefsJson };
274 });
275​
276 return Effect.gen(function* () {
277 assert.isTrue(yield* readTailscaleSshEnabled.pipe(Effect.provide(layer)));
278 assert.isFalse(yield* parseTailscaleSshEnabled('{"RunSSH":false,"WantRunning":true}'));
279 assert.isFalse(yield* parseTailscaleSshEnabled('{"RunSSH":true,"WantRunning":false}'));
280 assert.isFalse(yield* parseTailscaleSshEnabled("{}"));
281 const error = yield* parseTailscaleSshEnabled("{not-json").pipe(Effect.flip);
282 assert.instanceOf(error, TailscaleStatusParseError);
283 });
284 });
285​
286 it.effect("turns spawn defects into typed spawn failures", () => {
287 // A non-directory entry on PATH makes node's spawn throw ENOTDIR
288 // synchronously. The platform spawner calls `NodeChildProcess.spawn` from
289 // inside an `Effect.callback` registration, so that throw arrives as a
290 // defect rather than a typed error - the shape reproduced here.
291 const defect = Object.assign(new Error("spawn tailscale ENOTDIR"), { code: "ENOTDIR" });
292 const layer = layerSpawner(
293 ChildProcessSpawner.make(() =>
294 Effect.callback<never, never>(() => {
295 throw defect;
296 }),
297 ),
298 );
299​
300 return Effect.gen(function* () {
301 const statusError = yield* readTailscaleStatus.pipe(Effect.flip, Effect.provide(layer));
302 assert.instanceOf(statusError, TailscaleCommandSpawnError);
303 assert.equal(statusError.subcommand, "status");
304 assert.strictEqual(statusError.cause, defect);
305​
306 const serveError = yield* ensureTailscaleServe({ localPort: 13773, servePort: 8443 }).pipe(
307 Effect.flip,
308 Effect.provide(layer),
309 );
310 assert.instanceOf(serveError, TailscaleCommandSpawnError);
311 assert.equal(serveError.subcommand, "serve");
312 assert.strictEqual(serveError.cause, defect);
313​
314 const degraded = yield* readTailscaleStatus.pipe(
315 Effect.orElseSucceed(() => null),
316 Effect.provide(layer),
317 );
318 assert.equal(degraded, null);
319 });
320 });
321​
322 it.effect("keeps nonzero exit diagnostics structured", () => {
323 const layer = layerMockSpawner(() => ({
324 code: 7,
325 stderr: "not logged in tskey-auth-secret-token-value",
326 }));
327​
328 return Effect.gen(function* () {
329 const error = yield* readTailscaleStatus.pipe(Effect.flip, Effect.provide(layer));
330​
331 assert.instanceOf(error, TailscaleCommandExitError);
332 assert.equal(error.executable, "tailscale");
333 assert.equal(error.subcommand, "status");
334 assert.equal(error.argumentCount, 2);
335 assert.equal(error.exitCode, 7);
336 assert.equal(error.stdoutLength, 0);
337 assert.equal(error.stderrLength, 43);
338 assert.notProperty(error, "command");
339 assert.notProperty(error, "stderr");
340 assert.notInclude(error.message, "tskey-auth-secret-token-value");
341 assert.equal(error.message, "tailscale status exited with code 7.");
342 assert.equal(error.stderrDiagnostic, "not-logged-in");
343 assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
344 });
345 });
346​
347 // regression: #34736 - a full stdout pipe blocks the child before it exits.
348 it.effect("drains serve stdout so a long success summary does not time out", () =>
349 Effect.gen(function* () {
350 const stdoutDrained = yield* Deferred.make<void>();
351 const layer = layerSpawner(
352 ChildProcessSpawner.make(() =>
353 Effect.succeed(
354 ChildProcessSpawner.makeHandle({
355 pid: ChildProcessSpawner.ProcessId(1),
356 exitCode: Deferred.await(stdoutDrained).pipe(
357 Effect.as(ChildProcessSpawner.ExitCode(0)),
358 ),
359 isRunning: Effect.succeed(true),
360 kill: () => Effect.void,
361 unref: Effect.succeed(Effect.void),
362 stdin: Sink.drain,
363 stdout: Stream.make(encoder.encode("https://example.ts.net/\n")).pipe(
364 Stream.ensuring(Deferred.succeed(stdoutDrained, undefined)),
365 ),
366 stderr: Stream.empty,
367 all: Stream.empty,
368 getInputFd: () => Sink.drain,
369 getOutputFd: () => Stream.empty,
370 }),
371 ),
372 ),
373 );
374​
375 const fiber = yield* ensureTailscaleServe({ localPort: 3773 }).pipe(
376 Effect.provide(layer),
377 Effect.exit,
378 Effect.forkChild,
379 );
380 yield* TestClock.adjust("11 seconds");
381 const exit = yield* Fiber.join(fiber);
382 assert.isTrue(Exit.isSuccess(exit), String(exit));
383 }),
384 );
385​
386 // regression: #21609 - without forceKillAfter a timed-out probe only gets
387 // SIGTERM, so a group member that ignores it outlives the call.
388 it.effect("escalates timed-out probes to SIGKILL", () => {
389 const killGraces: Array<number | undefined> = [];
390 const layer = layerSpawner(
391 ChildProcessSpawner.make((command) => {
392 if (command._tag === "StandardCommand") {
393 const { forceKillAfter } = command.options;
394 killGraces.push(
395 forceKillAfter === undefined
396 ? undefined
397 : Duration.toMillis(Duration.fromInputUnsafe(forceKillAfter)),
398 );
399 }
400 return Effect.succeed(mockHandle({ stdout: "{}" }));
401 }),
402 );
403​
404 return Effect.gen(function* () {
405 yield* readTailscaleStatus.pipe(Effect.provide(layer));
406 yield* readTailscaleSshEnabled.pipe(Effect.provide(layer));
407 yield* ensureTailscaleServe({ localPort: 45_678 }).pipe(Effect.provide(layer));
408 assert.deepEqual(killGraces, [500, 500, 500]);
409 });
410 });
411});