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

tailscale.test.ts

345 lines13.0 KB

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