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

tailscale.test.ts

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