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

tailscale.test.ts

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